Extensiblility should be working now! extensible
[VOID.git] / VOID_Core.cs
blob:a/VOID_Core.cs -> blob:b/VOID_Core.cs
--- a/VOID_Core.cs
+++ b/VOID_Core.cs
@@ -21,6 +21,7 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Reflection;
 using KSP;
 using UnityEngine;
 
@@ -54,65 +55,116 @@
 			}
 		}
 
+		public static void Reset()
+		{
+			_instance.StopGUI();
+			_instance = null;
+			_initialized = false;
+		}
+
+		public static double Constant_G = 6.674e-11;
+
 		/*
 		 * Fields
 		 * */
 		protected string VoidName = "VOID";
-		protected string VoidVersion = "0.9.9";
-
-		[AVOID_ConfigValue("configValue")]
-		protected VOID_ConfigValue<int> configVersion = 1;
-
-		protected List<VOID_Module> _modules = new List<VOID_Module>();
+		protected string VoidVersion = "0.9.13";
+
+		protected bool _factoryReset = false;
+
+		[AVOID_SaveValue("configValue")]
+		protected VOID_SaveValue<int> configVersion = 1;
+
+		protected List<IVOID_Module> _modules = new List<IVOID_Module>();
 		protected bool _modulesLoaded = false;
 
-		[AVOID_ConfigValue("mainWindowPos")]
-		protected VOID_ConfigValue<Rect> mainWindowPos = new Rect(Screen.width / 2, Screen.height / 2, 10f, 10f);
-
-		[AVOID_ConfigValue("mainGuiMinimized")]
-		protected VOID_ConfigValue<bool> mainGuiMinimized = false;
-
-		[AVOID_ConfigValue("configWindowPos")]
-		protected VOID_ConfigValue<Rect> configWindowPos = new Rect(Screen.width / 2, Screen.height  /2, 10f, 10f);
-
-		[AVOID_ConfigValue("configWindowMinimized")]
-		protected VOID_ConfigValue<bool> configWindowMinimized = true;
-
-		[AVOID_ConfigValue("VOIDIconPos")]
-		protected VOID_ConfigValue<Rect> VOIDIconPos = new Rect(Screen.width / 2 - 200, Screen.height - 30, 30f, 30f);
+		[AVOID_SaveValue("mainWindowPos")]
+		protected VOID_SaveValue<Rect> mainWindowPos = new Rect(475, 575, 10f, 10f);
+
+		[AVOID_SaveValue("mainGuiMinimized")]
+		protected VOID_SaveValue<bool> mainGuiMinimized = false;
+
+		[AVOID_SaveValue("configWindowPos")]
+		protected VOID_SaveValue<Rect> configWindowPos = new Rect(825, 625, 10f, 10f);
+
+		[AVOID_SaveValue("configWindowMinimized")]
+		protected VOID_SaveValue<bool> configWindowMinimized = true;
+
+		[AVOID_SaveValue("VOIDIconPos")]
+		protected VOID_SaveValue<Rect> VOIDIconPos = new Rect(Screen.width / 2 - 200, Screen.height - 30, 30f, 30f);
 		protected Texture2D VOIDIconOff = new Texture2D(30, 30, TextureFormat.ARGB32, false);
 		protected Texture2D VOIDIconOn = new Texture2D(30, 30, TextureFormat.ARGB32, false);
 		protected Texture2D VOIDIconTexture;
 		protected string VOIDIconOnPath = "VOID/Textures/void_icon_on";
 		protected string VOIDIconOffPath = "VOID/Textures/void_icon_off";
+		protected bool VOIDIconLocked = true;
 
 		protected int windowBaseID = -96518722;
-
-		[AVOID_ConfigValue("togglePower")]
-		public VOID_ConfigValue<bool> togglePower = true;
+		protected int _windowID = 0;
+
+		protected bool GUIStylesLoaded = false;
+
+		protected Dictionary<string, GUIStyle> _LabelStyles = new Dictionary<string, GUIStyle>();
+
+		[AVOID_SaveValue("togglePower")]
+		public VOID_SaveValue<bool> togglePower = true;
 
 		public bool powerAvailable = true;
 
