* AntennaRelay.cs:
[AntennaRange.git] / AntennaRelay.cs
blob:a/AntennaRelay.cs -> blob:b/AntennaRelay.cs
--- a/AntennaRelay.cs
+++ b/AntennaRelay.cs
@@ -1,39 +1,75 @@
-// AntennaRange © 2014 toadicus
-//
-// AntennaRange provides incentive and requirements for the use of the various antenna parts.
-// Nominally, the breakdown is as follows:
-//
-//     Communotron 16 - Suitable up to Kerbalsynchronous Orbit
-//     Comms DTS-M1 - Suitable throughout the Kerbin subsystem
-//     Communotron 88-88 - Suitable throughout the Kerbol system.
-//
-// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
-// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
-//
-// This software uses the ModuleManager library © 2013 ialdabaoth, used under a Creative Commons Attribution-ShareAlike
-// 3.0 Uported License.
-//
-// This software uses code from the MuMechLib library, © 2013 r4m0n, used under the GNU GPL version 3.
+// AntennaRange
+//
+// AntennaRelay.cs
+//
+// Copyright © 2014, toadicus
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+//    this list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+//    this list of conditions and the following disclaimer in the documentation and/or other
+//    materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its contributors may be used
+//    to endorse or promote products derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 using System;
 using System.Collections.Generic;
 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 : IAntennaRelay
