context: #region Copyright & License Information
  /*
   * Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
   * 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.Pathfinder;
  using OpenRA.Primitives;
  using OpenRA.Support;
  using OpenRA.Traits;
  
  namespace OpenRA.Mods.Common.Traits
  {
  	[Desc("Unit is able to move.")]
  	public class MobileInfo : PausableConditionalTraitInfo, IMoveInfo, IPositionableInfo, IFacingInfo, IActorPreviewInitInfo,
  		IEditorActorOptions
  	{
  		[LocomotorReference]
  		[FieldLoader.Require]
  		[Desc("Which Locomotor does this trait use. Must be defined on the World actor.")]
  		public readonly string Locomotor = null;
  
  		public readonly WAngle InitialFacing = WAngle.Zero;
  
  		[Desc("Speed at which the actor turns.")]
  		public readonly WAngle TurnSpeed = new WAngle(512);
  
  		public readonly int Speed = 1;
  
  		[Desc("If set to true, this unit will always turn in place instead of following a curved trajectory (like infantry).")]
  		public readonly bool AlwaysTurnInPlace = false;
  
  		[CursorReference]
  		[Desc("Cursor to display when a move order can be issued at target location.")]
  		public readonly string Cursor = "move";
  
  		[CursorReference(dictionaryReference: LintDictionaryReference.Values)]
  		[Desc("Cursor overrides to display for specific terrain types.",
  			"A dictionary of [terrain type]: [cursor name].")]
  		public readonly Dictionary<string, string> TerrainCursors = new Dictionary<string, string>();
  
  		[CursorReference]
  		[Desc("Cursor to display when a move order cannot be issued at target location.")]
  		public readonly string BlockedCursor = "move-blocked";
  
  		[VoiceReference]
  		public readonly string Voice = "Action";
  
  		[Desc("Color to use for the target line for regular move orders.")]
  		public readonly Color TargetLineColor = Color.Green;
  
  		[Desc("Facing to use for actor previews (map editor, color picker, etc)")]
  		public readonly WAngle PreviewFacing = new WAngle(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;
  
  		[ConsumedConditionReference]
  		[Desc("Boolean expression defining the condition under which this actor cannot be nudged by other actors.")]
  		public readonly BooleanExpression ImmovableCondition = null;
  
  		[Desc("The distance from the edge of a cell over which the actor will adjust its tilt when moving between cells with different ramp types.",
  			"-1 means that the actor does not tilt on slopes.")]
  		public readonly WDist TerrainOrientationAdjustmentMargin = new WDist(-1);
  
  		IEnumerable<ActorInit> IActorPreviewInitInfo.ActorPreviewInits(ActorInfo ai, ActorPreviewType type)
  		{
  			yield return new FacingInit(PreviewFacing);
  		}
  
  		public Color GetTargetLineColor() { return TargetLineColor; }
  
  		public override object Create(ActorInitializer init) { return new Mobile(init, this); }
  
  		public LocomotorInfo LocomotorInfo { get; private set; }
  
  		public override void RulesetLoaded(Ruleset rules, ActorInfo ai)
  		{
  			var locomotorInfos = rules.Actors[SystemActors.World].TraitInfos<LocomotorInfo>();
  			LocomotorInfo = locomotorInfos.FirstOrDefault(li => li.Name == Locomotor);
  			if (LocomotorInfo == null)
  				throw new YamlException($"A locomotor named '{Locomotor}' doesn't exist.");
  			else if (locomotorInfos.Count(li => li.Name == Locomotor) > 1)
  				throw new YamlException($"There is more than one locomotor named '{Locomotor}'.");
  
  			// We need to reset the reference to the locomotor between each worlds, otherwise we are reference the previous state.
  			locomotor = null;
  
  			base.RulesetLoaded(rules, ai);
  		}
  
  		public WAngle GetInitialFacing() { return InitialFacing; }
  
  		// initialized and used by CanEnterCell
  		Locomotor locomotor;
  
  		/// <summary>
  		/// Note: If the target <paramref name="cell"/> has any free subcell, the value of <paramref name="subCell"/> is ignored.
  		/// </summary>
  		public bool CanEnterCell(World world, Actor self, CPos cell, SubCell subCell = SubCell.FullCell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
  		{
  			// PERF: Avoid repeated trait queries on the hot path
  			if (locomotor == null)
  				locomotor = world.WorldActor.TraitsImplementing<Locomotor>()
  				   .SingleOrDefault(l => l.Info.Name == Locomotor);
  
  			if (locomotor.MovementCostForCell(cell) == PathGraph.MovementCostForUnreachableCell)
  				return false;
  
  			return locomotor.CanMoveFreelyInto(self, cell, subCell, check, ignoreActor);
  		}
  
  		public bool CanStayInCell(World world, CPos cell)
  		{
  			// PERF: Avoid repeated trait queries on the hot path
  			if (locomotor == null)
  				locomotor = world.WorldActor.TraitsImplementing<Locomotor>()
  				   .SingleOrDefault(l => l.Info.Name == Locomotor);
  
  			if (cell.Layer == CustomMovementLayerType.Tunnel)
  				return false;
  
  			return locomotor.CanStayInCell(cell);
  		}
  
  		public IReadOnlyDictionary<CPos, SubCell> OccupiedCells(ActorInfo info, CPos location, SubCell subCell = SubCell.Any)
  		{
  			return new Dictionary<CPos, SubCell>() { { location, subCell } };
  		}
  
  		bool IOccupySpaceInfo.SharesCell => LocomotorInfo.SharesCell;
  
  		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?.Value ?? InitialFacing).Angle;
  				},
  				(actor, value) => actor.ReplaceInit(new FacingInit(new WAngle((int)value))));
  		}
  	}
  
  	public class Mobile : PausableConditionalTrait<MobileInfo>, IIssueOrder, IResolveOrder, IOrderVoice, IPositionable, IMove, ITick, ICreationActivity,
  		IFacing, IDeathActorInitModifier, INotifyAddedToWorld, INotifyRemovedFromWorld, INotifyBlockingMove, IActorPreviewInitModifier, INotifyBecomingIdle
  	{
  		readonly Actor self;
  		readonly Lazy<IEnumerable<int>> speedModifiers;
  
  		readonly bool returnToCellOnCreation;
  		readonly bool returnToCellOnCreationRecalculateSubCell = true;
  		readonly int creationActivityDelay;
  
  		#region IMove CurrentMovementTypes
  		MovementType movementTypes;
  		public MovementType CurrentMovementTypes
  		{
  			get => movementTypes;
  
  			set
  			{
  				var oldValue = movementTypes;
  				movementTypes = value;
  				if (value != oldValue)
  				{
  					self.World.ActorMap.UpdateOccupiedCells(self.OccupiesSpace);
  					foreach (var n in notifyMoving)
  						n.MovementTypeChanged(self, value);
  				}
  			}
  		}
  		#endregion
  
  		WRot terrainRampOrientation = WRot.None;
  		WAngle oldFacing;
  		WRot orientation;
  		WPos oldPos;
  		CPos fromCell, toCell;
  		public SubCell FromSubCell, ToSubCell;
  
  		INotifyCustomLayerChanged[] notifyCustomLayerChanged;
  		INotifyCenterPositionChanged[] notifyCenterPositionChanged;
  		INotifyMoving[] notifyMoving;
  		INotifyFinishedMoving[] notifyFinishedMoving;
  		IWrapMove[] moveWrappers;
  		bool requireForceMove;
  
  		public bool IsImmovable { get; private set; }
  		public bool TurnToMove;
  		public bool IsBlocking { get; private set; }
  
  		public bool IsMovingBetweenCells => FromCell != ToCell;
  
  		#region IFacing
  
  		[Sync]
  		public WAngle Facing
  		{
  			get => orientation.Yaw;
  			set => orientation = orientation.WithYaw(value);
  		}
  
  		public WRot Orientation => orientation.Rotate(terrainRampOrientation);
  
  		public WAngle TurnSpeed => Info.TurnSpeed;
  
  		#endregion
  
  		[Sync]
  		public CPos FromCell => fromCell;
  
  		[Sync]
  		public CPos ToCell => toCell;
  
  		public Locomotor Locomotor { get; private set; }
  
  		public IPathFinder Pathfinder { get; private set; }
  
  		#region IOccupySpace
  
  		[Sync]
  		public WPos CenterPosition { get; private set; }
  
  		public CPos TopLeft => ToCell;
  
  		public (CPos, SubCell)[] OccupiedCells()
  		{
  			if (FromCell == ToCell)
  				return new[] { (FromCell, FromSubCell) };
  
  			// HACK: Should be fixed properly, see https://github.com/OpenRA/OpenRA/pull/17292 for an explanation
  			if (Info.LocomotorInfo.SharesCell)
  				return new[] { (ToCell, ToSubCell) };
  
  			return new[] { (FromCell, FromSubCell), (ToCell, ToSubCell) };
  		}
  		#endregion
  
  		ICrushResource[] notifyCrushResource;
  
  		public Mobile(ActorInitializer init, MobileInfo info)
  			: base(info)
  		{
  			self = init.Self;
  
  			speedModifiers = Exts.Lazy(() => self.TraitsImplementing<ISpeedModifier>().ToArray().Select(x => x.GetSpeedModifier()));
  
  			ToSubCell = FromSubCell = info.LocomotorInfo.SharesCell ? init.World.Map.Grid.DefaultSubCell : SubCell.FullCell;
  
  			var subCellInit = init.GetOrDefault<SubCellInit>();
  			if (subCellInit != null)
  			{
  				FromSubCell = ToSubCell = subCellInit.Value;
  				returnToCellOnCreationRecalculateSubCell = false;
  			}
  
  			var locationInit = init.GetOrDefault<LocationInit>();
  			if (locationInit != null)
  			{
  				fromCell = toCell = locationInit.Value;
  				SetCenterPosition(self, init.World.Map.CenterOfSubCell(FromCell, FromSubCell));
  			}
  
  			Facing = oldFacing = init.GetValue<FacingInit, WAngle>(info.InitialFacing);
  
  			// Sets the initial center position
  			// Unit will move into the cell grid (defined by LocationInit) as its initial activity
  			var centerPositionInit = init.GetOrDefault<CenterPositionInit>();
  			if (centerPositionInit != null)
  			{
  				oldPos = centerPositionInit.Value;
  				SetCenterPosition(self, oldPos);
  				returnToCellOnCreation = true;
  			}
  
  			creationActivityDelay = init.GetValue<CreationActivityDelayInit, int>(0);
  		}
  
  		protected override void Created(Actor self)
  		{
  			notifyCustomLayerChanged = self.TraitsImplementing<INotifyCustomLayerChanged>().ToArray();
  			notifyCenterPositionChanged = self.TraitsImplementing<INotifyCenterPositionChanged>().ToArray();
  			notifyMoving = self.TraitsImplementing<INotifyMoving>().ToArray();
  			notifyFinishedMoving = self.TraitsImplementing<INotifyFinishedMoving>().ToArray();
  			moveWrappers = self.TraitsImplementing<IWrapMove>().ToArray();
  			Pathfinder = self.World.WorldActor.Trait<IPathFinder>();
  			Locomotor = self.World.WorldActor.TraitsImplementing<Locomotor>()
  				.Single(l => l.Info.Name == Info.Locomotor);
  
  			notifyCrushResource = self.TraitsImplementing<ICrushResource>().ToArray();
  
  			base.Created(self);
  		}
  
  		void ITick.Tick(Actor self)
  		{
  			UpdateMovement(self);
  		}
  
  		public void UpdateMovement(Actor self)
  		{
  			var newMovementTypes = MovementType.None;
  			if ((oldPos - CenterPosition).HorizontalLengthSquared != 0)
  				newMovementTypes |= MovementType.Horizontal;
  
  			if (oldPos.Z != CenterPosition.Z)
  				newMovementTypes |= MovementType.Vertical;
  
  			if (oldFacing != Facing)
  				newMovementTypes |= MovementType.Turn;
  
  			CurrentMovementTypes = newMovementTypes;
  
  			oldPos = CenterPosition;
  			oldFacing = Facing;
  		}
  
  		void INotifyAddedToWorld.AddedToWorld(Actor self)
  		{
  			self.World.AddToMaps(self, this);
  		}
  
  		void INotifyRemovedFromWorld.RemovedFromWorld(Actor self)
  		{
  			self.World.RemoveFromMaps(self, this);
  		}
  
  		protected override void TraitEnabled(Actor self)
  		{
  			self.World.ActorMap.UpdateOccupiedCells(self.OccupiesSpace);
  		}
  
  		protected override void TraitDisabled(Actor self)
  		{
  			self.World.ActorMap.UpdateOccupiedCells(self.OccupiesSpace);
  		}
  
  		protected override void TraitResumed(Actor self)
  		{
  			self.World.ActorMap.UpdateOccupiedCells(self.OccupiesSpace);
  		}
  
  		protected override void TraitPaused(Actor self)
  		{
  			self.World.ActorMap.UpdateOccupiedCells(self.OccupiesSpace);
  		}
  
  		#region Local misc stuff
  
  		public void Nudge(Actor nudger)
  		{
  			if (IsTraitDisabled || IsTraitPaused || IsImmovable)
  				return;
  
  			var cell = GetAdjacentCell(nudger.Location);
  			if (cell != null)
  				self.QueueActivity(false, MoveTo(cell.Value, 0));
  		}
  
  		public CPos? GetAdjacentCell(CPos nextCell, Func<CPos, bool> preferToAvoid = null)
  		{
  			var availCells = new List<CPos>();
  			var notStupidCells = new List<CPos>();
  			foreach (CVec direction in CVec.Directions)
  			{
  				var p = ToCell + direction;
  				if (CanEnterCell(p) && CanStayInCell(p) && (preferToAvoid == null || !preferToAvoid(p)))
  					availCells.Add(p);
  				else if (p != nextCell && p != ToCell)
  					notStupidCells.Add(p);
  			}
  
  			CPos? newCell = null;
  			if (availCells.Count > 0)
  				newCell = availCells.Random(self.World.SharedRandom);
  			else
  			{
  				var cellInfo = notStupidCells
  					.SelectMany(c => self.World.ActorMap.GetActorsAt(c).Where(IsMovable),
  						(c, a) => new { Cell = c, Actor = a })
  					.RandomOrDefault(self.World.SharedRandom);
  				if (cellInfo != null)
  					newCell = cellInfo.Cell;
  			}
  
  			return newCell;
  		}
  
  		static bool IsMovable(Actor otherActor)
  		{
  			if (!otherActor.IsIdle)
  				return false;
  
  			var mobile = otherActor.TraitOrDefault<Mobile>();
  			if (mobile == null || mobile.IsTraitDisabled || mobile.IsTraitPaused || mobile.IsImmovable)
  				return false;
  
  			return true;
  		}
  
  		public bool IsLeaving()
  		{
  			if (CurrentMovementTypes.HasMovementType(MovementType.Horizontal))
  				return true;
  
  			if (CurrentMovementTypes.HasMovementType(MovementType.Turn))
  				return TurnToMove;
  
  			return false;
  		}
  
  		public bool CanInteractWithGroundLayer(Actor self)
  		{
  			// TODO: Think about extending this to support arbitrary layer-layer checks
  			// in a way that is compatible with the other IMove types.
  			// This would then allow us to e.g. have units attack other units inside tunnels.
  			if (ToCell.Layer == 0)
  				return true;
  
  			var layer = self.World.GetCustomMovementLayers()[ToCell.Layer];
  			return layer == null || layer.InteractsWithDefaultLayer;
  		}
  
  		#endregion
  
  		#region IPositionable
  
  		// Returns a valid sub-cell
  		public SubCell GetValidSubCell(SubCell preferred = SubCell.Any)
  		{
  			// Try same sub-cell
  			if (preferred == SubCell.Any)
  				preferred = FromSubCell;
  
  			// Fix sub-cell assignment
  			if (Info.LocomotorInfo.SharesCell)
  			{
  				if (preferred <= SubCell.FullCell)
  					return self.World.Map.Grid.DefaultSubCell;
  			}
  			else
  			{
  				if (preferred != SubCell.FullCell)
  					return SubCell.FullCell;
  			}
  
  			return preferred;
  		}
  
  		// Sets the location (fromCell, toCell, FromSubCell, ToSubCell) and CenterPosition
  		public void SetPosition(Actor self, CPos cell, SubCell subCell = SubCell.Any)
  		{
  			subCell = GetValidSubCell(subCell);
  			SetLocation(cell, subCell, cell, subCell);
  
  			var position = cell.Layer == 0 ? self.World.Map.CenterOfCell(cell) :
  				self.World.GetCustomMovementLayers()[cell.Layer].CenterOfCell(cell);
  
  			var subcellOffset = self.World.Map.Grid.OffsetOfSubCell(subCell);
  			SetCenterPosition(self, position + subcellOffset);
  			FinishedMoving(self);
  		}
  
  		// Sets the location (fromCell, toCell, FromSubCell, ToSubCell) and CenterPosition
  		public void SetPosition(Actor self, WPos pos)
  		{
  			var cell = self.World.Map.CellContaining(pos);
  			SetLocation(cell, FromSubCell, cell, FromSubCell);
  			SetCenterPosition(self, self.World.Map.CenterOfSubCell(cell, FromSubCell) + new WVec(0, 0, self.World.Map.DistanceAboveTerrain(pos).Length));
  			FinishedMoving(self);
  		}
  
  		// Sets only the CenterPosition
  		public void SetCenterPosition(Actor self, WPos pos)
  		{
  			CenterPosition = pos;
  			self.World.UpdateMaps(self, this);
  
  			var map = self.World.Map;
  			SetTerrainRampOrientation(self, map.TerrainOrientation(map.CellContaining(pos)));
  
  			// The first time SetCenterPosition is called is in the constructor before creation, so we need a null check here as well
  			if (notifyCenterPositionChanged == null)
  				return;
  
  			foreach (var n in notifyCenterPositionChanged)
  				n.CenterPositionChanged(self, fromCell.Layer, toCell.Layer);
  		}
  
  		public void SetTerrainRampOrientation(Actor self, WRot orientation)
  		{
  			if (Info.TerrainOrientationAdjustmentMargin.Length >= 0)
  				terrainRampOrientation = orientation;
  		}
  
  		public bool IsLeavingCell(CPos location, SubCell subCell = SubCell.Any)
  		{
  			return ToCell != location && fromCell == location
  				&& (subCell == SubCell.Any || FromSubCell == subCell || subCell == SubCell.FullCell || FromSubCell == SubCell.FullCell);
  		}
  
  		public SubCell GetAvailableSubCell(CPos a, SubCell preferredSubCell = SubCell.Any, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
  		{
  			return Locomotor.GetAvailableSubCell(self, a, check, preferredSubCell, ignoreActor);
  		}
  
  		public bool CanExistInCell(CPos cell)
  		{
  			return Locomotor.MovementCostForCell(cell) != PathGraph.MovementCostForUnreachableCell;
  		}
  
  		public bool CanEnterCell(CPos cell, Actor ignoreActor = null, BlockedByActor check = BlockedByActor.All)
  		{
  			return Info.CanEnterCell(self.World, self, cell, ToSubCell, ignoreActor, check);
  		}
  
  		public bool CanStayInCell(CPos cell)
  		{
  
gt: 			return Info.CanStayInCell(self.World, cell);