-		[AVOID_ConfigValue("consumeResource")]
-		protected VOID_ConfigValue<bool> consumeResource = false;
-
-		[AVOID_ConfigValue("resourceName")]
-		protected VOID_ConfigValue<string> resourceName = "ElectricCharge";
-
-		[AVOID_ConfigValue("resourceRate")]
-		protected VOID_ConfigValue<float> resourceRate = 0.2f;
+		[AVOID_SaveValue("consumeResource")]
+		protected VOID_SaveValue<bool> consumeResource = false;
+
+		[AVOID_SaveValue("resourceName")]
+		protected VOID_SaveValue<string> resourceName = "ElectricCharge";
+
+		[AVOID_SaveValue("resourceRate")]
+		protected VOID_SaveValue<float> resourceRate = 0.2f;
+
+		[AVOID_SaveValue("updatePeriod")]
+		protected VOID_SaveValue<double> _updatePeriod = 1001f/15000f;
+		protected float _updateTimer = 0f;
+		protected string stringFrequency;
+
+		// Celestial Body Housekeeping
+		protected List<CelestialBody> _allBodies = new List<CelestialBody>();
+		protected bool bodiesLoaded = false;
+
+		// Vessel Type Housekeeping
+		protected List<VesselType> _allVesselTypes = new List<VesselType>();
+		protected bool vesselTypesLoaded = false;
 
 		public float saveTimer = 0;
 
-		protected string defaultSkin = "KSP window 2";
-		protected VOID_ConfigValue<string> _skin;
+		[AVOID_SaveValue("defaultSkin")]
+		protected VOID_SaveValue<string> defaultSkin = "KSP window 2";
+		protected int _skinIdx = int.MinValue;
+		protected List<GUISkin> skin_list;
+		protected string[] forbiddenSkins =
+		{
+			"PlaqueDialogSkin",
+			"FlagBrowserSkin",
+			"SSUITextAreaDefault",
+			"ExperimentsDialogSkin",
+			"ExpRecoveryDialogSkin",
+			"KSP window 5",
+			"KSP window 6"
+		};
+		protected bool skinsLoaded = false;
 
 		public bool configDirty;
 
 		/*
 		 * Properties
 		 * */
