AntennaRelay: Added radiusRatio for configurable 'fudge factor'.
[AntennaRange.git] / AntennaRelay.cs
blob:a/AntennaRelay.cs -> blob:b/AntennaRelay.cs
--- a/AntennaRelay.cs
+++ b/AntennaRelay.cs
@@ -31,19 +31,30 @@
 using System.Linq;
 using ToadicusTools;
 
+// @DONE TODO: Retool nearestRelay to always contain the nearest relay, even if out of range.
+// @DONE TODO: Retool CanTransmit to not rely on nearestRelay == null.
+// TODO: Track occluded vessels somehow.
+
 namespace AntennaRange
 {
 	public class AntennaRelay
 	{
-		public static bool requireLineOfSight;
-		public static double radiusRatio;
-
 		// We don't have a Bard, so we'll hide Kerbin here.
-		protected CelestialBody Kerbin;
-
-		protected CelestialBody _firstOccludingBody;
-
-		protected IAntennaRelay _nearestRelayCache;
+		private static CelestialBody _Kerbin;
+		public static CelestialBody Kerbin
+		{
+			get
+			{
+				if (_Kerbin == null && FlightGlobals.ready)
+				{
+					_Kerbin = FlightGlobals.GetHomeBody();
+				}
+
+				return _Kerbin;
+			}
+		}
+
+		private IAntennaRelay _nearestRelayCache;
 		protected IAntennaRelay moduleRef;
 
 		protected System.Diagnostics.Stopwatch searchTimer;
@@ -69,10 +80,11 @@
 		{
 			get
 			{
-				if (this.searchTimer.IsRunning &&
+				if (!this.searchTimer.IsRunning ||
 					this.searchTimer.ElapsedMilliseconds > this.millisecondsBetweenSearches)
 				{
 					this._nearestRelayCache = this.FindNearestRelay();
+
 					this.searchTimer.Restart();
 				}
 
@@ -84,16 +96,19 @@
 			}
 		}
 
-		/// <summary>
-		/// Gets the first occluding body.
-		/// </summary>
-		/// <value>The first occluding body.</value>
-		public CelestialBody firstOccludingBody
-		{
-			get
-			{
-				return this._firstOccludingBody;
-			}
+		public IAntennaRelay bestOccludedRelay
+		{
+			get;
+			protected set;
+		}
+
+		/// <summary>
+		/// Gets the first <see cref="CelestialBody"/> found to be blocking line of sight.
+		/// </summary>
+		public virtual CelestialBody firstOccludingBody
+		{
+			get;
+			protected set;
 		}
 
 		/// <summary>
@@ -104,20 +119,40 @@
 		{
 			get
 			{
-				this.nearestRelay = this.FindNearestRelay();
-
 				// If there is no available relay nearby...
-				if (this.nearestRelay == null)
-				{
-					// .. return the distance to Kerbin
-					return this.DistanceTo(this.Kerbin);
-				}
-				else
-				{
-					/// ...otherwise, return the distance to the nearest available relay.
-					return this.DistanceTo(nearestRelay);
-				}
-			}
+				// @DONE TODO: Remove nearestRelay == null
+				double kerbinDistance = this.DistanceTo(Kerbin);
+
+				if (this.nearestRelay != null)
+				{
+					double relayDistance = this.DistanceTo(this.nearestRelay);
+
+					// If our nearest relay is nearer than Kerbin, use its distance.
+					if (relayDistance < kerbinDistance)
+					{
+						this.KerbinDirect = false;
+
+						return relayDistance;
+					}
+				}
+
+				if (this.firstOccludingBody != null && this.bestOccludedRelay != null)
+				{
+					this.KerbinDirect = false;
+					return this.DistanceTo(this.bestOccludedRelay);
+				}
+
+				this.KerbinDirect = true;
+
+				// .. return the distance to Kerbin
+				return kerbinDistance;
+			}
+		}
+
+		public virtual double nominalTransmitDistance
+		{
+			get;
+			set;
 		}
 
 		/// <summary>
@@ -141,25 +176,51 @@
 			protected set;
 		}
 
+		public virtual bool KerbinDirect
+		{
+			get;
+			protected set;
+		}
+
 		/// <summary>
 		/// Determines whether this instance can transmit.
 		/// </summary>
 		/// <returns><c>true</c> if this instance can transmit; otherwise, <c>false</c>.</returns>
 		public virtual bool CanTransmit()
 		{
-			if (
-				this.transmitDistance > this.maxTransmitDistance ||
-				(
-					requireLineOfSight &&
-					this.nearestRelay == null &&
-					!this.vessel.hasLineOfSightTo(this.Kerbin, out this._firstOccludingBody, radiusRatio)
+			CelestialBody fob = null;
+
+			// @DONE TODO: Remove nearestRelay == null
+			// Because we're correctly falling back to Kerbin in transmitDistance the first test should always fail
+			// when we're out of range of anything, and the second will fail when LOS is blocked (and enforced).
+
+			Tools.PostDebugMessage(this.moduleRef, "Checking if CanTransmit with maxTransmitDistance={0}" +
+				"\n\ttransmitDistance={1}; KerbinDirect={2}, nearestRelay={3}, bestOccludedRelay={4}",
+				this.maxTransmitDistance, this.transmitDistance, this.KerbinDirect,
+				this.nearestRelay, this.bestOccludedRelay
+			);
+
+			// If our transmit distance is greater than our maximum range, we can't transmit and it doesn't matter why.
+			if (this.transmitDistance > this.maxTransmitDistance)
+			{
+				this.firstOccludingBody = null;
+				return false;
+			}
+			// ...if we're in range...
+			else
+			{
+				// ...check for LOS problems...
+				if (
+					ARConfiguration.RequireLineOfSight
+					&& this.KerbinDirect &&
+					!this.vessel.hasLineOfSightTo(Kerbin, out fob, ARConfiguration.RadiusRatio)
 				)
-			)
-			{
-				return false;
-			}
-			else
-			{
+				{
+					this.firstOccludingBody = fob;
+					return false;
+				}
+
+				this.firstOccludingBody = null;
 				return true;
 			}
 		}
@@ -168,9 +229,9 @@
 		/// Finds the nearest relay.
 		/// </summary>
 		/// <returns>The nearest relay or null, if no relays in range.</returns>
-		public IAntennaRelay FindNearestRelay()
-		{
-			if (this.searchTimer.IsRunning && this.searchTimer.ElapsedMilliseconds < this.millisecondsBetweenSearches)
+		private IAntennaRelay FindNearestRelay()
+		{
+			/*if (this.searchTimer.IsRunning && this.searchTimer.ElapsedMilliseconds < this.millisecondsBetweenSearches)
 			{
 				return this.nearestRelay;
 			}
@@ -181,7 +242,7 @@
 				this.searchTimer.Reset();
 			}
 
-			this.searchTimer.Start();
+			this.searchTimer.Start();*/
 
 			Tools.PostDebugMessage(string.Format(
 				"{0}: finding nearest relay for {1} ({2})",
@@ -190,12 +251,15 @@
 				this.vessel.id
 			));
 
-			this._firstOccludingBody = null;
+			this.firstOccludingBody = null;
+			this.bestOccludedRelay = null;
 
 			// Set this vessel as checked, so that we don't check it again.
 			RelayDatabase.Instance.CheckedVesselsTable[vessel.id] = true;
 
 			double nearestSqrDistance = double.PositiveInfinity;
+			double bestOccludedSqrDistance = double.PositiveInfinity;
+
 			IAntennaRelay _nearestRelay = null;
 
 			/*
@@ -231,32 +295,71 @@
 					continue;
 				}
 
+				// Find the distance from here to the vessel...
+				double potentialSqrDistance = this.sqrDistanceTo(potentialVessel);
+
 				// Skip vessels to which we do not have line of sight.
-				if (requireLineOfSight &&
-					!this.vessel.hasLineOfSightTo(potentialVessel, out this._firstOccludingBody, radiusRatio))
-				{
+				CelestialBody fob = null;
+
+				if (
+					ARConfiguration.RequireLineOfSight &&
+					!this.vessel.hasLineOfSightTo(potentialVessel, out fob, ARConfiguration.RadiusRatio)
+				)
+				{
+					this.firstOccludingBody = fob;
+
 					Tools.PostDebugMessage(
 						this,
-						"Vessel {0} discarded because we do not have line of sight.",
-						potentialVessel.vesselName
+						"Vessel {0} discarded because we do not have line of sight." +
+						"\npotentialSqrDistance: {1}, bestOccludedSqrDistance: {2}, maxTransmitSqrDistance: {3}" +
+						"\npotentialSqrDistance < bestOccludedSqrDistance: {4}" +
+						"\npotentialSqrDistance < (this.maxTransmitDistance * this.maxTransmitDistance): {5}",
+						potentialVessel.vesselName,
+						potentialSqrDistance, bestOccludedSqrDistance, this.maxTransmitDistance * this.maxTransmitDistance,
+						potentialSqrDistance < bestOccludedSqrDistance,
+						potentialSqrDistance < (this.maxTransmitDistance * this.maxTransmitDistance)
 					);
+
+					if (
+						(potentialSqrDistance < bestOccludedSqrDistance) &&
+						(potentialSqrDistance < (this.maxTransmitDistance * this.maxTransmitDistance))
+					)
+					{
+						Tools.PostDebugMessage(
+							this,
+							"Checking {0} relays on {1}.",
+							potentialVessel.GetAntennaRelays().Count(),
+							potentialVessel
+						);
+
+						foreach (IAntennaRelay occludedRelay in potentialVessel.GetAntennaRelays())
+						{
+							Tools.PostDebugMessage(this, "Checking candidate for bestOccludedRelay: {0}" +
+								"\n\tCanTransmit: {1}", occludedRelay, occludedRelay.CanTransmit());
+							if (occludedRelay.CanTransmit())
+							{
+								this.bestOccludedRelay = occludedRelay;
+								this.firstOccludingBody = fob;
+								bestOccludedSqrDistance = potentialSqrDistance;
+								Tools.PostDebugMessage(this, "Found new bestOccludedRelay: {0}" +
+									"\nfirstOccludingBodoy: {1}" +
+									"\nbestOccludedSqrDistance: {2}",
+									occludedRelay,
+									fob,
+									potentialSqrDistance
+								);
+								break;
+							}
+						}
+					}
+
 					continue;
 				}
 
-				// Find the distance from here to the vessel...
-				double potentialSqrDistance = (potentialVessel.GetWorldPos3D() - vessel.GetWorldPos3D()).sqrMagnitude;
-
 				/*
-				 * ...so that we can skip the vessel if it is further away than Kerbin, our transmit distance, or a
-				 * vessel we've already checked.
+				 * ...so that we can skip the vessel if it is further away than a vessel we've already checked.
 				 * */
-				if (
-					potentialSqrDistance > Tools.Min(
-						this.maxTransmitDistance * this.maxTransmitDistance,
-						nearestSqrDistance,
-						this.vessel.sqrDistanceTo(Kerbin)
-					)
-				)
+				if (potentialSqrDistance > nearestSqrDistance)
 				{
 					Tools.PostDebugMessage(
 						this,
@@ -300,22 +403,7 @@
 			this.moduleRef = module;
 
 			this.searchTimer = new System.Diagnostics.Stopwatch();
-			this.millisecondsBetweenSearches = 5000;
-
-			// HACK: This might not be safe in all circumstances, but since AntennaRelays are not built until Start,
-			// we hope it is safe enough.
-			this.Kerbin = FlightGlobals.Bodies.FirstOrDefault(b => b.name == "Kerbin");
-		}
-
-		static AntennaRelay()
-		{
-			var config = KSP.IO.PluginConfiguration.CreateForType<AntennaRelay>();
-
-			config.load();
-
-			AntennaRelay.requireLineOfSight = config.GetValue<bool>("requireLineOfSight", false);
-
-			config.save();
+			this.millisecondsBetweenSearches = 1250;
 		}
 	}
 }