+	public class AntennaRelay
 	{
 		// We don't have a Bard, so we'll hide Kerbin here.
-		protected CelestialBody Kerbin;
+		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;
+		protected long millisecondsBetweenSearches;
 
 		/// <summary>
 		/// Gets the parent Vessel.
 		/// </summary>
 		/// <value>The parent Vessel.</value>
-		public Vessel vessel
-		{
-			get;
-			protected set;
+		public virtual Vessel vessel
+		{
+			get
+			{
+				return this.moduleRef.vessel;
+			}
 		}
 
 		/// <summary>
@@ -42,6 +78,35 @@
 		/// <value>The nearest relay</value>
 		public IAntennaRelay nearestRelay
 		{
+			get
+			{
+				if (!this.searchTimer.IsRunning ||
+					this.searchTimer.ElapsedMilliseconds > this.millisecondsBetweenSearches)
+				{
+					this._nearestRelayCache = this.FindNearestRelay();
+
+					this.searchTimer.Restart();
+				}
+
+				return this._nearestRelayCache;
+			}
+			protected set
+			{
+				this._nearestRelayCache = value;
+			}
+		}
+
+		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;
 		}
@@ -54,20 +119,40 @@
 		{
 			get
 			{
-				this.nearestRelay = this.FindNearestRelay();
-
 				// If there is no available relay nearby...
-				if (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>
@@ -91,18 +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 bool CanTransmit()
-		{
+		public virtual bool CanTransmit()
+		{
+			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)
+				)
+				{
+					this.firstOccludingBody = fob;
+					return false;
+				}
+
+				this.firstOccludingBody = null;
 				return true;
 			}
 		}
@@ -111,146 +229,181 @@
 		/// Finds the nearest relay.
 		/// </summary>
 		/// <returns>The nearest relay or null, if no relays in range.</returns>
-		public IAntennaRelay FindNearestRelay()
-		{
-			// Set this relay as checked, so that we don't check it again.
-			this.relayChecked = true;
-
-			// Get a list of vessels within transmission range.
-			List<Vessel> nearbyVessels = FlightGlobals.Vessels
-				.Where(v => (v.GetWorldPos3D() - vessel.GetWorldPos3D()).magnitude < this.maxTransmitDistance)
-					.ToList();
-
-			nearbyVessels.RemoveAll(v => v.vesselType == VesselType.Debris);
+		private IAntennaRelay FindNearestRelay()
+		{
+			/*if (this.searchTimer.IsRunning && this.searchTimer.ElapsedMilliseconds < this.millisecondsBetweenSearches)
+			{
+				return this.nearestRelay;
+			}
+
+			if (this.searchTimer.IsRunning)
+			{
+				this.searchTimer.Stop();
+				this.searchTimer.Reset();
+			}
+
+			this.searchTimer.Start();*/
 
 			Tools.PostDebugMessage(string.Format(
-				"{0}: Non-debris vessels in range: {1}",
+				"{0}: finding nearest relay for {1} ({2})",
 				this.GetType().Name,
-				nearbyVessels.Count
-				));
-
-			// Remove this vessel.
-			nearbyVessels.RemoveAll(v => v.id == vessel.id);
-
-			Tools.PostDebugMessage(string.Format(
-				"{0}: Vessels in range excluding self: {1}",
-				this.GetType().Name,
-				nearbyVessels.Count
-				));
-
-			// Get a flattened list of all IAntennaRelay modules and protomodules in transmission range.
-			List<IAntennaRelay> nearbyRelays = nearbyVessels.SelectMany(v => v.GetAntennaRelays()).ToList();
-
-			Tools.PostDebugMessage(string.Format(
-				"{0}: Found {1} nearby relays.",
-				this.GetType().Name,
-				nearbyRelays.Count
-				));
-
-			// Remove all relays already checked this time.
-			nearbyRelays.RemoveAll(r => r.relayChecked);
-
-			Tools.PostDebugMessage(string.Format(
-				"{0}: Found {1} nearby relays not already checked.",
-				this.GetType().Name,
-				nearbyRelays.Count
-				));
-
-			// Remove all relays that cannot transmit.
-			// This call to r.CanTransmit() starts a depth-first recursive search for relays with a path back to Kerbin.
-			nearbyRelays.RemoveAll(r => !r.CanTransmit());
-
-			Tools.PostDebugMessage(string.Format(
-				"{0}: Found {1} nearby relays not already checked that can transmit.",
-				this.GetType().Name,
-				nearbyRelays.Count
-				));
-
-			// Sort the available relays by distance.
-			nearbyRelays.Sort(new RelayComparer(this.vessel));
-
-			// Get the nearest available relay, or null if there are no available relays nearby.
-			IAntennaRelay _nearestRelay = nearbyRelays.FirstOrDefault();
-
-			// If we have a nearby relay...
-			if (_nearestRelay != null)
-			{
-				// ...but that relay is farther than Kerbin...
-				if (this.DistanceTo(_nearestRelay) > this.DistanceTo(Kerbin))
-				{
-					// ...just use Kerbin.
-					_nearestRelay = null;
+				this,
+				this.vessel.id
+			));
+
+			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;
+
+			/*
+			 * Loop through all the vessels and exclude this vessel, vessels of the wrong type, and vessels that are too
+			 * far away.  When we find a candidate, get through its antennae for relays which have not been checked yet
+			 * and that can transmit.  Once we find a suitable candidate, assign it to _nearestRelay for comparison
+			 * against future finds.
+			 * */
+			foreach (Vessel potentialVessel in FlightGlobals.Vessels)
+			{
+				// Skip vessels that have already been checked for a nearest relay this pass.
+				if (RelayDatabase.Instance.CheckedVesselsTable.ContainsKey(potentialVessel.id))
+				{
+					continue;
+				}
+
+				// Skip vessels of the wrong type.
+				switch (potentialVessel.vesselType)
+				{
+					case VesselType.Debris:
+					case VesselType.Flag:
+					case VesselType.EVA:
+					case VesselType.SpaceObject:
+					case VesselType.Unknown:
+						continue;
+					default:
+						break;
+				}
+
+				// Skip vessels with the wrong ID
+				if (potentialVessel.id == vessel.id)
+				{
+					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.
+				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." +
+						"\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;
+				}
+
+				/*
+				 * ...so that we can skip the vessel if it is further away than a vessel we've already checked.
+				 * */
+				if (potentialSqrDistance > nearestSqrDistance)
+				{
+					Tools.PostDebugMessage(
+						this,
+						"Vessel {0} discarded because it is out of range, or farther than another relay.",
+						potentialVessel.vesselName
+					);
+					continue;
+				}
+
+				nearestSqrDistance = potentialSqrDistance;
+
+				foreach (IAntennaRelay potentialRelay in potentialVessel.GetAntennaRelays())
+				{
+					if (potentialRelay.CanTransmit())
+					{
+						_nearestRelay = potentialRelay;
+						Tools.PostDebugMessage(string.Format("{0}: found new best relay {1} ({2})",
+							this.GetType().Name,
+							_nearestRelay.ToString(),
+							_nearestRelay.vessel.id
+						));
+						break;
+					}
 				}
 			}
 
 			// Now that we're done with our recursive CanTransmit checks, flag this relay as not checked so it can be
 			// used next time.
-			this.relayChecked = false;
+			RelayDatabase.Instance.CheckedVesselsTable.Remove(vessel.id);
 
 			// Return the nearest available relay, or null if there are no available relays nearby.
 			return _nearestRelay;
 		}
 
-		public override string ToString()
-		{
-			return string.Format(
-				"Antenna relay on vessel {0} (range to relay: {1}m)",
-				vessel,
-				Tools.MuMech_ToSI(transmitDistance)
-			);
-		}
-
 		/// <summary>
 		/// Initializes a new instance of the <see cref="AntennaRange.ProtoDataTransmitter"/> class.
 		/// </summary>
 		/// <param name="ms"><see cref="ProtoPartModuleSnapshot"/></param>
-		public AntennaRelay(Vessel v)
-		{
-			this.vessel = v;
-
-			// 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");
-		}
-
-		/*
-		 * Class implementing IComparer<IAntennaRelay> for use in sorting relays by distance.
-		 * */
-		internal class RelayComparer : IComparer<IAntennaRelay>
-		{
-			/// <summary>
-			/// The reference Vessel (usually the active vessel).
-			/// </summary>
-			protected Vessel referenceVessel;
-
-			// We don't want no stinking public parameterless constructors.
-			private RelayComparer() {}
-
-			/// <summary>
-			/// Initializes a new instance of the <see cref="AntennaRange.AntennaRelay+RelayComparer"/> class for use
-			/// in sorting relays by distance.
-			/// </summary>
-			/// <param name="reference">The reference Vessel</param>
-			public RelayComparer(Vessel reference)
-			{
-				this.referenceVessel = reference;
-			}
-
-			/// <summary>
-			/// Compare the <see cref="IAntennaRelay"/>s "one" and "two".
-			/// </summary>
-			/// <param name="one">The first IAntennaRelay in the comparison</param>
-			/// <param name="two">The second IAntennaRelay in the comparison</param>
-			public int Compare(IAntennaRelay one, IAntennaRelay two)
-			{
-				double distanceOne;
-				double distanceTwo;
-
-				distanceOne = one.vessel.DistanceTo(referenceVessel);
-				distanceTwo = two.vessel.DistanceTo(referenceVessel);
-
-				return distanceOne.CompareTo(distanceTwo);
-			}
+		public AntennaRelay(IAntennaRelay module)
+		{
+			this.moduleRef = module;
+
+			this.searchTimer = new System.Diagnostics.Stopwatch();
+			this.millisecondsBetweenSearches = 1250;
 		}
 	}
 }