-		public List<VOID_Module> Modules
+		public bool factoryReset
+		{
+			get
+			{
+				return this._factoryReset;
+			}
+		}
+
+		public List<IVOID_Module> Modules
 		{
 			get
 			{
@@ -124,19 +176,63 @@
 		{
 			get
 			{
-				if (this._skin == null)
-				{
-					this._skin = this.defaultSkin;
-				}
-				return AssetBase.GetGUISkin(this._skin);
-			}
-		}
-
-		public Vessel vessel
-		{
-			get
-			{
-				return FlightGlobals.ActiveVessel;
+				if (this.skin_list == null || this._skinIdx < 0 || this._skinIdx > this.skin_list.Count)
+				{
+					return AssetBase.GetGUISkin(this.defaultSkin);
+				}
+				return this.skin_list[this._skinIdx];
+			}
+		}
+
+		public int windowID
+		{
+			get
+			{
+				if (this._windowID == 0)
+				{
+				this._windowID = this.windowBaseID;
+				}
+				return this._windowID++;
+			}
+		}
+
+		public Dictionary<string, GUIStyle> LabelStyles
+		{
+			get
+			{
+				return this._LabelStyles;
+			}
+		}
+
+		public List<CelestialBody> allBodies
+		{
+			get
+			{
+				return this._allBodies;
+			}
+		}
+
+		public List<VesselType> allVesselTypes
+		{
+			get
+			{
+				return this._allVesselTypes;
+			}
+		}
+
+		public float updateTimer
+		{
+			get
+			{
+				return this._updateTimer;
+			}
+		}
+
+		public double updatePeriod
+		{
+			get
+			{
+				return this._updatePeriod;
 			}
 		}
 
@@ -147,31 +243,38 @@
 		{
 			this._Name = "VOID Core";
 
+			this._Active = true;
+
 			this.VOIDIconOn = GameDatabase.Instance.GetTexture (this.VOIDIconOnPath, false);
 			this.VOIDIconOff = GameDatabase.Instance.GetTexture (this.VOIDIconOffPath, false);
 
-			Tools.PostDebugMessage (string.Format ("VOID_Core: Loaded {0} modules.", this.Modules.Count));
-
 			this.LoadConfig ();
 		}
 
-		protected void LoadModules()
+		protected void LoadModulesOfType<T>()
 		{
 			var types = AssemblyLoader.loadedAssemblies
 				.Select (a => a.assembly.GetExportedTypes ())
 					.SelectMany (t => t)
-					.Where (v => typeof(IVOID_Module).IsAssignableFrom (v)
+					.Where (v => typeof(T).IsAssignableFrom (v)
 					        && !(v.IsInterface || v.IsAbstract) &&
 					        !typeof(VOID_Core).IsAssignableFrom (v)
 					        );
 
 			Tools.PostDebugMessage (string.Format (
-				"{0}: Checking {1} modules to check.",
+				"{0}: Found {1} modules to check.",
 				this.GetType ().Name,
 				types.Count ()
 				));
 			foreach (var voidType in types)
 			{
+				if (!HighLogic.LoadedSceneIsEditor &&
+				    typeof(IVOID_EditorModule).IsAssignableFrom(voidType)
+				    )
+				{
+					continue;
+				}
+
 				Tools.PostDebugMessage (string.Format (
 					"{0}: found Type {1}",
 					this.GetType ().Name,
@@ -182,6 +285,12 @@
 			}
 
 			this._modulesLoaded = true;
+
+			Tools.PostDebugMessage(string.Format(
+				"{0}: Loaded {1} modules.",
+				this.GetType().Name,
+				this.Modules.Count
+			));
 		}
 
 		protected void LoadModule(Type T)
@@ -196,12 +305,33 @@
 				));
 				return;
 			}
-			this._modules.Add (Activator.CreateInstance (T) as VOID_Module);
+			IVOID_Module module = Activator.CreateInstance (T) as IVOID_Module;
+			module.LoadConfig();
+			this._modules.Add (module);
+
+			Tools.PostDebugMessage(string.Format(
+				"{0}: loaded module {1}.",
+				this.GetType().Name,
+				T.Name
+			));
+		}
+
+		protected void Preload_BeforeUpdate()
+		{
+			if (!this.bodiesLoaded)
+			{
+				this.LoadAllBodies();
+			}
+
+			if (!this.vesselTypesLoaded)
+			{
+				this.LoadVesselTypes();
+			}
 		}
 
 		public void Update()
 		{
-			this.saveTimer += Time.deltaTime;
+			this.Preload_BeforeUpdate ();
 
 			if (!this.guiRunning)
 			{
@@ -213,23 +343,29 @@
 				this.StopGUI ();
 			}
 
-			foreach (VOID_Module module in this.Modules)
+			foreach (IVOID_Module module in this.Modules)
 			{
 				if (!module.guiRunning && module.toggleActive)
 				{
 					module.StartGUI ();
 				}
-				if (module.guiRunning && !module.toggleActive || !this.togglePower || !HighLogic.LoadedSceneIsFlight)
+				if (module.guiRunning && !module.toggleActive ||
+				    !this.togglePower ||
+				    !HighLogic.LoadedSceneIsFlight ||
+				    this.factoryReset
+				    )
 				{
 					module.StopGUI();
 				}
-			}
-
-			if (this.saveTimer > 15f)
-			{
-				this.SaveConfig ();
-				this.saveTimer = 0;
-			}
+
+				if (module is IVOID_BehaviorModule)
+				{
+					((IVOID_BehaviorModule)module).Update();
+				}
+			}
+
+			this.CheckAndSave ();
+			this._updateTimer += Time.deltaTime;
 		}
 
 		public void FixedUpdate()
@@ -250,20 +386,114 @@
 					this.powerAvailable = false;
 				}
 			}
