-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Aircraft.cs
1393 lines (1108 loc) · 45 KB
/
Aircraft.cs
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
#region Copyright & License Information
/*
* Copyright (c) The OpenRA Developers and Contributors
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Activities;
using OpenRA.Mods.Common.Activities;
using OpenRA.Mods.Common.Orders;
using OpenRA.Primitives;
using OpenRA.Support;
using OpenRA.Traits;
namespace OpenRA.Mods.Common.Traits
{
public enum IdleBehaviorType
{
None,
Land,
ReturnToBase,
LeaveMap,
LeaveMapAtClosestEdge
}
public class AircraftInfo : PausableConditionalTraitInfo, IPositionableInfo, IFacingInfo, IMoveInfo, ICruiseAltitudeInfo,
IActorPreviewInitInfo, IEditorActorOptions
{
[Desc("Behavior when aircraft becomes idle. Options are Land, ReturnToBase, LeaveMap, and None.",
"'Land' will behave like 'None' (hover or circle) if a suitable landing site is not available.")]
public readonly IdleBehaviorType IdleBehavior = IdleBehaviorType.None;
public readonly WDist CruiseAltitude = new(1280);
[Desc("Whether the aircraft can be repulsed.")]
public readonly bool Repulsable = true;
[Desc("The distance it tries to maintain from other aircraft if repulsable.")]
public readonly WDist IdealSeparation = new(1706);
[Desc("The speed at which the aircraft is repulsed from other aircraft. Specify -1 for normal movement speed.")]
public readonly int RepulsionSpeed = -1;
public readonly WAngle InitialFacing = WAngle.Zero;
[Desc("Speed at which the actor turns.")]
public readonly WAngle TurnSpeed = new(512);
[Desc("Turn speed to apply when aircraft flies in circles while idle. Defaults to TurnSpeed if undefined.")]
public readonly WAngle? IdleTurnSpeed = null;
[Desc("When flying if the difference between current facing and desired facing is less than this value, don't turn. This prevents visual jitter.")]
public readonly WAngle TurnDeadzone = new(2);
[Desc("Maximum flight speed when cruising.")]
public readonly int Speed = 1;
[Desc("If non-negative, force the aircraft to move in circles at this speed when idle (a speed of 0 means don't move), ignoring CanHover.")]
public readonly int IdleSpeed = -1;
[Desc("Body pitch when flying forwards. Only relevant for voxel aircraft.")]
public readonly WAngle Pitch = WAngle.Zero;
[Desc("Pitch steps to apply each tick when starting/stopping.")]
public readonly WAngle PitchSpeed = WAngle.Zero;
[Desc("Body roll when turning. Only relevant for voxel aircraft.")]
public readonly WAngle Roll = WAngle.Zero;
[Desc("Body roll to apply when aircraft flies in circles while idle. Defaults to Roll if undefined. Only relevant for voxel aircraft.")]
public readonly WAngle? IdleRoll = null;
[Desc("Roll steps to apply each tick when turning.")]
public readonly WAngle RollSpeed = WAngle.Zero;
[Desc("Minimum altitude where this aircraft is considered airborne.")]
public readonly int MinAirborneAltitude = 1;
public readonly HashSet<string> LandableTerrainTypes = new();
[Desc("Can the actor be ordered to move in to shroud?")]
public readonly bool MoveIntoShroud = true;
[Desc("e.g. crate, wall, infantry")]
public readonly BitSet<CrushClass> Crushes = default;
[Desc("Types of damage that are caused while crushing. Leave empty for no damage types.")]
public readonly BitSet<DamageType> CrushDamageTypes = default;
[VoiceReference]
public readonly string Voice = "Action";
[Desc("Color to use for the target line for regular move orders.")]
public readonly Color TargetLineColor = Color.Green;
[GrantedConditionReference]
[Desc("The condition to grant to self while airborne.")]
public readonly string AirborneCondition = null;
[GrantedConditionReference]
[Desc("The condition to grant to self while at cruise altitude.")]
public readonly string CruisingCondition = null;
[Desc("Can the actor hover in place mid-air? If not, then the actor will have to remain in motion (circle around).")]
public readonly bool CanHover = false;
[Desc("Can the actor immediately change direction without turning first (doesn't need to fly in a curve)?")]
public readonly bool CanSlide = false;
[Desc("Does the actor land and take off vertically?")]
public readonly bool VTOL = false;
[Desc("Does this VTOL actor need to turn before landing (on terrain)?")]
public readonly bool TurnToLand = false;
[Desc("Does this actor automatically take off after resupplying?")]
public readonly bool TakeOffOnResupply = false;
[Desc("Does this actor automatically take off after creation?")]
public readonly bool TakeOffOnCreation = true;
[Desc("Can this actor be given an explicit land order using the force-move modifier?")]
public readonly bool CanForceLand = true;
[Desc("Altitude at which the aircraft considers itself landed.")]
public readonly WDist LandAltitude = WDist.Zero;
[Desc("Range to search for an alternative landing location if the ordered cell is blocked.")]
public readonly WDist LandRange = WDist.FromCells(5);
[Desc("How fast this actor ascends or descends during horizontal movement.")]
public readonly WAngle MaximumPitch = WAngle.FromDegrees(10);
[Desc("How fast this actor ascends or descends when moving vertically only (vertical take off/landing or hovering towards CruiseAltitude).")]
public readonly WDist AltitudeVelocity = new(43);
[Desc("Sounds to play when the actor is taking off.")]
public readonly string[] TakeoffSounds = Array.Empty<string>();
[Desc("Sounds to play when the actor is landing.")]
public readonly string[] LandingSounds = Array.Empty<string>();
[Desc("The distance of the resupply base that the aircraft will wait for its turn.")]
public readonly WDist WaitDistanceFromResupplyBase = new(3072);
[Desc("The number of ticks that a airplane will wait to make a new search for an available airport.")]
public readonly int NumberOfTicksToVerifyAvailableAirport = 150;
[Desc("Facing to use for actor previews (map editor, color picker, etc)")]
public readonly WAngle PreviewFacing = new(384);
[Desc("Display order for the facing slider in the map editor")]
public readonly int EditorFacingDisplayOrder = 3;
[ConsumedConditionReference]
[Desc("Boolean expression defining the condition under which the regular (non-force) move cursor is disabled.")]
public readonly BooleanExpression RequireForceMoveCondition = null;
[CursorReference]
[Desc("Cursor to display when a move order can be issued at target location.")]
public readonly string Cursor = "move";
[CursorReference]
[Desc("Cursor to display when a move order cannot be issued at target location.")]
public readonly string BlockedCursor = "move-blocked";
[CursorReference]
[Desc("Cursor to display when able to land at target building.")]
public readonly string EnterCursor = "enter";
[CursorReference]
[Desc("Cursor to display when unable to land at target building.")]
public readonly string EnterBlockedCursor = "enter-blocked";
public WAngle GetInitialFacing() { return InitialFacing; }
public WDist GetCruiseAltitude() { return CruiseAltitude; }
public Color GetTargetLineColor() { return TargetLineColor; }
public override object Create(ActorInitializer init) { return new Aircraft(init, this); }
IEnumerable<ActorInit> IActorPreviewInitInfo.ActorPreviewInits(ActorInfo ai, ActorPreviewType type)
{
yield return new FacingInit(PreviewFacing);
}
public IReadOnlyDictionary<CPos, SubCell> OccupiedCells(ActorInfo info, CPos location, SubCell subCell = SubCell.Any) { return new Dictionary<CPos, SubCell>(); }
bool IOccupySpaceInfo.SharesCell => false;
// Used to determine if an aircraft can spawn landed
public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
{
if (!world.Map.Contains(cell))
return false;
var type = world.Map.GetTerrainInfo(cell).Type;
if (!LandableTerrainTypes.Contains(type))
return false;
if (check == BlockedByActor.None)
return true;
// Since aircraft don't share cells, we don't pass the subCell parameter
return !world.ActorMap.GetActorsAt(cell).Any(x => x != ignoreActor);
}
IEnumerable<EditorActorOption> IEditorActorOptions.ActorOptions(ActorInfo ai, World world)
{
yield return new EditorActorSlider("Facing", EditorFacingDisplayOrder, 0, 1023, 8,
actor =>
{
var init = actor.GetInitOrDefault<FacingInit>(this);
return (init != null ? init.Value : InitialFacing).Angle;
},
(actor, value) => actor.ReplaceInit(new FacingInit(new WAngle((int)value))));
}
}
public class Aircraft : PausableConditionalTrait<AircraftInfo>, ITick, ISync, IFacing, IPositionable, IMove,
INotifyAddedToWorld, INotifyRemovedFromWorld, INotifyActorDisposing, INotifyBecomingIdle, ICreationActivity,
IActorPreviewInitModifier, IDeathActorInitModifier, IIssueDeployOrder, IIssueOrder, IResolveOrder, IOrderVoice
{
readonly Actor self;
Repairable repairable;
Rearmable rearmable;
IAircraftCenterPositionOffset[] positionOffsets;
IDisposable reservation;
IEnumerable<int> speedModifiers;
INotifyMoving[] notifyMoving;
INotifyCenterPositionChanged[] notifyCenterPositionChanged;
IOverrideAircraftLanding overrideAircraftLanding;
[Sync]
public WAngle Facing
{
get => Orientation.Yaw;
set => Orientation = Orientation.WithYaw(value);
}
public WAngle Pitch
{
get => Orientation.Pitch;
set => Orientation = Orientation.WithPitch(value);
}
public WAngle Roll
{
get => Orientation.Roll;
set => Orientation = Orientation.WithRoll(value);
}
public WRot Orientation { get; private set; }
[Sync]
public WPos CenterPosition { get; private set; }
public CPos TopLeft => self.World.Map.CellContaining(CenterPosition);
public WAngle TurnSpeed => IsTraitDisabled || IsTraitPaused ? WAngle.Zero : Info.TurnSpeed;
public WAngle? IdleTurnSpeed => IsTraitDisabled || IsTraitPaused ? null : Info.IdleTurnSpeed;
public WAngle GetTurnSpeed(bool isIdleTurn)
{
// A MovementSpeed of zero indicates either a speed modifier of zero percent or that the trait is paused or disabled.
// Bail early in that case.
if ((isIdleTurn && IdleMovementSpeed == 0) || MovementSpeed == 0)
return WAngle.Zero;
var turnSpeed = isIdleTurn ? IdleTurnSpeed ?? TurnSpeed : TurnSpeed;
return new WAngle(Util.ApplyPercentageModifiers(turnSpeed.Angle, speedModifiers).Clamp(1, 1024));
}
public Actor ReservedActor { get; private set; }
public bool MayYieldReservation { get; private set; }
public bool ForceLanding { get; private set; }
(CPos, SubCell)[] landingCells = Array.Empty<(CPos, SubCell)>();
public bool RequireForceMove;
readonly int creationActivityDelay;
readonly bool creationByMap;
readonly CPos[] creationRallyPoint;
bool notify = true;
public static WPos GroundPosition(Actor self)
{
return self.CenterPosition - new WVec(WDist.Zero, WDist.Zero, self.World.Map.DistanceAboveTerrain(self.CenterPosition));
}
public bool AtLandAltitude => self.World.Map.DistanceAboveTerrain(GetPosition()) == LandAltitude;
bool airborne;
bool cruising;
int airborneToken = Actor.InvalidConditionToken;
int cruisingToken = Actor.InvalidConditionToken;
MovementType movementTypes;
WPos cachedPosition;
WAngle cachedFacing;
public Aircraft(ActorInitializer init, AircraftInfo info)
: base(info)
{
self = init.Self;
var locationInit = init.GetOrDefault<LocationInit>();
var centerPositionInit = init.GetOrDefault<CenterPositionInit>();
if (locationInit != null || centerPositionInit != null)
{
var pos = centerPositionInit?.Value ?? self.World.Map.CenterOfCell(locationInit.Value);
creationByMap = init.Contains<SpawnedByMapInit>();
SetPosition(self, pos);
}
Facing = init.GetValue<FacingInit, WAngle>(Info.InitialFacing);
creationActivityDelay = init.GetValue<CreationActivityDelayInit, int>(0);
creationRallyPoint = init.GetOrDefault<RallyPointInit>()?.Value;
}
public WDist LandAltitude
{
get
{
var alt = Info.LandAltitude;
foreach (var offset in positionOffsets)
alt -= new WDist(offset.PositionOffset.Z);
return alt;
}
}
public WPos GetPosition()
{
var pos = self.CenterPosition;
foreach (var offset in positionOffsets)
pos += offset.PositionOffset;
return pos;
}
public override IEnumerable<VariableObserver> GetVariableObservers()
{
foreach (var observer in base.GetVariableObservers())
yield return observer;
if (Info.RequireForceMoveCondition != null)
yield return new VariableObserver(RequireForceMoveConditionChanged, Info.RequireForceMoveCondition.Variables);
}
void RequireForceMoveConditionChanged(Actor self, IReadOnlyDictionary<string, int> conditions)
{
RequireForceMove = Info.RequireForceMoveCondition.Evaluate(conditions);
}
protected override void Created(Actor self)
{
repairable = self.TraitOrDefault<Repairable>();
rearmable = self.TraitOrDefault<Rearmable>();
speedModifiers = self.TraitsImplementing<ISpeedModifier>().ToArray().Select(sm => sm.GetSpeedModifier());
cachedPosition = self.CenterPosition;
notifyMoving = self.TraitsImplementing<INotifyMoving>().ToArray();
positionOffsets = self.TraitsImplementing<IAircraftCenterPositionOffset>().ToArray();
overrideAircraftLanding = self.TraitOrDefault<IOverrideAircraftLanding>();
notifyCenterPositionChanged = self.TraitsImplementing<INotifyCenterPositionChanged>().ToArray();
base.Created(self);
}
void INotifyAddedToWorld.AddedToWorld(Actor self)
{
AddedToWorld(self);
}
protected virtual void AddedToWorld(Actor self)
{
self.World.AddToMaps(self, this);
var altitude = self.World.Map.DistanceAboveTerrain(CenterPosition);
if (altitude.Length >= Info.MinAirborneAltitude)
OnAirborneAltitudeReached();
if (altitude == Info.CruiseAltitude)
OnCruisingAltitudeReached();
}
void INotifyRemovedFromWorld.RemovedFromWorld(Actor self)
{
RemovedFromWorld(self);
}
protected virtual void RemovedFromWorld(Actor self)
{
UnReserve();
self.World.RemoveFromMaps(self, this);
OnCruisingAltitudeLeft();
OnAirborneAltitudeLeft();
}
void ITick.Tick(Actor self)
{
Tick(self);
}
protected virtual void Tick(Actor self)
{
// Add land activity if Aircraft trait is paused and the actor can land at the current location.
if (!ForceLanding && IsTraitPaused && airborne && CanLand(self.Location)
&& !((self.CurrentActivity is Land) || self.CurrentActivity is Turn))
{
self.QueueActivity(false, new Land(self));
ForceLanding = true;
}
// Add takeoff activity if Aircraft trait is not paused and the actor should not land when idle.
if (ForceLanding && !IsTraitPaused && !cruising && self.CurrentActivity is not TakeOff)
{
ForceLanding = false;
if (Info.IdleBehavior != IdleBehaviorType.Land)
self.QueueActivity(false, new TakeOff(self));
}
var oldCachedFacing = cachedFacing;
cachedFacing = Facing;
var oldCachedPosition = cachedPosition;
cachedPosition = self.CenterPosition;
var newMovementTypes = MovementType.None;
if (oldCachedFacing != Facing)
newMovementTypes |= MovementType.Turn;
if ((oldCachedPosition - cachedPosition).HorizontalLengthSquared != 0)
newMovementTypes |= MovementType.Horizontal;
if ((oldCachedPosition - cachedPosition).VerticalLengthSquared != 0)
newMovementTypes |= MovementType.Vertical;
CurrentMovementTypes = newMovementTypes;
if (!CurrentMovementTypes.HasMovementType(MovementType.Horizontal))
{
if (Info.Roll != WAngle.Zero && Roll != WAngle.Zero)
Roll = Util.TickFacing(Roll, WAngle.Zero, Info.RollSpeed);
if (Info.Pitch != WAngle.Zero && Pitch != WAngle.Zero)
Pitch = Util.TickFacing(Pitch, WAngle.Zero, Info.PitchSpeed);
}
Repulse();
}
public void Repulse()
{
var repulsionForce = GetRepulsionForce();
if (repulsionForce == WVec.Zero)
return;
var speed = Info.RepulsionSpeed != -1 ? Info.RepulsionSpeed : MovementSpeed;
// HACK: Prevent updating visibility twice per tick. We really shouldn't be
// moving twice in a tick in the first place.
notify = false;
SetPosition(self, CenterPosition + FlyStep(speed, repulsionForce.Yaw));
notify = true;
}
public virtual WVec GetRepulsionForce()
{
if (!Info.Repulsable)
return WVec.Zero;
if (reservation != null)
{
var distanceFromReservationActor = (ReservedActor.CenterPosition - self.CenterPosition).HorizontalLength;
if (distanceFromReservationActor < Info.WaitDistanceFromResupplyBase.Length)
return WVec.Zero;
}
// Repulsion only applies when we're flying at CruiseAltitude!
if (!cruising)
return WVec.Zero;
// PERF: Avoid LINQ.
var repulsionForce = WVec.Zero;
foreach (var actor in self.World.FindActorsInCircle(self.CenterPosition, Info.IdealSeparation))
{
if (actor.IsDead)
continue;
var ai = actor.Info.TraitInfoOrDefault<AircraftInfo>();
if (ai == null || !ai.Repulsable || ai.CruiseAltitude != Info.CruiseAltitude)
continue;
repulsionForce += GetRepulsionForce(actor);
}
// Actors outside the map bounds receive an extra nudge towards the center of the map
if (!self.World.Map.Contains(self.Location))
{
// The map bounds are in projected coordinates, which is technically wrong for this,
// but we avoid the issues in practice by guessing the middle of the map instead of the edge
var center = WPos.Lerp(self.World.Map.ProjectedTopLeft, self.World.Map.ProjectedBottomRight, 1, 2);
repulsionForce += new WVec(0, 1024, 0).Rotate(WRot.FromYaw((self.CenterPosition - center).Yaw));
}
if (Info.CanSlide)
return repulsionForce;
// Non-hovering actors mush always keep moving forward, so they need extra calculations.
var currentDir = FlyStep(Facing);
var length = currentDir.HorizontalLength * repulsionForce.HorizontalLength;
if (length == 0)
return WVec.Zero;
var dot = WVec.Dot(currentDir, repulsionForce) / length;
// avoid stalling the plane
return dot >= 0 ? repulsionForce : WVec.Zero;
}
public WVec GetRepulsionForce(Actor other)
{
if (self == other || other.CenterPosition.Z < self.CenterPosition.Z)
return WVec.Zero;
var d = self.CenterPosition - other.CenterPosition;
var distSq = d.HorizontalLengthSquared;
if (distSq > Info.IdealSeparation.LengthSquared)
return WVec.Zero;
if (distSq < 1)
{
var yaw = self.World.SharedRandom.Next(0, 1023);
var rot = new WRot(WAngle.Zero, WAngle.Zero, new WAngle(yaw));
return new WVec(1024, 0, 0).Rotate(rot);
}
return d * 1024 * 8 / (int)distSq;
}
public Actor GetActorBelow()
{
// Map.DistanceAboveTerrain(WPos pos) is called directly because Aircraft is an IPositionable trait
// and all calls occur in Tick methods.
if (self.World.Map.DistanceAboveTerrain(CenterPosition) != LandAltitude)
return null; // Not on the resupplier.
return self.World.ActorMap.GetActorsAt(self.Location)
.FirstOrDefault(a => a.Info.HasTraitInfo<ReservableInfo>());
}
public void MakeReservation(Actor target)
{
UnReserve();
var reservable = target.TraitOrDefault<Reservable>();
if (reservable != null)
{
reservation = reservable.Reserve(target, self, this);
ReservedActor = target;
}
}
public void AllowYieldingReservation()
{
if (reservation == null)
return;
MayYieldReservation = true;
}
public void UnReserve()
{
if (reservation == null)
return;
reservation.Dispose();
reservation = null;
ReservedActor = null;
MayYieldReservation = false;
}
bool AircraftCanEnter(Actor a, TargetModifiers modifiers)
{
if (RequireForceMove && !modifiers.HasModifier(TargetModifiers.ForceMove))
return false;
return AircraftCanEnter(a);
}
bool AircraftCanEnter(Actor a)
{
if (self.AppearsHostileTo(a))
return false;
var canRearmAtActor = rearmable != null && rearmable.Info.RearmActors.Contains(a.Info.Name);
var canRepairAtActor = repairable != null && repairable.Info.RepairActors.Contains(a.Info.Name);
return canRearmAtActor || canRepairAtActor;
}
bool AircraftCanResupplyAt(Actor a, bool allowedToForceEnter = false)
{
if (self.AppearsHostileTo(a))
return false;
var canRearmAtActor = rearmable != null && rearmable.Info.RearmActors.Contains(a.Info.Name);
var canRepairAtActor = repairable != null && repairable.Info.RepairActors.Contains(a.Info.Name);
var allowedToEnterRearmer = canRearmAtActor && (allowedToForceEnter || rearmable.RearmableAmmoPools.Any(p => !p.HasFullAmmo));
var allowedToEnterRepairer = canRepairAtActor && (allowedToForceEnter || self.GetDamageState() != DamageState.Undamaged);
return allowedToEnterRearmer || allowedToEnterRepairer;
}
public int MovementSpeed => !IsTraitDisabled && !IsTraitPaused ? Util.ApplyPercentageModifiers(Info.Speed, speedModifiers) : 0;
public int IdleMovementSpeed => Info.IdleSpeed < 0 ? MovementSpeed :
!IsTraitDisabled && !IsTraitPaused ? Util.ApplyPercentageModifiers(Info.IdleSpeed, speedModifiers) : 0;
public (CPos Cell, SubCell SubCell)[] OccupiedCells()
{
return landingCells;
}
public WVec FlyStep(WAngle facing)
{
return FlyStep(MovementSpeed, facing);
}
public WVec FlyStep(int speed, WAngle facing)
{
var dir = new WVec(0, -1024, 0).Rotate(WRot.FromYaw(facing));
return speed * dir / 1024;
}
public CPos? FindLandingLocation(CPos targetCell, WDist maxSearchDistance)
{
// The easy case
if (CanLand(targetCell, blockedByMobile: false))
return targetCell;
var cellRange = (maxSearchDistance.Length + 1023) / 1024;
var centerPosition = self.World.Map.CenterOfCell(targetCell);
foreach (var c in self.World.Map.FindTilesInCircle(targetCell, cellRange))
{
if (!CanLand(c, blockedByMobile: false))
continue;
var delta = self.World.Map.CenterOfCell(c) - centerPosition;
if (delta.LengthSquared < maxSearchDistance.LengthSquared)
return c;
}
return null;
}
public bool CanLand(IEnumerable<CPos> cells, Actor dockingActor = null, bool blockedByMobile = true)
{
foreach (var c in cells)
if (!CanLand(c, dockingActor, blockedByMobile))
return false;
return true;
}
public bool CanLand(CPos cell, Actor dockingActor = null, bool blockedByMobile = true)
{
if (!self.World.Map.Contains(cell))
return false;
foreach (var otherActor in self.World.ActorMap.GetActorsAt(cell))
if (IsBlockedBy(self, otherActor, dockingActor, blockedByMobile))
return false;
// Terrain type is ignored when docking with an actor
if (dockingActor != null)
return true;
var landableTerrain = overrideAircraftLanding != null ? overrideAircraftLanding.LandableTerrainTypes : Info.LandableTerrainTypes;
return landableTerrain.Contains(self.World.Map.GetTerrainInfo(cell).Type);
}
bool IsBlockedBy(Actor self, Actor otherActor, Actor ignoreActor, bool blockedByMobile = true)
{
// We are not blocked by the actor we are ignoring.
if (otherActor == self || otherActor == ignoreActor)
return false;
// We are not blocked by actors we can nudge out of the way
// TODO: Generalize blocker checks and handling here and in Locomotor
if (!blockedByMobile && self.Owner.RelationshipWith(otherActor.Owner) == PlayerRelationship.Ally &&
otherActor.TraitOrDefault<Mobile>() != null && otherActor.CurrentActivity == null)
return false;
// PERF: Only perform ITemporaryBlocker trait look-up if mod/map rules contain any actors that are temporary blockers
if (self.World.RulesContainTemporaryBlocker)
{
// If there is a temporary blocker in our path, but we can remove it, we are not blocked.
var temporaryBlocker = otherActor.TraitOrDefault<ITemporaryBlocker>();
if (temporaryBlocker != null && temporaryBlocker.CanRemoveBlockage(otherActor, self))
return false;
}
// If we cannot crush the other actor in our way, we are blocked.
if (Info.Crushes.IsEmpty)
return true;
// If the other actor in our way cannot be crushed, we are blocked.
// PERF: Avoid LINQ.
foreach (var crushable in otherActor.Crushables)
if (crushable.CrushableBy(otherActor, self, Info.Crushes))
return false;
return true;
}
public bool CanRearmAt(Actor host)
{
return rearmable != null && rearmable.Info.RearmActors.Contains(host.Info.Name) && rearmable.RearmableAmmoPools.Any(p => !p.HasFullAmmo);
}
public bool CanRepairAt(Actor host)
{
return repairable != null && repairable.Info.RepairActors.Contains(host.Info.Name) && self.GetDamageState() != DamageState.Undamaged;
}
public void ModifyDeathActorInit(Actor self, TypeDictionary init)
{
init.Add(new FacingInit(Facing));
}
void INotifyBecomingIdle.OnBecomingIdle(Actor self)
{
OnBecomingIdle(self);
}
protected virtual void OnBecomingIdle(Actor self)
{
if (Info.IdleBehavior == IdleBehaviorType.LeaveMap)
{
self.QueueActivity(new FlyOffMap(self));
self.QueueActivity(new RemoveSelf());
}
else if (Info.IdleBehavior == IdleBehaviorType.LeaveMapAtClosestEdge)
{
var edgeCell = self.World.Map.ChooseClosestEdgeCell(self.Location);
self.QueueActivity(new FlyOffMap(self, Target.FromCell(self.World, edgeCell)));
self.QueueActivity(new RemoveSelf());
}
else if (Info.IdleBehavior == IdleBehaviorType.ReturnToBase && GetActorBelow() == null)
self.QueueActivity(new ReturnToBase(self, null, !Info.TakeOffOnResupply));
else
{
var dat = self.World.Map.DistanceAboveTerrain(CenterPosition);
if (dat == LandAltitude)
{
if (!CanLand(self.Location) && ReservedActor == null)
self.QueueActivity(new TakeOff(self));
// All remaining idle behaviors rely on not being at LandAltitude, so unconditionally return
return;
}
if (Info.IdleBehavior == IdleBehaviorType.Land && Info.LandableTerrainTypes.Count > 0)
self.QueueActivity(new Land(self));
else
self.QueueActivity(new FlyIdle(self));
}
}
#region Implement IPositionable
public bool CanExistInCell(CPos cell) { return true; }
public bool IsLeavingCell(CPos location, SubCell subCell = SubCell.Any) { return false; } // TODO: Handle landing
public bool CanEnterCell(CPos cell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All) { return true; }
public SubCell GetValidSubCell(SubCell preferred) { return SubCell.Invalid; }
public SubCell GetAvailableSubCell(CPos a, SubCell preferredSubCell = SubCell.Any, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
{
// Does not use any subcell
return SubCell.Invalid;
}
public void SetCenterPosition(Actor self, WPos pos) { SetPosition(self, pos); }
// Changes position, but not altitude
public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any)
{
SetPosition(self, self.World.Map.CenterOfCell(cell) + new WVec(0, 0, CenterPosition.Z));
}
public void SetPosition(Actor self, WPos pos)
{
CenterPosition = pos;
if (!self.IsInWorld)
return;
var altitude = self.World.Map.DistanceAboveTerrain(CenterPosition);
// LandingCells define OccupiedCells, so we need to keep current position with LandindCells in sync.
// Though we don't want to update LandingCells when the unit is airborne, as when non-VTOL units reserve
// their landing position it is expected for their landing cell to not match their current position.
if (HasInfluence() && altitude.Length <= Info.MinAirborneAltitude)
{
var currentPos = new[] { (TopLeft, SubCell.FullCell) };
if (landingCells.SequenceEqual(currentPos))
{
self.World.ActorMap.RemoveInfluence(self, this);
landingCells = currentPos;
self.World.ActorMap.AddInfluence(self, this);
}
}
self.World.UpdateMaps(self, this);
var isAirborne = altitude.Length >= Info.MinAirborneAltitude;
if (isAirborne && !airborne)
OnAirborneAltitudeReached();
else if (!isAirborne && airborne)
OnAirborneAltitudeLeft();
var isCruising = altitude == Info.CruiseAltitude;
if (isCruising && !cruising)
OnCruisingAltitudeReached();
else if (!isCruising && cruising)
OnCruisingAltitudeLeft();
// NB: This can be called from the constructor before notifyCenterPositionChanged is assigned.
if (notify && notifyCenterPositionChanged != null)
foreach (var n in notifyCenterPositionChanged)
n.CenterPositionChanged(self, 0, 0);
FinishedMoving(self);
}
public void FinishedMoving(Actor self)
{
// Only crush actors on having landed
if (!self.IsAtGroundLevel())
return;
CrushAction(self, (notifyCrushed) => notifyCrushed.OnCrush);
}
public void EnteringCell(Actor self)
{
CrushAction(self, (notifyCrushed) => notifyCrushed.WarnCrush);
}
void CrushAction(Actor self, Func<INotifyCrushed, Action<Actor, Actor, BitSet<CrushClass>>> action)
{
var crushables = self.World.ActorMap.GetActorsAt(TopLeft).Where(a => a != self)
.SelectMany(a => a.Crushables.Select(t => new TraitPair<ICrushable>(a, t)));
// Only crush actors that are on the ground level
foreach (var crushable in crushables)
if (crushable.Trait.CrushableBy(crushable.Actor, self, Info.Crushes) && crushable.Actor.IsAtGroundLevel())
foreach (var notifyCrushed in crushable.Actor.TraitsImplementing<INotifyCrushed>())
action(notifyCrushed)(crushable.Actor, self, Info.Crushes);
}
public void AddInfluence((CPos, SubCell)[] landingCells)
{
if (HasInfluence())
throw new InvalidOperationException(
$"Cannot {nameof(AddInfluence)} until previous influence is removed with {nameof(RemoveInfluence)}");
this.landingCells = landingCells;
if (self.IsInWorld)
self.World.ActorMap.AddInfluence(self, this);
}
public void AddInfluence(CPos landingCell)
{
AddInfluence(new[] { (landingCell, SubCell.FullCell) });
}
public void RemoveInfluence()
{
if (self.IsInWorld)
self.World.ActorMap.RemoveInfluence(self, this);
landingCells = Array.Empty<(CPos, SubCell)>();
}
public bool HasInfluence()
{
return landingCells.Length > 0;
}
#endregion
#region Implement IMove
public Activity MoveTo(CPos cell, int nearEnough = 0, Actor ignoreActor = null,
bool evaluateNearestMovableCell = false, Color? targetLineColor = null)
{
return new Fly(self, Target.FromCell(self.World, cell), WDist.FromCells(nearEnough), targetLineColor: targetLineColor);
}
public Activity MoveWithinRange(in Target target, WDist range,
WPos? initialTargetPosition = null, Color? targetLineColor = null)
{
return new Fly(self, target, WDist.Zero, range, initialTargetPosition, targetLineColor);
}
public Activity MoveWithinRange(in Target target, WDist minRange, WDist maxRange,
WPos? initialTargetPosition = null, Color? targetLineColor = null)
{
return new Fly(self, target, minRange, maxRange,
initialTargetPosition, targetLineColor);
}
public Activity MoveFollow(Actor self, in Target target, WDist minRange, WDist maxRange,
WPos? initialTargetPosition = null, Color? targetLineColor = null)
{
return new FlyFollow(self, target, minRange, maxRange,
initialTargetPosition, targetLineColor);
}
public Activity ReturnToCell(Actor self) { return null; }
public Activity MoveToTarget(Actor self, in Target target,
WPos? initialTargetPosition = null, Color? targetLineColor = null)
{
return new Fly(self, target, initialTargetPosition, targetLineColor);
}
public Activity MoveIntoTarget(Actor self, in Target target)
{
return new Land(self, target);
}
public Activity MoveOntoTarget(Actor self, in Target target, in WVec offset, WAngle? facing, Color? targetLineColor = null)
{
return new Land(self, target, offset, facing, targetLineColor);
}
public Activity LocalMove(Actor self, WPos fromPos, WPos toPos)
{
// TODO: Ignore repulsion when moving
var activities = new CallFunc(() => SetCenterPosition(self, fromPos));
activities.Queue(new Fly(self, Target.FromPos(toPos)));
return activities;
}
public int EstimatedMoveDuration(Actor self, WPos fromPos, WPos toPos)
{
var speed = MovementSpeed;
return speed > 0 ? (toPos - fromPos).Length / speed : 0;
}
public CPos NearestMoveableCell(CPos cell) { return cell; }
public MovementType CurrentMovementTypes
{
get => movementTypes;
set
{
var oldValue = movementTypes;
movementTypes = value;
if (value != oldValue)
foreach (var n in notifyMoving)
n.MovementTypeChanged(self, value);
}
}
public bool CanEnterTargetNow(Actor self, in Target target)
{
// Lambdas can't use 'in' variables, so capture a copy for later
var targetActor = target;
if (target.Positions.Any(p => self.World.ActorMap.GetActorsAt(self.World.Map.CellContaining(p)).Any(a => a != self && a != targetActor.Actor)))
return false;
MakeReservation(target.Actor);
return true;
}
#endregion
#region Implement order interfaces
public IEnumerable<IOrderTargeter> Orders
{
get
{
yield return new EnterAlliedActorTargeter<BuildingInfo>(
"ForceEnter",
6,
Info.EnterCursor,
Info.EnterBlockedCursor,