+
+			foreach (IVOID_BehaviorModule module in
+			         this._modules.OfType<IVOID_BehaviorModule>().Where(m => !m.GetType().IsAbstract))
+			{
+				module.FixedUpdate();
+			}
+		}
+
+		protected void LoadSkins()
+		{
+			this.skin_list = AssetBase.FindObjectsOfTypeIncludingAssets(typeof(GUISkin))
+				.Where(s => !this.forbiddenSkins.Contains(s.name))
+					.Select(s => s as GUISkin)
+					.ToList();
+
+			Tools.PostDebugMessage(string.Format(
+				"{0}: loaded {1} GUISkins.",
+				this.GetType().Name,
+				this.skin_list.Count
+			));
+
+			if (this._skinIdx == int.MinValue)
+			{
+				this._skinIdx = this.skin_list.IndexOf(this.Skin);
+				Tools.PostDebugMessage(string.Format(
+					"{0}: resetting _skinIdx to default.",
+					this.GetType().Name
+					));
+			}
+
+			Tools.PostDebugMessage(string.Format(
+				"{0}: _skinIdx = {1}.",
+				this.GetType().Name,
+				this._skinIdx.ToString()
+				));
+
+			this.skinsLoaded = true;
+		}
+
+		protected void LoadGUIStyles()
+		{
+			this.LabelStyles["center"] = new GUIStyle(GUI.skin.label);
+			this.LabelStyles["center"].normal.textColor = Color.white;
+			this.LabelStyles["center"].alignment = TextAnchor.UpperCenter;
+
+			this.LabelStyles["center_bold"] = new GUIStyle(GUI.skin.label);
+			this.LabelStyles["center_bold"].normal.textColor = Color.white;
+			this.LabelStyles["center_bold"].alignment = TextAnchor.UpperCenter;
+			this.LabelStyles["center_bold"].fontStyle = FontStyle.Bold;
+
+			this.LabelStyles["right"] = new GUIStyle(GUI.skin.label);
+			this.LabelStyles["right"].normal.textColor = Color.white;
+			this.LabelStyles["right"].alignment = TextAnchor.UpperRight;
+
+			this.GUIStylesLoaded = true;
+		}
+
+		
+		protected void LoadAllBodies()
+		{
+			this._allBodies = FlightGlobals.Bodies;
+			this.bodiesLoaded = true;
+		}
+
+		protected void LoadVesselTypes()
+		{
+			this._allVesselTypes = Enum.GetValues(typeof(VesselType)).OfType<VesselType>().ToList();
+			this.vesselTypesLoaded = true;
+		}
+
+		protected void CheckAndSave()
+		{
+			this.saveTimer += Time.deltaTime;
+
+			if (this.saveTimer > 2f)
+			{
+				Tools.PostDebugMessage (string.Format (
+					"{0}: Time to save, checking if configDirty: {1}",
+					this.GetType ().Name,
+					this.configDirty
+					));
+
+				if (!this.configDirty)
+				{
+					return;
+				}
+
+				this.SaveConfig ();
+				this.saveTimer = 0;
+			}
 		}
 
 		public void VOIDMainWindow(int _)
 		{
 			GUILayout.BeginVertical();
 			
-			if (this.powerAvailable)
-			{
-				string str = "ON";
-				if (togglePower) str = "OFF";
-				if (GUILayout.Button("Power " + str)) togglePower = !togglePower;
-			    if (togglePower)
+			if (this.powerAvailable || HighLogic.LoadedSceneIsEditor)
+			{
+				if (!HighLogic.LoadedSceneIsEditor)
+				{
+					string str = "ON";
+					if (togglePower) str = "OFF";
+					if (GUILayout.Button("Power " + str)) togglePower = !togglePower;
+				}
+
+				if (togglePower || HighLogic.LoadedSceneIsEditor)
 			    {
-					foreach (VOID_Module module in this.Modules)
+					foreach (IVOID_Module module in this.Modules)
 					{
 						module.toggleActive = GUILayout.Toggle (module.toggleActive, module.Name);
 					}
@@ -287,26 +517,170 @@
 		{
 			GUILayout.BeginVertical ();
 
-			this.consumeResource = GUILayout.Toggle (this.consumeResource, "Consume Resources");
+			this.DrawConfigurables ();
 
 			GUILayout.EndVertical ();
 			GUI.DragWindow ();
 		}
 
+		public override void DrawConfigurables()
+		{
+			if (HighLogic.LoadedSceneIsFlight)
+			{
+				this.consumeResource = GUILayout.Toggle (this.consumeResource, "Consume Resources");
+
+				this.VOIDIconLocked = GUILayout.Toggle (this.VOIDIconLocked, "Lock Icon Position");
+			}
+
+			GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true));
+
+			GUILayout.Label("Skin:", GUILayout.ExpandWidth(false));
+
+			GUIContent _content = new GUIContent();
+
+			_content.text = "◄";
+			_content.tooltip = "Select previous skin";
+			if (GUILayout.Button(_content, GUILayout.ExpandWidth(true)))
+			{
+				this._skinIdx--;
+				if (this._skinIdx < 0) this._skinIdx = skin_list.Count - 1;
+				Tools.PostDebugMessage (string.Format (
+					"{0}: new this._skinIdx = {1} :: skin_list.Count = {2}",
+					this.GetType().Name,
+					this._skinIdx,
+					this.skin_list.Count
+				));
+			}
+
+			string skin_name = skin_list[this._skinIdx].name;
+			_content.text = skin_name;
+			_content.tooltip = "Current skin";
+			GUILayout.Label(_content, this.LabelStyles["center"], GUILayout.ExpandWidth(true));
+
+			_content.text = "►";
+			_content.tooltip = "Select next skin";
+			if (GUILayout.Button(_content, GUILayout.ExpandWidth(true)))
+			{
+				this._skinIdx++;
+				if (this._skinIdx >= skin_list.Count) this._skinIdx = 0;
+				Tools.PostDebugMessage (string.Format (
+					"{0}: new this._skinIdx = {1} :: skin_list.Count = {2}",
+					this.GetType().Name,
+					this._skinIdx,
+					this.skin_list.Count
+					));
+			}
+
+			if (this.Skin.name != this.defaultSkin)
+			{
+				this.defaultSkin = this.Skin.name;
+			}
+
+			GUILayout.EndHorizontal();
+
+			GUILayout.BeginHorizontal();
+			GUILayout.Label("Update Rate (Hz):");
+			if (this.stringFrequency == null)
+			{
+				this.stringFrequency = (1f / this.updatePeriod).ToString();
+			}
+			this.stringFrequency = GUILayout.TextField(this.stringFrequency.ToString(), 5, GUILayout.ExpandWidth(true));
+			// GUILayout.FlexibleSpace();
+			if (GUILayout.Button("Apply"))
+			{
+				double updateFreq = 1f / this.updatePeriod;
+				double.TryParse(stringFrequency, out updateFreq);
+				this._updatePeriod = 1 / updateFreq;
+			}
+			GUILayout.EndHorizontal();
+
+			foreach (IVOID_Module mod in this.Modules)
+			{
+				mod.DrawConfigurables ();
+			}
+
+			this._factoryReset = GUILayout.Toggle (this._factoryReset, "Factory Reset");
+		}
+
+		public void OnGUI()
+		{
+			if (Event.current.type == EventType.Repaint)
+			{
+				return;
+			}
+
+			/*
+			Tools.PostDebugMessage(string.Format(
+				"Event.current.type: {0}" +
+				"\nthis.VOIDIconLocked: {1}" +
+				"\nEvent.current.mousePosition: {2}" +
+				"\nVOIDIconPos: ({3}, {4}),({5}, {6})",
+				Event.current.type,
+				this.VOIDIconLocked,
+				Event.current.mousePosition,
+				this.VOIDIconPos.value.xMin,
+				this.VOIDIconPos.value.yMin,
+				this.VOIDIconPos.value.xMax,
+				this.VOIDIconPos.value.yMax
+				));
+				*/
+
+			if (!this.VOIDIconLocked &&
+			    VOIDIconPos.value.Contains(Event.current.mousePosition)
+			    && Event.current.type == EventType.mouseDrag
+			    )
+			{
+				Tools.PostDebugMessage(string.Format(
+					"Event.current.type: {0}" +
+					"\ndelta.x: {1}; delta.y: {2}",
+					Event.current.type,
+					Event.current.delta.x,
+					Event.current.delta.y
+				));
+
+				Rect tmp = new Rect(VOIDIconPos);
+
+				tmp.x = Event.current.mousePosition.x - tmp.width / 2;
+				tmp.y = Event.current.mousePosition.y - tmp.height / 2;
+
+				if (tmp.x > Screen.width - tmp.width)
+				{
+					tmp.x = Screen.width - tmp.width;
+				}
+
+				if (tmp.y > Screen.height - tmp.height)
+				{
+					tmp.y = Screen.height - tmp.height;
+				}
+
+				VOIDIconPos = tmp;
+			}
+		}
+
 		public override void DrawGUI()
 		{
 			if (!this._modulesLoaded)
 			{
-				this.LoadModules ();
+				this.LoadModulesOfType<IVOID_Module> ();
+			}
+
+			this._windowID = this.windowBaseID;
+
+			if (!this.skinsLoaded)
+			{
+				this.LoadSkins();
 			}
 
 			GUI.skin = this.Skin;
 
-			int windowID = this.windowBaseID;
-
-            this.VOIDIconTexture = this.VOIDIconOff;  //icon off default
+			if (!this.GUIStylesLoaded)
+			{
+				this.LoadGUIStyles ();
+			}
+
+			this.VOIDIconTexture = this.VOIDIconOff;  //icon off default
 			if (this.togglePower) this.VOIDIconTexture = this.VOIDIconOn;     //or on if power_toggle==true
-			if (GUI.Button(new Rect(VOIDIconPos), VOIDIconTexture, new GUIStyle()))
+			if (GUI.Button(VOIDIconPos, VOIDIconTexture, new GUIStyle()) && this.VOIDIconLocked)
 			{
 				this.mainGuiMinimized = !this.mainGuiMinimized;
 			}
@@ -316,7 +690,7 @@
 				Rect _mainWindowPos = this.mainWindowPos;
 
 				_mainWindowPos = GUILayout.Window (
-					++windowID,
+					this.windowID,
 					_mainWindowPos,
 					this.VOIDMainWindow,
 					string.Join (" ", new string[] {this.VoidName, this.VoidVersion}),
@@ -324,18 +698,20 @@
 					GUILayout.Height (50)
 				);
 
-				if (_mainWindowPos != this.mainWindowPos.value)
+				_mainWindowPos = Tools.ClampRectToScreen (_mainWindowPos);
+
+				if (_mainWindowPos != this.mainWindowPos)
 				{
 					this.mainWindowPos = _mainWindowPos;
 				}
 			}
 
-			if (!this.configWindowMinimized)
+			if (!this.configWindowMinimized && !this.mainGuiMinimized)
 			{
 				Rect _configWindowPos = this.configWindowPos;
 
-				this.configWindowPos = GUILayout.Window (
-					++windowID,
+				_configWindowPos = GUILayout.Window (
+					this.windowID,
 					_configWindowPos,
 					this.VOIDConfigWindow,
 					string.Join (" ", new string[] {this.VoidName, "Configuration"}),
@@ -343,36 +719,51 @@
 					GUILayout.Height (50)
 				);
 
-				if (_configWindowPos != this.configWindowPos.value)
-				{
-					this.mainWindowPos = _configWindowPos;
-				}
-			}
+				_configWindowPos = Tools.ClampRectToScreen (_configWindowPos);
+
+				if (_configWindowPos != this.configWindowPos)
+				{
+					this.configWindowPos = _configWindowPos;
+				}
+			}
+		}
+
+		public void ResetGUI()
+		{
+			this.StopGUI ();
+
+			foreach (IVOID_Module module in this.Modules)
+			{
+				module.StopGUI ();
+				module.StartGUI ();
+			}
+
+			this.StartGUI ();
 		}
 
 		public override void LoadConfig()
 		{
 			base.LoadConfig ();
 
-			foreach (VOID_Module module in this.Modules)
+			foreach (IVOID_Module module in this.Modules)
 			{
 				module.LoadConfig ();
 			}
 		}
 
-		public override void SaveConfig()
-		{
-			if (!this.configDirty)
-			{
-				return;
-			}
-
-			base.SaveConfig ();
-
-			foreach (VOID_Module module in this.Modules)
-			{
-				module.SaveConfig ();
-			}
+		public void SaveConfig()
+		{
+			var config = KSP.IO.PluginConfiguration.CreateForType<VOID_Core> ();
+			config.load ();
+
+			this._SaveToConfig(config);
+
+			foreach (IVOID_Module module in this.Modules)
+			{
+				module._SaveToConfig (config);
+			}
+
+			config.save();
 
 			this.configDirty = false;
 		}