From 459abc27794d7bd7146b8d4e1866024dd8906bdd Mon Sep 17 00:00:00 2001 From: Kragrathea Date: Mon, 6 Jan 2014 23:47:45 -0800 Subject: [PATCH 1/4] PlanetFactoryCE Inital --- PlanetFactory/DebugConsole.cs | 276 +++++++++++ PlanetFactory/GUI.cs | 273 +++++++++-- PlanetFactory/PFEffects.cs | 4 +- PlanetFactory/PFExport.cs | 21 +- PlanetFactory/PFMods.cs | 10 + PlanetFactory/PFUtil.cs | 424 +++++++++++++++++ PlanetFactory/PlanetFactory.cs | 739 +++++++++++++++++++++-------- PlanetFactory/PlanetFactory.csproj | 7 +- 8 files changed, 1503 insertions(+), 251 deletions(-) create mode 100644 PlanetFactory/DebugConsole.cs diff --git a/PlanetFactory/DebugConsole.cs b/PlanetFactory/DebugConsole.cs new file mode 100644 index 0000000..e24f569 --- /dev/null +++ b/PlanetFactory/DebugConsole.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using UnityEngine; +using System.Collections; + +namespace PlanetFactory +{ + public class DebugConsole : MonoBehaviour + { + + struct ConsoleMessage + { + public readonly string message; + //public readonly string stackTrace; + public readonly LogType type; + + public ConsoleMessage(string message, LogType type) + { + this.message = message; + //this.stackTrace = stackTrace; + this.type = type; + } + } + + public KeyCode toggleKey = KeyCode.BackQuote; + + static List entries = new List(); + static Vector2 scrollPos; + public static bool show; + bool collapse; + + // Visual elements: + + GUIContent[] comboBoxList; + private ComboBox comboBoxControl = null; + private GUIStyle listStyle = new GUIStyle(); + + private void InitComboBox() + { + comboBoxList = PlanetFactory.Instance.newBodies.Select(x => new GUIContent(x.name)).ToArray(); + + //comboBoxControl.SelectedItemIndex = PlanetFactory.Instance.newBodies.FindIndex(x => x.name == curPlanetName); + listStyle.normal.textColor = Color.white; + listStyle.onHover.background = + listStyle.hover.background = new Texture2D(2, 2); + listStyle.hover.textColor = Color.blue; + listStyle.padding.left = + listStyle.padding.right = + listStyle.padding.top = + listStyle.padding.bottom = 4; + comboBoxControl = new ComboBox(); + } + + const int margin = 15; + Rect windowRect = new Rect((Screen.width / 2)-margin, margin, Screen.width / 2, Screen.height / 2); + + GUIContent clearLabel = new GUIContent("Clear", "Clear the contents of the console."); + GUIContent collapseLabel = new GUIContent("Collapse", "Hide repeated messages."); + + //void OnEnable() { Application.RegisterLogCallback(HandleLog); } + //void OnDisable() { Application.RegisterLogCallback(null); } + + static void ScrollToEnd() + { + scrollPos =new Vector2(0,9999999); + } + + void Update() + { + if (Input.GetKeyDown(toggleKey)) + { + show = !show; + } + } + + void OnGUI() + { + if (!show) + { + return; + } + + windowRect = GUILayout.Window(123456, windowRect, ConsoleWindow, "PlanetFactory Log"); + } + + /// + /// A window displaying the logged messages. + /// + /// The window's ID. + void ConsoleWindow(int windowID) + { + +// GUILayout.BeginHorizontal(); + +// // Clear button +// //if (GUILayout.Button(clearLabel)) +// //{ +// // entries.Clear(); +// //} +// // Collapse toggle +// //collapse = GUILayout.Toggle(collapse, collapseLabel, GUILayout.ExpandWidth(false)); + +//// return; +// try +// { +// if (FlightGlobals.currentMainBody != null) +// { +// var curBodyName = FlightGlobals.currentMainBody.bodyName; + +// if (GUILayout.Button("Reload " + curBodyName)) +// { +// var pfBody = PFUtil.FindPFBody(curBodyName); +// PlanetFactory.SetPathFor(pfBody); + +// PlanetFactory.LoadPQS(curBodyName); + +// var cb = PFUtil.FindCB(curBodyName); +// if (cb) +// { +// PlanetFactory.LoadCB(cb); +// PlanetFactory.LoadOrbit(cb); +// } +// PlanetFactory.SetPathFor(null); +// } +// if (GUILayout.Button("Reload scaled " + curBodyName)) +// { +// var pfBody = PFUtil.FindPFBody(curBodyName); +// PlanetFactory.SetPathFor(pfBody); +// PlanetFactory.PFBody.LoadScaledPlanet(PFUtil.FindScaled(curBodyName), curBodyName, true); +// PlanetFactory.SetPathFor(null); +// } + +// if (GUILayout.Button("Export " + curBodyName)) +// { +// var width = 2048; +// if (FlightGlobals.currentMainBody.Radius < 50000) +// width = 1024; + +// var pfBody = PFUtil.FindPFBody(curBodyName); +// PlanetFactory.SetPathFor(pfBody); +// PFExport.CreateScaledSpacePlanet(curBodyName, pfBody.templateName, null, width, 20000); +// PlanetFactory.SetPathFor(null); + +// } + + +// //if (comboBoxControl == null) +// // InitComboBox(); + + +// } +// } +// finally +// { +// PlanetFactory.SetPathFor(null); +// } + + +// GUILayout.EndHorizontal(); + + if (GUI.Button(new Rect(3, 3, 20, 20), "X")) + { + show = false; + } + + scrollPos = GUILayout.BeginScrollView(scrollPos); + // Go through each logged entry + for (int i = 0; i < entries.Count; i++) + { + ConsoleMessage entry = entries[i]; + + // If this message is the same as the last one and the collapse feature is chosen, skip it + if (collapse && i > 0 && entry.message == entries[i - 1].message) + { + continue; + } + + // Change the text colour according to the log type + switch (entry.type) + { + case LogType.Error: + case LogType.Exception: + GUI.contentColor = Color.red; + break; + + case LogType.Warning: + GUI.contentColor = Color.yellow; + break; + + default: + GUI.contentColor = Color.white; + break; + } + + GUILayout.Label(entry.message,GUILayout.MaxHeight(15)); + } + + GUI.contentColor = Color.white; + + GUILayout.EndScrollView(); + + //if (comboBoxControl != null) + //{ + // var selectedItemIndex = comboBoxControl.SelectedItemIndex; + // selectedItemIndex = comboBoxControl.List( + // new Rect(20, 40, 160, 20), comboBoxList[selectedItemIndex].text, comboBoxList, listStyle); + //} + + // Set the window to be draggable by the top title bar + GUI.DragWindow(new Rect(0, 0, 10000, 20)); + + + windowRect = ResizeWindow(windowRect, ref isResizing, ref windowResizeStart, minWindowSize); + + } + + + bool isResizing = false; + Rect windowResizeStart = new Rect(); + Vector2 minWindowSize = new Vector2(75, 50); + static GUIStyle styleWindowResize = null; + static GUIContent gcDrag = new GUIContent("//", "drag to resize"); + + public static Rect ResizeWindow(Rect windowRect, ref bool isResizing, ref Rect resizeStart, Vector2 minWindowSize) + { + if (styleWindowResize == null) + { + // this is a custom style that looks like a // in the lower corner + styleWindowResize = GUI.skin.GetStyle("WindowResizer"); + } + + Vector2 mouse = GUIUtility.ScreenToGUIPoint(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y)); + Rect r = GUILayoutUtility.GetRect(gcDrag, styleWindowResize); + r.x = windowRect.width - 25; + r.y = windowRect.height - 25; + r.width = 25; + r.height = 25; + + if (Event.current.type == EventType.mouseDown && r.Contains(mouse)) + { + isResizing = true; + resizeStart = new Rect(mouse.x, mouse.y, windowRect.width, windowRect.height); + //Event.current.Use(); // the GUI.Button below will eat the event, and this way it will show its active state + } + else if (Event.current.type == EventType.mouseUp && isResizing) + { + isResizing = false; + } + else if (!Input.GetMouseButton(0)) + { + // if the mouse is over some other window we won't get an event, this just kind of circumvents that by checking the button state directly + isResizing = false; + } + else if (isResizing) + { + windowRect.width = Mathf.Max(minWindowSize.x, resizeStart.width + (mouse.x - resizeStart.x)); + windowRect.height = Mathf.Max(minWindowSize.y, resizeStart.height + (mouse.y - resizeStart.y)); + windowRect.xMax = Mathf.Min(Screen.width, windowRect.xMax); // modifying xMax affects width, not x + windowRect.yMax = Mathf.Min(Screen.height, windowRect.yMax); // modifying yMax affects height, not y + } + + GUI.Button(r, gcDrag, styleWindowResize); + + return windowRect; + } + + public static void Log(string message, LogType type=LogType.Log) + { + ConsoleMessage entry = new ConsoleMessage(message, type); + entries.Add(entry); + ScrollToEnd(); + } + } +} diff --git a/PlanetFactory/GUI.cs b/PlanetFactory/GUI.cs index 587efcf..2ab3c31 100644 --- a/PlanetFactory/GUI.cs +++ b/PlanetFactory/GUI.cs @@ -34,7 +34,9 @@ private void InitComboBox() private Texture2D logoTexture; - public Rect windowRect = new Rect(20, 20, 410, 250); + public Rect logoWindowRect = new Rect(20, 40, 410, 250); + public Rect utilWindowRect = new Rect(20, 40, 210, 20); + public Rect planetWindowRect = new Rect(300, 20, 210, 20); void LogoWindow(int windowID) { @@ -42,23 +44,36 @@ void LogoWindow(int windowID) logoTexture = PFUtil.LoadTexture(DataPath + "logo_small.png"); if (logoTexture != null) GUI.DrawTexture(new Rect(4, 20, logoTexture.width, logoTexture.height), logoTexture); - isFactoryEnabled = GUI.Toggle(new Rect(10, 20, 320, 20), isFactoryEnabled, "Load Sentar Expansion"); - + var yOff = 20; + isFactoryEnabled = GUI.Toggle(new Rect(10, yOff, 320, 20), isFactoryEnabled, "Load Sentar Expansion"); + yOff += 20; + //isSystemEnabled = GUI.Toggle(new Rect(10, yOff, 320, 20), isSystemEnabled, "Load System CFG"); + //yOff += 20; + foreach (var s in PlanetFactory.Instance.Systems) + { + s.enabled = GUI.Toggle(new Rect(10, yOff, 320, 20), s.enabled, string.Format("Load {0} System", s.name)); + yOff += 20; + } + if (GUI.changed) + { + SaveConfig(); + } + GUI.DragWindow(new Rect(0, 0, 10000, 20)); } - private void OnGUI() + private void oldOnGUI() { if (!isTooLateToLoad) { - windowRect = GUI.Window(0, windowRect, LogoWindow, "Krags Planet Factory"); + logoWindowRect = GUI.Window(0, logoWindowRect, LogoWindow, "Krags Planet Factory"); - autoLoadSave = GUI.Toggle(new Rect(20, 280, 160, 20), autoLoadSave, "Auto Load Savegame->"); + //autoLoadSave = GUI.Toggle(new Rect(20, 280, 160, 20), autoLoadSave, "Auto Load Savegame->"); - int selectedItemIndex = comboBoxControl.SelectedItemIndex; - selectedItemIndex = comboBoxControl.List( - new Rect(170, 280, 160, 20), comboBoxList[selectedItemIndex].text, comboBoxList, listStyle); + //int selectedItemIndex = comboBoxControl.SelectedItemIndex; + //selectedItemIndex = comboBoxControl.List( + // new Rect(170, 280, 160, 20), comboBoxList[selectedItemIndex].text, comboBoxList, listStyle); - autoLoadSaveName = comboBoxList[selectedItemIndex].text; + //autoLoadSaveName = comboBoxList[selectedItemIndex].text; if (GUI.changed) { @@ -66,48 +81,246 @@ private void OnGUI() } } -#if DEBUG + if (guiHidden) return; if (FlightGlobals.currentMainBody == null) return; + try + { + var curBodyName = FlightGlobals.currentMainBody.bodyName; + + if (GUI.Button(new Rect(20, 60, 100, 20), "Reload " + curBodyName)) + { + var pfBody = PFUtil.FindPFBody(curBodyName); + PlanetFactory.SetPathFor(pfBody); + + LoadPQS(curBodyName); + + var cb = PFUtil.FindCB(curBodyName); + if (cb) + { + LoadCB(cb); + LoadOrbit(cb); + } + PlanetFactory.SetPathFor(null); + } + if (GUI.Button(new Rect(20, 80, 100, 20), "Reload scaled " + curBodyName)) + { + var pfBody = PFUtil.FindPFBody(curBodyName); + PlanetFactory.SetPathFor(pfBody); + PFBody.LoadScaledPlanet(PFUtil.FindScaled(curBodyName), curBodyName, true); + PlanetFactory.SetPathFor(null); + } + + if (GUI.Button(new Rect(20, 120, 100, 20), "Export " + curBodyName)) + { + var width = 2048; + if (FlightGlobals.currentMainBody.Radius < 50000) + width = 1024; + + var pfBody = PFUtil.FindPFBody(curBodyName); + PlanetFactory.SetPathFor(pfBody); + PFExport.CreateScaledSpacePlanet(curBodyName, pfBody.templateName, null, width, 20000); + PlanetFactory.SetPathFor(null); + + } + if (GUI.Button(new Rect(20, 140, 100, 20), "Test Effects" + curBodyName)) + { + PFEffects.TestEffects(PFUtil.FindScaled(curBodyName)); + } + } + finally + { + PlanetFactory.SetPathFor(null); + } + } - var curBodyName=FlightGlobals.currentMainBody.bodyName; - if (GUI.Button(new Rect(20, 60, 100, 20), "Reload " + curBodyName)) + void OnGUI() + { + if (!isTooLateToLoad) { - LoadPQS(curBodyName); + logoWindowRect = GUI.Window(0, logoWindowRect, LogoWindow, "Krags Planet Factory"); - var cb = PFUtil.FindCB(curBodyName); - if (cb) + if (GUI.changed) { - LoadCB(cb); - LoadOrbit(cb); + SaveConfig(); } } - if (GUI.Button(new Rect(20, 80, 100, 20), "Reload scaled " + curBodyName)) + if (guiHidden) + return; + utilWindowRect = GUILayout.Window(2378942, utilWindowRect, UtilWindow, "PlanetFactory"); + + if(showPlanetWindow && FlightGlobals.ActiveVessel!=null) + planetWindowRect = GUILayout.Window(5533442, planetWindowRect, PlanetWindow, "Go To"); + + + } + bool showPlanetWindow = false; + bool showPlanetPicker = false; + float altitudeScalar = 0.3f; + void PlanetWindow(int windowID) + { + + + GUILayout.BeginVertical(); + GUILayout.Label("Altitude"); + altitudeScalar = GUILayout.HorizontalSlider(altitudeScalar, 0.1f, 3.95f); + + if (GUI.changed) + { + var body = PFUtil.FindCB(FlightGlobals.currentMainBody.name); + var oldOrbit = FlightGlobals.ActiveVessel.orbitDriver.orbit; + //var newOrbit =new Orbit(oldOrbit.inclination,oldOrbit.E, body.Radius + (body.Radius * altitudeScalar) + // ,oldOrbit.LAN, 0,oldOrbit.epoch,0,oldOrbit.referenceBody); + + //PFUtil.HardsetOrbit(FlightGlobals.ActiveVessel.orbitDriver.orbit, newOrbit); + + //var body = PFUtil.FindCB(planet.name); + var orbit = new Orbit(oldOrbit.inclination, oldOrbit.E, body.Radius + (body.Radius * altitudeScalar), 0, 0, oldOrbit.meanAnomalyAtEpoch, 0, body); + + PFUtil.WarpShip(FlightGlobals.ActiveVessel, orbit); + + } + if (GUI.Button(new Rect(3, 3, 20, 20), "X")) { - PFBody.LoadScaledPlanet(PFUtil.FindScaled(curBodyName), curBodyName, true); + showPlanetWindow = false; + planetWindowRect.height = 20; } + - if (GUI.Button(new Rect(20, 120, 100, 20), "Export " + curBodyName)) + if (GUILayout.Button("Planet Picker")) + { + showPlanetPicker = !showPlanetPicker; + planetWindowRect.height = 20; + } + if (showPlanetPicker) + { + foreach (var planet in newBodies) + { + if (GUILayout.Button(planet.name)) + { + PFUtil.Log(planet.name); + + var body = PFUtil.FindCB(planet.name); + var orbit = new Orbit(0, 0, body.Radius + (body.Radius * altitudeScalar), 0, 0, 0, 0, body); + + PFUtil.WarpShip(FlightGlobals.ActiveVessel, orbit); + + showPlanetPicker = false; + planetWindowRect.height = 20; + //Set(CreateOrbit(0, 0, body.Radius + (body.Radius / 3), 0, 0, 0, 0, body)); + + } + } + + } + GUILayout.EndVertical(); + GUI.contentColor = Color.white; + + GUI.DragWindow(new Rect(0, 0, 10000, 20)); + } + void UtilWindow(int windowID) + { + if (GUI.Button(new Rect(3, 3, 20, 20), "X")) + { + guiHidden = true; + } + + GUILayout.BeginVertical(); + + try + { + if (GUILayout.Button("Toggle Log")) + { + DebugConsole.show = !DebugConsole.show; + } + if (FlightGlobals.ActiveVessel!=null) + { + if (GUILayout.Button("Go To...")) + { + showPlanetWindow = !showPlanetWindow; + } + } + + if (FlightGlobals.currentMainBody != null && newBodies.Any(x=>x.name==currentBodyName)) + { + var curBodyName = FlightGlobals.currentMainBody.bodyName; + + GUILayout.Label("Current Planet:" + curBodyName); + if (GUILayout.Button("Reload CFG")) + { + var pfBody = PFUtil.FindPFBody(curBodyName); + PlanetFactory.SetPathFor(pfBody); + + PlanetFactory.LoadPQS(curBodyName); + + var cb = PFUtil.FindCB(curBodyName); + if (cb) + { + PlanetFactory.LoadCB(cb); + PlanetFactory.LoadOrbit(cb); + } + PlanetFactory.SetPathFor(null); + } + //if (GUILayout.Button("Reload scaled " + curBodyName)) + //{ + // var pfBody = PFUtil.FindPFBody(curBodyName); + // PlanetFactory.SetPathFor(pfBody); + // PlanetFactory.PFBody.LoadScaledPlanet(PFUtil.FindScaled(curBodyName), curBodyName, true); + // PlanetFactory.SetPathFor(null); + //} + + if (GUILayout.Button("Create Scaled")) + { + var width = 2048; + if (FlightGlobals.currentMainBody.Radius < 50000) + width = 1024; + + var pfBody = PFUtil.FindPFBody(curBodyName); + PlanetFactory.SetPathFor(pfBody); + PFExport.CreateScaledSpacePlanet(curBodyName, pfBody.templateName, null, width, 20000); + PlanetFactory.PFBody.LoadScaledPlanet(PFUtil.FindScaled(curBodyName), curBodyName, true); + PlanetFactory.SetPathFor(null); + + } + + + //if (comboBoxControl == null) + // InitComboBox(); + + + } + } + finally { - var width = 2048; - if (FlightGlobals.currentMainBody.Radius < 50000) - width = 1024; - PFExport.CreateScaledSpacePlanet(curBodyName, "Laythe", null, width, 20000); + PlanetFactory.SetPathFor(null); } - //if (GUI.Button(new Rect(20, 140, 100, 20), "Effect " + curBodyName)) + + GUILayout.EndVertical(); + + GUI.contentColor = Color.white; + + //GUILayout.EndScrollView(); + + //if (comboBoxControl != null) //{ - // PFEffects.TestEffects(PFUtil.FindScaled(curBodyName)); + // var selectedItemIndex = comboBoxControl.SelectedItemIndex; + // selectedItemIndex = comboBoxControl.List( + // new Rect(20, 40, 160, 20), comboBoxList[selectedItemIndex].text, comboBoxList, listStyle); //} -#endif - } - + // Set the window to be draggable by the top title bar + GUI.DragWindow(new Rect(0, 0, 10000, 20)); + + } + } + + // Popup list created by Eric Haines // ComboBox Extended by Hyungseok Seo.(Jerry) sdragoon@nate.com // diff --git a/PlanetFactory/PFEffects.cs b/PlanetFactory/PFEffects.cs index f935519..c99c6e3 100644 --- a/PlanetFactory/PFEffects.cs +++ b/PlanetFactory/PFEffects.cs @@ -104,7 +104,7 @@ public static void AddRing(GameObject smallPlanet, double innerRadius, double ou public static GameObject AddEffect(GameObject smallPlanet, string effectName, Vector3 position, Quaternion rotation, Vector3 scale) { - MonoBehaviour.print(String.Format("Adding effect {0} to {1}", effectName, smallPlanet.name)); + PFUtil.Log(String.Format("Adding effect {0} to {1}", effectName, smallPlanet.name)); var effect = (GameObject)Object.Instantiate(Resources.Load("Effects/" + effectName)); effect.transform.parent = smallPlanet.transform; @@ -113,7 +113,7 @@ public static GameObject AddEffect(GameObject smallPlanet, string effectName, Ve effect.layer = smallPlanet.layer; effect.transform.localScale = scale; - MonoBehaviour.print("Finished effect"); + return (effect); } diff --git a/PlanetFactory/PFExport.cs b/PlanetFactory/PFExport.cs index cdb11b4..112e845 100644 --- a/PlanetFactory/PFExport.cs +++ b/PlanetFactory/PFExport.cs @@ -19,10 +19,10 @@ public static void CreateScaledSpacePlanet(string name, string templateName, Gam var exportBin = true; var removeAlpha = true; - var configRoot = ConfigNode.Load(PlanetFactory.DataPath+name+".cfg"); + var configRoot = ConfigNode.Load(PlanetFactory.CurrentPath + name + ".cfg"); if (configRoot != null && configRoot.HasNode("ScaledExport")) { - PlanetFactory.print("Loading ScaledExport"); + PFUtil.Log("Loading ScaledExport"); var node=configRoot.GetNode("ScaledExport"); if(node.HasValue("templateName")) templateName = node.GetValue("templateName"); @@ -42,11 +42,11 @@ public static void CreateScaledSpacePlanet(string name, string templateName, Gam if (node.HasValue("removeAlpha")) removeAlpha = bool.Parse(node.GetValue("removeAlpha")); - PlanetFactory.print("Loaded ScaledExport"); + PFUtil.Log("Loaded ScaledExport"); } - + //print("templateName:" + templateName); var template = GameObject.Find(templateName); @@ -82,8 +82,11 @@ public static void CreateScaledSpacePlanet(string name, string templateName, Gam } bodyPQS.isBuildingMaps = false; + var binFileName = PlanetFactory.CurrentPath + name + "_.bin"; //print("Writing scaledPlanet"); - var writer = KSP.IO.BinaryWriter.CreateForType(name + "_.bin"); + var stream = File.Open(binFileName,FileMode.Create); + var writer = new BinaryWriter(stream); + //var writer = KSP.IO.BinaryWriter.CreateForType(PlanetFactory.CurrentPath+ name + "_.bin"); foreach (var v in newVerts) { writer.Write(v.x); @@ -106,14 +109,14 @@ public static void CreateScaledSpacePlanet(string name, string templateName, Gam } } var mapBytes = textures[0].EncodeToPNG(); - File.WriteAllBytes(PlanetFactory.DataPath+ name + "_map_.png", mapBytes); + File.WriteAllBytes(PlanetFactory.CurrentPath + name + "_map_.png", mapBytes); - mapBytes = textures[1].EncodeToPNG(); - File.WriteAllBytes(PlanetFactory.DataPath + name + "_bump_.png", mapBytes); + //mapBytes = textures[1].EncodeToPNG(); + //File.WriteAllBytes(PlanetFactory.CurrentPath + name + "_bump_.png", mapBytes); var normalMap = PFUtil.BumpToNormalMap(textures[1], 9); mapBytes = normalMap.EncodeToPNG(); - File.WriteAllBytes(PlanetFactory.DataPath + name + "_normal_.png", mapBytes); + File.WriteAllBytes(PlanetFactory.CurrentPath + name + "_normal_.png", mapBytes); } #endif diff --git a/PlanetFactory/PFMods.cs b/PlanetFactory/PFMods.cs index 5bddceb..881d6c1 100644 --- a/PlanetFactory/PFMods.cs +++ b/PlanetFactory/PFMods.cs @@ -72,6 +72,16 @@ public LandClass() } } +public class PFVertexPlanetLandClass : PQSMod_VertexPlanet.LandClass +{ + public PFVertexPlanetLandClass(): + base("Default",0,1,Color.cyan,Color.yellow,0.2) + { + colorNoiseMap = new PQSMod_VertexPlanet.SimplexWrapper(1, 4, 0.6, 4); + colorNoiseMap.Setup(666); + } +} + public class PQSMod_PFOblate : PQSMod { public double offset; diff --git a/PlanetFactory/PFUtil.cs b/PlanetFactory/PFUtil.cs index 3e33d8a..ed79f7a 100644 --- a/PlanetFactory/PFUtil.cs +++ b/PlanetFactory/PFUtil.cs @@ -12,6 +12,24 @@ public static class PFUtil { private static GameObject _localSpace; + public static List logLines; + public static void Log(string line,LogType logType=LogType.Log) + { + PlanetFactory.print(line); + try + { + DebugConsole.Log(line, logType); + var writer=File.AppendText(PlanetFactory.DataPath + "Log.txt"); + writer.WriteLine(line); + writer.Close(); + //File.WriteAllLines(PlanetFactory.DataPath + "Log.txt", new string[] { line }); + } + catch + { + } + //logLines.Add(line); + } + public static GameObject LocalSpace { get @@ -59,6 +77,18 @@ public static CelestialBody FindCB(string name) return null; } + public static PlanetFactory.PFBody FindPFBody(string name) + { + try + { + return PlanetFactory.Instance.FindPFBody(name); + } + catch + { + } + + return null; + } private static Texture2D _defaultTexture=null; public static Texture2D defaultTexture { get{ if(_defaultTexture==null) @@ -72,7 +102,10 @@ public static Texture2D LoadTexture(string name,bool embedded=false) if (!embedded) { if (!File.Exists(name)) + { + PFUtil.Log(string.Format("Texture {0} not found. Using defaultTexture", name),LogType.Warning); return defaultTexture; + } textureData = File.ReadAllBytes(name); } else @@ -96,6 +129,68 @@ public static Texture2D LoadTexture(string name,bool embedded=false) return texture; } + public static void WarpShip(Vessel vessel, Orbit newOrbit) + { + if (newOrbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()).magnitude > newOrbit.referenceBody.sphereOfInfluence) + { + Log("Destination position was above the sphere of influence"); + return; + } + + vessel.Landed = false; + vessel.Splashed = false; + vessel.landedAt = string.Empty; + var parts = vessel.parts; + if (parts != null) + { + var clamps = parts.Where(p => p.Modules != null && p.Modules.OfType().Any()).ToList(); + foreach (var clamp in clamps) + clamp.Die(); + } + + try + { + OrbitPhysicsManager.HoldVesselUnpack(60); + } + catch (NullReferenceException) + { + } + + foreach (var v in (FlightGlobals.fetch == null ? (IEnumerable)new[] { vessel } : FlightGlobals.Vessels).Where(v => v.packed == false)) + v.GoOnRails(); + + HardsetOrbit(vessel.orbit, newOrbit); + + vessel.orbitDriver.pos = vessel.orbit.pos.xzy; + vessel.orbitDriver.vel = vessel.orbit.vel; + } + + public static void WarpPlanet(CelestialBody body, Orbit newOrbit) + { + var oldBody = body.referenceBody; + HardsetOrbit(body.orbit, newOrbit); + if (oldBody != newOrbit.referenceBody) + { + oldBody.orbitingBodies.Remove(body); + newOrbit.referenceBody.orbitingBodies.Add(body); + } + body.CBUpdate(); + } + + public static void HardsetOrbit(Orbit orbit, Orbit newOrbit) + { + orbit.inclination = newOrbit.inclination; + orbit.eccentricity = newOrbit.eccentricity; + orbit.semiMajorAxis = newOrbit.semiMajorAxis; + orbit.LAN = newOrbit.LAN; + orbit.argumentOfPeriapsis = newOrbit.argumentOfPeriapsis; + orbit.meanAnomalyAtEpoch = newOrbit.meanAnomalyAtEpoch; + orbit.epoch = newOrbit.epoch; + orbit.referenceBody = newOrbit.referenceBody; + orbit.Init(); + orbit.UpdateFromUT(Planetarium.GetUniversalTime()); + } + public static void RecalculateTangents(Mesh theMesh) { @@ -196,6 +291,335 @@ public static Texture2D BumpToNormalMap(Texture2D source, float strength) } +public static class Dump +{ + public static string GetGobPath(GameObject gob) + { + if (gob == null) + return ""; + var parent = gob.transform.parent; + var str = "" + gob.transform.name + "(" + gob.name + gob.GetInstanceID() + ")"; + while (parent != null) + { + str = parent.name + "(" + parent.gameObject.name + parent.gameObject.GetInstanceID() + ")" + "->" + str; + parent = parent.transform.parent; + } + return str; + } + + public static string ObjectToGui(object o, string name) + { + var t = o.GetType(); + //Console.WriteLine("Type:" + t); + if (t == typeof(string) || t.IsValueType) + return String.Format("({0}){1}={2}\n", t, name, o); + var enumerable = o as IEnumerable; + if (enumerable != null) + return String.Format("({0}){1}={2}", t, name, "\n"); + + var str = ""; + foreach (var f in t.GetFields()) + { + try + { + object val = f.GetValue(o); + string typ = ""; + if (val != null) + typ = val.GetType().ToString(); + str += String.Format("({0}){1}.({2}){3}={4}\n", t, name, typ, f.Name, f.GetValue(o)); + } + catch + { + str += String.Format("({0}){1}.({2}){3}={4}\n", t, name, "Unk", f.Name, "ERROR"); + } + } + foreach (var p in t.GetProperties()) + { + try + { + object val = p.GetValue(o, null); + string typ = ""; + if (val != null) + typ = val.GetType().ToString(); + + str += String.Format("({0}){1}.({2}){3}={4}\n", t, name, typ, p.Name, p.GetValue(o, null)); + } + catch + { + str += String.Format("({0}){1}.({2}){3}={4}\n", t, name, "Unk", p.Name, "ERROR"); + } + } + return str; + } + + public static string DumpMods() + { + var lines = new List(); + var all = Resources.FindObjectsOfTypeAll(typeof(PQSMod)) as PQSMod[]; + foreach (PQSMod obj in all) + { + var path = GetGobPath(obj.gameObject); + + if (path.Contains("Scatter")) + continue; + //PFUtil.Log(path); + lines.Add(path); + + var tstr = ""; + tstr += DumpObject(obj, path,2); // path + "->"); + + tstr = tstr.Replace("\r\r\n", "\r\n"); + lines.Add(tstr); + } + lines.Sort(); + var str = string.Join("\n", lines.Distinct().ToArray()); + return (str); + } + + public static string DumpAll() + { + var lines = new List(); + var all = Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[]; + foreach (GameObject obj in all) + { + var path = GetGobPath(obj); + //if (path.Contains("KerbinSystem") || path.Contains("Mun") || path.Contains("Tylo"))// || path.Contains("Joker")) + if (path.Contains("Kerbin") && path.Contains("localSpace")// || path.Contains("Minmus") || path.Contains("Vall") + //path.Contains("Kerbin") |||| path.Contains("Dres") || path.Contains("Jool") || path.Contains("Laythe") || path.Contains("Eeloo") + //|| path.Contains("CelestialBody") + ) + { + if (path.Contains("Scatter")) + continue; + //PFUtil.Log(path); + lines.Add(path); + + //var objStr = ObjectToGui(obj, ""); + //var objValues = objStr.Split('\n'); + //foreach (var v in objValues) + //{ + // lines.Add(path + "." + v); + //} + + var comps = obj.GetComponents(); + var tstr = ""; + tstr += String.Format("\nlocalPos:{0} localScale{1}\n", obj.transform.localPosition, obj.transform.localScale); + tstr += String.Format("\npos:{0} lossyScale{1}\n", obj.transform.position, obj.transform.lossyScale); + foreach (Component c in comps) + { + var typ = c.GetType().ToString(); + tstr += c.name + "(" + typ + "),\n"; + if (true //typ.Contains("Atmosphere") + //|| typ.Contains("CelestialBody") + ) + { + //tstr += Dump.Graph(c + tstr += DumpComponent(c, path + "COMP:"); + //var cobjStr = ObjectToGui(c, ""); + //var cobjValues = objStr.Split('\n'); + //foreach (var v in cobjValues) + //{ + // tstr += path + "COMP:" + c.name + "." + v + "\n"; + //} + } + } + tstr = tstr.Replace("\r\r\n", "\r\n"); + lines.Add(path + ".COMPONENTS={" + tstr + "}"); + + tstr = ""; + foreach (Transform c in obj.transform) + { + tstr += String.Format("\nlocalPos:{0} localScale{1}\n", c.localPosition, c.localScale); + tstr += String.Format("\npos:{0} lossyScale{1}\n", c.position, c.lossyScale); + tstr += c.name + "(" + c.GetType() + "),"; + } + lines.Add(path + ".XFORMS={" + tstr + "}"); + + //lines.Add(Dump.Graph(obj, path + ".XFORMS={ ")); + } + } + lines.Sort(); + var str = string.Join("\n", lines.Distinct().ToArray()); + return (str); + } + + public static string GetGob(string name = "Minmus") + { + var mm = GameObject.Find(name); + return Graph(mm); + } + + public static string Graph(Transform transform, string indent) + { + var outStr = ""; + outStr += (indent + "XF:" + transform.name + "<" + transform.GetType().Name + ">"); + outStr += "\n"; + + + foreach (Component component in transform.GetComponents()) + { + outStr += DumpComponent(component, indent + " "); + outStr += "\n"; + + } + + foreach (Transform child in transform.transform) + { + outStr += Graph(child.gameObject, indent + " "); + outStr += "\n"; + + } + return outStr; + } + + public static string Graph(GameObject gameObject, string indent = "") + { + var outStr = ""; + outStr += (indent + gameObject.name + "<" + gameObject.GetType().Name + ">"); + outStr += "\n"; + + + foreach (Component component in gameObject.GetComponentsInChildren(true)) + { + outStr += DumpComponent(component, indent + " "); + outStr += "\n"; + + } + + foreach (Transform child in gameObject.transform) + { + outStr += Graph(child.gameObject, indent + " "); + outStr += "\n"; + + } + return outStr; + } + + public static string DumpComponent(Component component, string indent) + { + var myName = component.name + "->" + (component.GetType().Name); + var outStr = (indent + myName + "\n"); + outStr += DumpObject(component, indent + myName, 1); + return outStr; + } + + public static string DumpObject(object o, string name = "", int depth = 3) + { + //var v = new MyStuff.Debug.Foo(); + try + { + var leafprefix = "xxxx"; // (string.IsNullOrWhiteSpace(name) ? name : name + " = "); + if (!string.IsNullOrEmpty(name)) + leafprefix = name + "="; + + if (null == o) return leafprefix + "null"; + + var t = o.GetType(); + if (depth-- < 1 || t == typeof(string) || t.IsValueType) + return leafprefix + "(" + t.Name + ")" + o; + + var sb = new StringBuilder(); + + var enumerable = o as IEnumerable; + if (enumerable != null) + { + name = (name ?? "").TrimEnd('[', ']') + '['; + var elements = enumerable.Cast().Select(e => DumpObject(e, "", depth)).ToList(); + var arrayInOneLine = elements.Count + "] = {" + string.Join(",", elements.ToArray()) + '}'; + if (!arrayInOneLine.Contains(Environment.NewLine)) // Single line? + return name + arrayInOneLine; + var i = 0; + foreach (var element in elements) + { + var lineheader = name + i++ + ']'; + sb.Append(lineheader) + .AppendLine(element.Replace(Environment.NewLine, Environment.NewLine + lineheader)); + } + return sb.ToString(); + } + foreach (var f in t.GetFields()) + try + { + var pname = f.Name.ToLower(); + //if (!pname.Contains("enable") && !pname.Contains("active")) + // continue; + + if (/*f.Name.ToLower() == "orbit" || f.Name.ToLower() == "material" || + f.GetType() == typeof(Material) || f.Name.ToLower() == "orbitingbodies" ||*/ f.Name.ToLower().Contains("landclass") + || f.GetType().Name.ToLower().Contains("simplex")) + sb.AppendLine(DumpObject(f.GetValue(o), name + '.' + f.Name, depth + 2)); + else + sb.AppendLine(DumpObject(f.GetValue(o), name + '.' + f.Name, depth)); + } + catch + { + } + foreach (var p in t.GetProperties()) + try + { + var pname = p.Name.ToLower(); + //if (pname == "targetrotation") + // continue; + //if (!pname.Contains("enable") && !pname.Contains("active")) + // continue; + if (/*p.Name.ToLower() == "orbit" || p.Name.ToLower() == "material" || + p.GetType() == typeof(Material) || p.Name.ToLower() == "orbitingbodies" ||*/ p.Name.ToLower().Contains("landclass") + || p.GetType().Name.ToLower().Contains("simplex")) + sb.AppendLine(DumpObject(p.GetValue(o, null), name + '.' + p.Name, depth + 2)); + else + sb.AppendLine(DumpObject(p.GetValue(o, null), name + '.' + p.Name, depth)); + } + catch + { + } + + if (sb.Length == 0) return leafprefix + o; + return sb.ToString().TrimEnd(); + } + catch + { + return name + "???"; + } + } + + public static string MeshToString(MeshFilter mf) + { + Mesh m = mf.mesh; + Material[] mats = mf.renderer.sharedMaterials; + + var sb = new StringBuilder(); + + sb.Append("g ").Append(mf.name).Append("\n"); + foreach (Vector3 v in m.vertices) + { + sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, v.z)); + } + sb.Append("\n"); + foreach (Vector3 v in m.normals) + { + sb.Append(string.Format("vn {0} {1} {2}\n", v.x, v.y, v.z)); + } + sb.Append("\n"); + foreach (Vector3 v in m.uv) + { + sb.Append(string.Format("vt {0} {1}\n", v.x, v.y)); + } + for (int material = 0; material < m.subMeshCount; material++) + { + sb.Append("\n"); + sb.Append("usemtl ").Append(mats[material].name).Append("\n"); + sb.Append("usemap ").Append(mats[material].name).Append("\n"); + + int[] triangles = m.GetTriangles(material); + for (int i = 0; i < triangles.Length; i += 3) + { + sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", + triangles[i] + 1, triangles[i + 1] + 1, triangles[i + 2] + 1)); + } + } + return sb.ToString(); + } +} diff --git a/PlanetFactory/PlanetFactory.cs b/PlanetFactory/PlanetFactory.cs index 59d1dd0..98fbf7e 100644 --- a/PlanetFactory/PlanetFactory.cs +++ b/PlanetFactory/PlanetFactory.cs @@ -13,52 +13,111 @@ public partial class PlanetFactory : MonoBehaviour private static int nextFlightGlobalsIndex = 16; private bool guiHidden = true; public static string DataPath = "GameData/PlanetFactory/PluginData/PlanetFactory/"; + public static string OverridePath = string.Empty; + private static PlanetFactory _instance=null; + public static PlanetFactory Instance{ + get{ + return _instance; + } + private set{ + _instance=value; + } + } + public string ConfigFilename = DataPath + "PlanetFactory.cfg"; - private ConfigNode configRoot; + public static void SetPathFor(PFBody body) + { + if (body != null && body.parentSystem != null) + { + //PFUtil.Log("set OverridePath:" + body.parentSystem.path); + PlanetFactory.OverridePath = body.parentSystem.path; + //print("currentPath:" + CurrentPath); + } + else + { + //PFUtil.Log("clear OverridePath"); + PlanetFactory.OverridePath = string.Empty; + } + } + public static string CurrentPath{ + get + { + if (OverridePath != string.Empty) + return OverridePath; + return DataPath; + } + } + public PlanetFactory() + { + _instance = this; + } + private ConfigNode PFConfigRoot; public bool autoLoad = true; public bool isFactoryEnabled = true; + //public bool isSystemEnabled = true; + public bool autoLoadSave = true; public string autoLoadSaveName = "default"; public double ultraWarpAlt = 20000000000.0; public bool ultraWarpEnabled = true; public static bool shiftyMode = false; + public string disabledSystems = ""; private void LoadConfig() { - print("LoadConfig:" + ConfigFilename); - configRoot = ConfigNode.Load(ConfigFilename); - if (configRoot == null) + PFUtil.Log("LoadConfig:" + ConfigFilename); + PFConfigRoot = ConfigNode.Load(ConfigFilename); + if (PFConfigRoot == null) { - configRoot = new ConfigNode(); + PFConfigRoot = new ConfigNode(); } - var pfConfig = configRoot.nodes.GetNode("PlanetFactory"); + var pfConfig = PFConfigRoot.nodes.GetNode("PlanetFactory"); if (pfConfig == null) { - configRoot.AddNode("PlanetFactory"); + PFConfigRoot.AddNode("PlanetFactory"); SaveConfig(); } else { - print("loading PlanetFactory config:"); + PFUtil.Log("loading PlanetFactory config:"); LoadConfiguration(this, pfConfig); } } private void SaveConfig() { - print("SaveConfig"); - var pfConfig = configRoot.nodes.GetNode("PlanetFactory"); + PFUtil.Log("SaveConfig"); + var pfConfig = PFConfigRoot.nodes.GetNode("PlanetFactory"); + pfConfig.SetValue("autoLoad", autoLoad.ToString()); pfConfig.SetValue("isFactoryEnabled", isFactoryEnabled.ToString()); + //pfConfig.SetValue("isSystemEnabled", isSystemEnabled.ToString()); + pfConfig.SetValue("autoLoadSave", autoLoadSave.ToString()); pfConfig.SetValue("autoLoadSaveName", autoLoadSaveName); - configRoot.Save(ConfigFilename); + + //var sNode=new ConfigNode("Systems"); + + var disabledSys = new List(); + foreach (var s in Systems) + { + if (!s.enabled) + disabledSys.Add(s.name); + } +// print(string.Join(",", disabledSys.ToArray())); + if (!pfConfig.values.Contains("disabledSystems")) + pfConfig.AddValue("disabledSystems", string.Join(",", disabledSys.ToArray())); + else + pfConfig.SetValue("disabledSystems", string.Join(",", disabledSys.ToArray())); + //PFConfigRoot.AddNode(sNode); + + PFConfigRoot.Save(ConfigFilename); } private List saveNames; private void FindSaves() { - print("FindSaves"); + PFUtil.Log("FindSaves"); var dirs=Directory.GetDirectories("saves\\"); saveNames = dirs.Where(x => File.Exists(x + "\\persistent.sfs")).Select(x => x.Split(new[] { '\\' })[1]).ToList(); } @@ -74,17 +133,25 @@ private void Start() print("PlanetFactory Starting"); string sFilePath = KSP.IO.IOUtils.GetFilePathFor(this.GetType(), ""); - Debug.Log("PFDataPath: " + sFilePath); - sFilePath = sFilePath.Replace("\\", "/"); DataPath = sFilePath+"/"; - print("Setting PlanetFactory Data Path to:" + DataPath); + print("Setting datapath:" + DataPath); + + File.Delete(PlanetFactory.DataPath + "Log.txt"); + + PFUtil.Log("//////////////////////////////////////////////////////////////////////////////////////////"); + PFUtil.Log("PlanetFactory Starting at"+DateTime.Now); + PFUtil.Log("//////////////////////////////////////////////////////////////////////////////////////////"); + PFUtil.Log("PlanetFactory Data Path:" + DataPath); + ConfigFilename = DataPath + "PlanetFactory.cfg"; LoadConfig(); - FindSaves(); + FindSystems(); + + //FindSaves(); InitComboBox(); } @@ -104,30 +171,30 @@ private void Update() if (!autoLoad) return; - var menu = GameObject.Find("MainMenu"); - if (menu != null && bDoOnce) - { - bDoOnce = false; - - if (autoLoadSave) - { - HighLogic.CurrentGame = GamePersistence.LoadGame("persistent", autoLoadSaveName, true, false); - if (HighLogic.CurrentGame != null) - { - HighLogic.SaveFolder = autoLoadSaveName; - //load to SpaceCenter - HighLogic.CurrentGame.Start(); - //Go to flight - //FlightDriver.StartAndFocusVessel("persistent", 0);// FlightGlobals.Vessels.Count()-1); - } - } - else - { - //pop up load game dialog. - var mc = menu.GetComponent(); - mc.continueBtn.onPressed.Invoke(); - } - } + //var menu = GameObject.Find("MainMenu"); + //if (menu != null && bDoOnce) + //{ + // bDoOnce = false; + + // if (autoLoadSave) + // { + // HighLogic.CurrentGame = GamePersistence.LoadGame("persistent", autoLoadSaveName, true, false); + // if (HighLogic.CurrentGame != null) + // { + // HighLogic.SaveFolder = autoLoadSaveName; + // //load to SpaceCenter + // HighLogic.CurrentGame.Start(); + // //Go to flight + // //FlightDriver.StartAndFocusVessel("persistent", 0);// FlightGlobals.Vessels.Count()-1); + // } + // } + // else + // { + // //pop up load game dialog. + // var mc = menu.GetComponent(); + // mc.continueBtn.onPressed.Invoke(); + // } + //} } private bool isFactoryLoaded = false; @@ -143,7 +210,7 @@ private void SetLocalCollision(string planetName,bool enabled=true) { if (c.enabled!=enabled) { - print("Updating collision " + c.gameObject.name +"="+enabled ); + //PFUtil.Log("Updating collision " + c.gameObject.name + "=" + enabled); c.enabled = enabled; } } @@ -155,7 +222,7 @@ private void UpdateCollision() { if (FlightGlobals.currentMainBody!=null && FlightGlobals.currentMainBody.bodyName != currentBodyName) { - print("Body change "+currentBodyName +" to " + FlightGlobals.currentMainBody.bodyName); + PFUtil.Log("Body change " + currentBodyName + " to " + FlightGlobals.currentMainBody.bodyName); if (currentBodyName != null) SetLocalCollision(currentBodyName, false); @@ -178,14 +245,14 @@ public void UpdateTimewarps() { if (TimeWarp.fetch.warpRates.Length < ultraWarpRates.Length) { - print("UltraWarp on " + FlightGlobals.ship_altitude); + PFUtil.Log("UltraWarp on " + FlightGlobals.ship_altitude); TimeWarp.fetch.warpRates = ultraWarpRates; } }else { if (TimeWarp.fetch.warpRates.Length != stockWarpRates.Length) { - print("UltraWarp off " + FlightGlobals.ship_altitude); + PFUtil.Log("UltraWarp off " + FlightGlobals.ship_altitude); if(TimeWarp.CurrentRateIndex>stockWarpRates.Length-1) TimeWarp.SetRate(stockWarpRates.Length-1, true); TimeWarp.fetch.warpRates = stockWarpRates; @@ -196,21 +263,35 @@ public void UpdateTimewarps() public void OnLevelWasLoaded(int level) { - print("OnLevelWasLoaded:" + level); + //PFUtil.Log("OnLevelWasLoaded:" + level); if (PSystemManager.Instance != null && ScaledSpace.Instance == null) { isTooLateToLoad = true; } - if (!isFactoryEnabled) - return; +// if (!isFactoryEnabled)// && !isSystemEnabled) +// return; + PlanetariumCamera.fetch.maxDistance = 5000000000000; if (PSystemManager.Instance != null && ScaledSpace.Instance == null) { isFactoryLoaded = true; + if (!isFactoryEnabled) + { + newBodies = new List(); + } + + LoadSystems(); + + //PFUtil.Log("Body indexes"); + //foreach (var body in newBodies) + //{ + // PFUtil.Log(body.name + ":" + body.flightGlobalsIndex); + //} + findPrefabBodies(PSystemManager.Instance.systemPrefab.rootBody); foreach (var b in newBodies) @@ -221,9 +302,10 @@ public void OnLevelWasLoaded(int level) } catch (Exception e) { - print("Error creating planet "+b.name); - print(e.Message); - print(e.InnerException.Message); + PFUtil.Log("Error creating planet " + b.name,LogType.Error); + PFUtil.Log("Exception:" + e.Message, LogType.Error); + PFUtil.Log("InnerException:" + e.InnerException.Message, LogType.Error); + PFUtil.Log("Stack:", LogType.Error); } } PSystemManager.Instance.OnPSystemReady.Add(OnPSystemReady); @@ -233,8 +315,8 @@ public void OnLevelWasLoaded(int level) public void OnPSystemReady() { //print("OnPSystemReady"); - if (!isFactoryEnabled) - return; +// if (!isFactoryEnabled)// && !isSystemEnabled) +// return; foreach (var b in newBodies) { try @@ -243,13 +325,141 @@ public void OnPSystemReady() } catch (Exception e) { - print("Error updating planet " + b.name); - print(e.Message); - print(e.InnerException.Message); + PFUtil.Log("Error updating planet " + b.name, LogType.Error); + PFUtil.Log("Exception:" + e.Message, LogType.Error); + if(e.InnerException!=null) + PFUtil.Log("InnerException:" + e.InnerException.Message, LogType.Error); + PFUtil.Log("Stack:"+e.StackTrace, LogType.Error); } } + //PFUtil.Log(Dump.DumpMods()); } + public class PFSystem + { + public string name; + public List planetNames = new List(); + public bool enabled = true; + public string path = ""; + + public List LoadPlanets() + { + var bodies = new List(); + + if (!enabled) + return bodies; + + PFUtil.Log("Loading System:" + name); + foreach (var planetName in planetNames) + { + var bodyConfigFilename = path + planetName + ".cfg"; + PFUtil.Log("Loading Body:" + planetName); + var configRoot = ConfigNode.Load(bodyConfigFilename); + if (configRoot.nodes.Contains("PFBody")) + { + var n = configRoot.GetNode("PFBody"); + var body = new PFBody() + { + parentSystem=this + }; + LoadConfiguration(body, n); + bodies.Add(body); + } + } + //PFUtil.Log("LoadSystem finished"); + return(bodies); + } + } + public List Systems = new List(); + public void FindSystems() + { + var sysFiles=Directory.GetFiles(DataPath, "*.system", SearchOption.AllDirectories); + foreach (var sysFile in sysFiles) + { + var sysName=Path.GetFileNameWithoutExtension(sysFile); + PFUtil.Log("LoadSystem:" + sysName); + //PFUtil.Log(sysFile); + var configRoot = ConfigNode.Load(sysFile); + var systemNode = configRoot.GetNode("System"); + if (systemNode == null) + continue; + + PFSystem curSystem = null; + int i = 0; + while (true) + { + var planetName = systemNode.GetValue("planetName", i); + if (planetName == null) + break; + + if (curSystem == null) + { + var sysPath =Path.GetDirectoryName(sysFile)+"/"; + //PFUtil.Log("New system:" + sysName + "->" + sysPath); + curSystem = new PFSystem() { + name = sysName, + path = sysPath + }; + } + curSystem.planetNames.Add(planetName); + PFUtil.Log(string.Format("Adding body {0} to system {1}", planetName, curSystem.name)); + i++; + } + + if (curSystem != null) + { + var disabledList = disabledSystems.Split(new char[] { ',' }); + if (disabledList.Any(x => x == curSystem.name)) + { + PFUtil.Log("Disabling system " + curSystem.name); + curSystem.enabled = false; + } + Systems.Add(curSystem); + } + //var lines=File.ReadAllLines(name); + //PFSystem curSystem = null; + //foreach (var line in lines) + //{ + // var l=line.Split(new string[]{"//"},StringSplitOptions.None); + // var planetName = l[0].Trim(); + // if (planetName != string.Empty && File.Exists(DataPath+planetName+".cfg")) + // { + // if (curSystem == null) + // curSystem = new PFSystem(){name=name}; + // curSystem.planetNames.Add(planetName); + // print(string.Format("Adding body {0} to system {1}",planetName,curSystem.name)); + // } + //} + } + } + + public void LoadSystems() + { + foreach (var sys in Systems) + { + var bodies = sys.LoadPlanets(); + newBodies.AddRange(bodies); + } + } + //public void xLoadSystem() + //{ + // var systemConfigFilename=DataPath + "System.cfg"; + // print("LoadSystem:" + systemConfigFilename); + // configRoot = ConfigNode.Load(systemConfigFilename); + // int i = 0; + // while (true) + // { + // var n = configRoot.GetNode("PFBody", i); + // if (n == null) + // break; + + // var body = new PFBody(); + // LoadConfiguration(body, n); + // newBodies.Add(body); + // i++; + // } + // print("LoadSystem finished"); + //} public class PFOrbit { public double inclination; @@ -266,7 +476,7 @@ public PFOrbit() } public bool Load(string name) { - var root = ConfigNode.Load(DataPath + name + ".cfg"); + var root = ConfigNode.Load(CurrentPath + name + ".cfg"); if (root == null) return false; var orbitConfig = root.nodes.GetNode("Orbit"); @@ -285,16 +495,19 @@ public class PFBody public string templateName; public PFOrbit orbit; public int flightGlobalsIndex; + public bool hideScaled = false; + public PFSystem parentSystem=null; + public bool clearPQS = false; [XmlIgnore] - public localUpdateDelegate localUpdate; + public localUpdateDelegate localUpdate=null; public PFBody() { } public PFBody(string name, string templateName, int flightGlobalsIndex, PFOrbit orbit, - localUpdateDelegate localUpdate) + localUpdateDelegate localUpdate=null) { this.name = name; this.templateName = templateName; @@ -305,75 +518,122 @@ public PFBody(string name, string templateName, int flightGlobalsIndex, PFOrbit public void CreatePrefab() { - var templateBody = prefabBodies[templateName]; + try + { + if (parentSystem != null) + { + PlanetFactory.OverridePath = parentSystem.path; + } + var templateBody = prefabBodies[templateName]; + + var body = (PSystemBody)Instantiate(templateBody); - var body = (PSystemBody) Instantiate(templateBody); - body.celestialBody.bodyName = name; - body.flightGlobalsIndex = flightGlobalsIndex; + body.celestialBody.bodyName = name; + body.flightGlobalsIndex = flightGlobalsIndex; + + if (orbit == null) + orbit = new PFOrbit(); //load from config (if any) - orbit.Load(name); + orbit.Load(name); - var parentBody = prefabBodies[orbit.referenceBody]; - if (body.celestialBody.orbitDriver != null) - { - body.celestialBody.orbitDriver.orbit = new Orbit(orbit.inclination, orbit.eccentricity, - orbit.semiMajorAxis, orbit.LAN, - orbit.argumentOfPeriapsis, orbit.meanAnomalyAtEpoch, orbit.epoch, parentBody.celestialBody); + var parentBody = prefabBodies[orbit.referenceBody]; + if (body.celestialBody.orbitDriver != null) + { + body.celestialBody.orbitDriver.orbit = new Orbit(orbit.inclination, orbit.eccentricity, + orbit.semiMajorAxis, orbit.LAN, + orbit.argumentOfPeriapsis, orbit.meanAnomalyAtEpoch, orbit.epoch, parentBody.celestialBody); - body.celestialBody.orbitDriver.UpdateOrbit(); - } + body.celestialBody.orbitDriver.UpdateOrbit(); + } - LoadCB(body.celestialBody); + LoadCB(body.celestialBody); - body.children.Clear(); - parentBody.children.Add(body); - body.enabled = false; + body.children.Clear(); + parentBody.children.Add(body); + body.enabled = false; - prefabBodies[name] = body; + prefabBodies[name] = body; + } + finally + { + PlanetFactory.OverridePath = string.Empty; + } } public void UpdateBody() { - print("UpdateLocal:" + name); - localUpdate(this); + PFUtil.Log("UpdateLocal:" + name); + try + { + if (parentSystem != null) + { + PlanetFactory.OverridePath = parentSystem.path; + } - print("UpdateScaled:" + name); - var smallPlanet = PFUtil.FindScaled(name); + if (clearPQS) + ClearPQSMods(name); - if (templateName == "Sun") - { - var sunBody = PFUtil.FindCB("Sun"); - var cb = PFUtil.FindCB(name); + if (localUpdate != null) + localUpdate(this); + else + LoadPQS(name); + + PFUtil.Log("UpdateScaled:" + name); + var smallPlanet = PFUtil.FindScaled(name); - var orbitDriver = smallPlanet.AddComponent(); - orbitDriver.updateMode = OrbitDriver.UpdateMode.UPDATE; - orbitDriver.name = cb.name; - orbitDriver.orbit = new Orbit(orbit.inclination, orbit.eccentricity, orbit.semiMajorAxis, orbit.LAN, - orbit.argumentOfPeriapsis, orbit.meanAnomalyAtEpoch, orbit.epoch, sunBody); + if (templateName == "Sun") + { + var sunBody = PFUtil.FindCB(orbit.referenceBody); + var cb = PFUtil.FindCB(name); - cb.orbitDriver = orbitDriver; + var orbitDriver = smallPlanet.AddComponent(); + orbitDriver.updateMode = OrbitDriver.UpdateMode.UPDATE; + orbitDriver.name = cb.name; + orbitDriver.orbit = new Orbit(orbit.inclination, orbit.eccentricity, orbit.semiMajorAxis, orbit.LAN, + orbit.argumentOfPeriapsis, orbit.meanAnomalyAtEpoch, orbit.epoch, sunBody); - orbitDriver.referenceBody = sunBody; - orbitDriver.celestialBody = cb; + cb.orbitDriver = orbitDriver; - cb.sphereOfInfluence = cb.orbit.semiMajorAxis * Math.Pow(cb.Mass / cb.orbit.referenceBody.Mass, 0.4); - cb.hillSphere = cb.orbit.semiMajorAxis * (1 - cb.orbit.eccentricity) * Math.Pow(cb.Mass / cb.orbit.referenceBody.Mass, 0.333333333333333); - cb.orbitDriver.QueuedUpdate = true; - cb.CBUpdate(); + orbitDriver.referenceBody = sunBody; + orbitDriver.celestialBody = cb; - orbitDriver.UpdateOrbit(); - } + cb.sphereOfInfluence = cb.orbit.semiMajorAxis * Math.Pow(cb.Mass / cb.orbit.referenceBody.Mass, 0.4); + cb.hillSphere = cb.orbit.semiMajorAxis * (1 - cb.orbit.eccentricity) * Math.Pow(cb.Mass / cb.orbit.referenceBody.Mass, 0.333333333333333); + cb.orbitDriver.QueuedUpdate = true; + cb.CBUpdate(); + + orbitDriver.UpdateOrbit(); + } + + LoadScaledPlanet(smallPlanet, name); - LoadScaledPlanet(smallPlanet, name); + if (hideScaled)//doesnt work. + { + var bigPlanet = PFUtil.FindLocal(name); + var mr = bigPlanet.GetComponent(); + if (mr != null) + mr.mesh = mr.sharedMesh = null; + + mr = smallPlanet.GetComponent(); + if (mr != null) + mr.mesh = mr.sharedMesh = null; + //mr.active = false; + } + } + finally + { + PlanetFactory.OverridePath = string.Empty; + } } public static void LoadScaledPlanet(GameObject smallPlanet, string name,bool bLoadTemp=false) { + PFUtil.Log("LoadScaledPlanet:" + name); - var root = ConfigNode.Load(DataPath + name + ".cfg"); + var root = ConfigNode.Load(CurrentPath + name + ".cfg"); if (root != null) { var sConfig = root.nodes.GetNode("ScaledTransform"); @@ -381,36 +641,50 @@ public static void LoadScaledPlanet(GameObject smallPlanet, string name,bool bLo if (sConfig != null) { var scaledBody = PFUtil.FindScaled(name); - - var ratio = float.Parse(sConfig.GetValue("ratio")); - var newScale = (float)PFUtil.FindCB(name).Radius * ratio; - scaledBody.transform.localScale = new Vector3(newScale, newScale, newScale); + if (sConfig.HasValue("ratio")) + { + var ratio = float.Parse(sConfig.GetValue("ratio")); + var newScale = (float)PFUtil.FindCB(name).Radius * ratio; + scaledBody.transform.localScale = new Vector3(newScale, newScale, newScale); + } } } - var binName = name + ".bin"; if (!bLoadTemp) { - var colorTexture = PFUtil.LoadTexture(DataPath + name + "_map.png"); - var bumpTexture = PFUtil.LoadTexture(DataPath + name + "_normal.png"); + var colorTexture = PFUtil.LoadTexture(CurrentPath + name + "_map.png"); + var bumpTexture = PFUtil.LoadTexture(CurrentPath + name + "_normal.png"); + + if (bumpTexture == PFUtil.defaultTexture) + bumpTexture = null; //Bug fix. Dont use Normal map if not found. LoadScaledPlanetTextures(name, colorTexture, bumpTexture); } else { - var colorTexture = PFUtil.LoadTexture(DataPath + name + "_map_.png"); - var bumpTexture = PFUtil.LoadTexture(DataPath + name + "_normal_.png"); + var colorTexture = PFUtil.LoadTexture(CurrentPath + name + "_map_.png"); + var bumpTexture = PFUtil.LoadTexture(CurrentPath + name + "_normal_.png"); + + if (bumpTexture == PFUtil.defaultTexture) + bumpTexture = null; //Bug fix. Dont use Normal map if not found. + binName = name + "_.bin"; LoadScaledPlanetTextures(name, colorTexture, bumpTexture); } - if (KSP.IO.File.Exists(binName)) + var binFileName = CurrentPath + binName; + if (File.Exists(binFileName)) + //if (KSP.IO.File.Exists(binName)) { - //print("Loading mesh"); + PFUtil.Log("Loading mesh:" + binName); var smallPlanetMeshFilter = (MeshFilter) smallPlanet.GetComponentInChildren((typeof (MeshFilter))); var newVerts = new Vector3[smallPlanetMeshFilter.mesh.vertices.Count()]; - var reader = KSP.IO.BinaryReader.CreateForType(binName); + //var reader = KSP.IO.BinaryReader.CreateForType(binName); + + var stream = File.OpenRead(binFileName); + var reader = new BinaryReader(stream); + for (var i = 0; i < newVerts.Count(); i++) { newVerts[i].x = reader.ReadSingle(); @@ -504,35 +778,62 @@ public static void LoadConfiguration(System.Object obj, ConfigNode node) field.SetValue(obj, ParseOrbit(node.GetNode(key))); break; case "pqsmod_pfheightcolor+landclass[]": - int i = 0; - var lcs = new List(); - //print("parse landclass"); - var pn = node.GetNode(key); - while (true) { - var n = pn.GetNode("LandClass", i); - if (n != null) + int i = 0; + var lcs = new List(); + //print("parse landclass"); + var pn = node.GetNode(key); + while (true) { - var nlc = new PQSMod_PFHeightColor.LandClass(); - LoadConfiguration(nlc,n); - lcs.Add(nlc); + var n = pn.GetNode("LandClass", i); + if (n != null) + { + var nlc = new PQSMod_PFHeightColor.LandClass(); + LoadConfiguration(nlc, n); + lcs.Add(nlc); + } + else + { + break; + } + i++; } - else + field.SetValue(obj, lcs.ToArray()); + } + break; + case "pqsmod_vertexplanet+landclass[]": + { + int i = 0; + var lcs = new List(); + PFUtil.Log("pqsmod_vertexplanet+landclass[]"); + var pn = node.GetNode(key); + while (true) { - break; + var n = pn.GetNode("LandClass", i); + if (n != null) + { + var nlc = new PFVertexPlanetLandClass(); + LoadConfiguration(nlc, n); + lcs.Add(nlc); + } + else + { + break; + } + i++; } - i++; + field.SetValue(obj, lcs.ToArray()); + PFUtil.Log("END pqsmod_vertexplanet+landclass[]"); + } - field.SetValue(obj, lcs.ToArray()); - break; - + break; case "mapso": //print("Loading map:"+config[key]); if (config[key].ToLower() == "null") field.SetValue(obj, null); else { - var colorTexture = PFUtil.LoadTexture(DataPath + config[key]); + var colorTexture = PFUtil.LoadTexture(CurrentPath + config[key]); var mapso = (MapSO) ScriptableObject.CreateInstance(typeof (MapSO)); mapso.CreateMap(MapSO.MapDepth.RGBA, colorTexture); field.SetValue(obj, mapso); @@ -564,15 +865,16 @@ public static Dictionary ConfigToDict(ConfigNode node) } return (dict); } - public static void LoadCB(CelestialBody body) + public static void LoadCB(CelestialBody body,ConfigNode root=null) { - var root = ConfigNode.Load(DataPath + body.bodyName + ".cfg"); + if(root==null) + root = ConfigNode.Load(CurrentPath + body.bodyName + ".cfg"); if (root != null) { var cbConfig = root.nodes.GetNode("CelestialBody"); if (cbConfig != null) { - print("loading CB config:" + body.bodyName); + PFUtil.Log("loading CB config:" + body.bodyName); LoadConfiguration(body, cbConfig); body.CBUpdate(); } @@ -594,14 +896,32 @@ public static void LoadOrbit(CelestialBody body) body.orbitDriver.UpdateOrbit(); } } + //PQSMod_MaterialSetDirection.target + private static string[] EssentialMods = { "PQSMod_MaterialSetDirection", "PQSMod_CelestialBodyTransform", "PQSMod_AltitudeAlpha", "PQSMod_UVPlanetRelativePosition", "PQSMod_QuadMeshColliders" }; + //PQSMod_AerialPerspectiveMaterial? + public static void ClearPQSMods(string bodyName) + { + PFUtil.Log("ClearPQSMods:" + bodyName); + var localGameObject = PFUtil.FindLocal(bodyName); + var mods = localGameObject.GetComponentsInChildren(true); + foreach (var mod in mods) + { + var modType = mod.GetType().ToString(); + if (!EssentialMods.Any(x => modType.Contains(x))) + { + mod.modEnabled = false; + mod.gameObject.SetActive(false); + Destroy(mod.gameObject); + PFUtil.Log("Removed:" + modType); + } + } + } public static void LoadPQS(string bodyName) { var localGameObject = PFUtil.FindLocal(bodyName);// localSpace.transform.FindChild(body.name).gameObject; - print("load config"); - print(typeof(PQSMod).AssemblyQualifiedName); - var root = ConfigNode.Load(DataPath +bodyName+ ".cfg"); + var root = ConfigNode.Load(CurrentPath + bodyName + ".cfg"); var pqs = localGameObject.GetComponentInChildren(); @@ -614,7 +934,7 @@ public static void LoadPQS(string bodyName) mod.modEnabled = false; mod.gameObject.SetActive(false); Destroy(mod.gameObject); - print("Removed PQSCity:"); + //PFUtil.Log("Removed PQSCity:"); } } @@ -632,7 +952,7 @@ public static void LoadPQS(string bodyName) componentType = Type.GetType(componentTypeStr + ", PlanetFactory, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); if (componentType == null) { - print("Cant find PQSMod type:" + componentTypeStr); + PFUtil.Log("Cant find PQSMod type:" + componentTypeStr,LogType.Warning); continue; } var component = localGameObject.GetComponentInChildren(componentType); @@ -658,7 +978,6 @@ public static void LoadPQS(string bodyName) if (component != null) { - print("Loading Config PQS:");// + Dump.GetGobPath(component.gameObject)); LoadConfiguration(component, node); try @@ -677,6 +996,10 @@ public static void LoadPQS(string bodyName) pqs.RebuildSphere(); } + public PFBody FindPFBody(string name) + { + return newBodies.FirstOrDefault(x=>x.name==name); + } public List newBodies = new List { @@ -694,7 +1017,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); }), @@ -712,7 +1034,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); //PFEffects.AddEffect(PFUtil.FindScaled(body.name), "fx_exhaustFlame_blue", Vector3.zero, Quaternion.Euler(-90, 0, 0), new Vector3(5000000000, 5000000000, 5000000000)); @@ -731,12 +1052,12 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); if (!shiftyMode) return; + var localGameObject = PFUtil.FindLocal(body.name); var vp = localGameObject.GetComponentInChildren(); var md = vp.gameObject.AddComponent(); @@ -778,7 +1099,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); var localGameObject = PFUtil.FindLocal(body.name); @@ -822,7 +1142,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); }), @@ -840,7 +1159,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); }), new PFBody("Pock", "Minmus", 156, @@ -857,7 +1175,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); var localGameObject = PFUtil.FindLocal(body.name); @@ -910,7 +1227,6 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); var localGameObject = PFUtil.FindLocal(body.name); var vhm = localGameObject.GetComponentInChildren(); @@ -959,72 +1275,69 @@ public static void LoadPQS(string bodyName) }, localUpdate: delegate(PFBody body) { - print("Updating Local " + body.name); LoadPQS(body.name); }), #if true - new PFBody("Serious", "Sun", 200, - new PFOrbit - { - inclination = 30.0f, - eccentricity = 0.2, - semiMajorAxis = 450000000000, - LAN = 0, - argumentOfPeriapsis = 0, - meanAnomalyAtEpoch = 0, - epoch = 0, - referenceBody = "Sun" - }, - localUpdate: delegate(PFBody body) - { - print("Updating Local " + body.name); - var localGameObject = PFUtil.FindLocal(body.name); - var cb = localGameObject.GetComponent(); - - //cb.GeeASL = 0.0962500333786; - //cb.CBUpdate(); - }), - - new PFBody("Joker", "Minmus", 210, - new PFOrbit - { - inclination = 30.0f, - eccentricity = 0, - semiMajorAxis = 2610000000, - LAN = 0, - argumentOfPeriapsis = 0, - meanAnomalyAtEpoch = 0, - epoch = 0, - referenceBody = "Serious" - }, - localUpdate: delegate(PFBody body) - { - print("Updating Local " + body.name); - var localGameObject = PFUtil.FindLocal(body.name); - var vp = localGameObject.GetComponentInChildren(); - if (vp != null) - { - vp.seed = 666; - vp.deformity = 10000; - - vp.landClasses[0].baseColor = new Color(0.4f, 0.1f, 0.1f); - vp.landClasses[1].baseColor = new Color(0.4f, 0.7f, 0.4f); - vp.landClasses[2].baseColor = new Color(0.5f, 0.5f, 0.7f); - vp.landClasses[3].baseColor = new Color(0.9f, 0.9f, 0.9f); - - vp.sphere.minDetailDistance = 8; - vp.sphere.minLevel = 1; - vp.sphere.maxLevel = 9; - - vp.RebuildSphere(); - } - - var orbitDriver = localGameObject.GetComponent(); - if (orbitDriver != null) - orbitDriver.orbitColor = Color.magenta; - - }), + //new PFBody("Serious", "Sun", 200, + // new PFOrbit + // { + // inclination = 30.0f, + // eccentricity = 0.2, + // semiMajorAxis = 450000000000, + // LAN = 0, + // argumentOfPeriapsis = 0, + // meanAnomalyAtEpoch = 0, + // epoch = 0, + // referenceBody = "Sun" + // }, + // localUpdate: delegate(PFBody body) + // { + // var localGameObject = PFUtil.FindLocal(body.name); + // var cb = localGameObject.GetComponent(); + + // //cb.GeeASL = 0.0962500333786; + // //cb.CBUpdate(); + // }), + + //new PFBody("Joker", "Minmus", 210, + // new PFOrbit + // { + // inclination = 30.0f, + // eccentricity = 0, + // semiMajorAxis = 2610000000, + // LAN = 0, + // argumentOfPeriapsis = 0, + // meanAnomalyAtEpoch = 0, + // epoch = 0, + // referenceBody = "Serious" + // }, + // localUpdate: delegate(PFBody body) + // { + // var localGameObject = PFUtil.FindLocal(body.name); + // var vp = localGameObject.GetComponentInChildren(); + // if (vp != null) + // { + // vp.seed = 666; + // vp.deformity = 10000; + + // vp.landClasses[0].baseColor = new Color(0.4f, 0.1f, 0.1f); + // vp.landClasses[1].baseColor = new Color(0.4f, 0.7f, 0.4f); + // vp.landClasses[2].baseColor = new Color(0.5f, 0.5f, 0.7f); + // vp.landClasses[3].baseColor = new Color(0.9f, 0.9f, 0.9f); + + // vp.sphere.minDetailDistance = 8; + // vp.sphere.minLevel = 1; + // vp.sphere.maxLevel = 9; + + // vp.RebuildSphere(); + // } + + // var orbitDriver = localGameObject.GetComponent(); + // if (orbitDriver != null) + // orbitDriver.orbitColor = Color.magenta; + + // }), #endif @@ -1078,6 +1391,8 @@ public static void LoadScaledPlanetTextures(string planetName, Texture2D colorTe { var scaledPlanet = ScaledSpace.Instance.transform.FindChild(planetName).gameObject; var smallPlanetMeshRenderer = (MeshRenderer) scaledPlanet.GetComponentInChildren((typeof (MeshRenderer))); + if (smallPlanetMeshRenderer == null) + return; if (colorTexture != null) smallPlanetMeshRenderer.material.mainTexture = colorTexture; if (bumpTexture != null) @@ -1113,6 +1428,7 @@ public PlanetFactoryPartlessLoader() public static class PlanetFactoryPluginWrapper { public static GameObject PlanetFactory; + public static GameObject DebugConsole; public static void Initialize() { @@ -1123,6 +1439,13 @@ public static void Initialize() new [] {typeof (PlanetFactory.PlanetFactory)}); UnityEngine.Object.DontDestroyOnLoad(PlanetFactory); } + if (GameObject.Find("DebugConsole") == null) + { + DebugConsole = new GameObject( + "DebugConsole", + new[] { typeof(PlanetFactory.DebugConsole) }); + UnityEngine.Object.DontDestroyOnLoad(DebugConsole); + } } } diff --git a/PlanetFactory/PlanetFactory.csproj b/PlanetFactory/PlanetFactory.csproj index d256e1a..e77494f 100644 --- a/PlanetFactory/PlanetFactory.csproj +++ b/PlanetFactory/PlanetFactory.csproj @@ -35,7 +35,8 @@ 4 - + + False ..\..\..\..\KSP_dev\KSP_Data\Managed\Assembly-CSharp.dll @@ -44,11 +45,13 @@ - + + False ..\..\..\..\KSP_dev\KSP_Data\Managed\UnityEngine.dll + From b90a8c2df735216caffa295b7804a467b2b1b448 Mon Sep 17 00:00:00 2001 From: Kragrathea Date: Wed, 22 Jan 2014 20:16:40 -0800 Subject: [PATCH 2/4] Fix PF pqs mods not working in 0.23 --- PlanetFactory/PFMods.cs | 42 +++++++++++++++-------------------------- 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/PlanetFactory/PFMods.cs b/PlanetFactory/PFMods.cs index 881d6c1..b4e178e 100644 --- a/PlanetFactory/PFMods.cs +++ b/PlanetFactory/PFMods.cs @@ -11,13 +11,13 @@ public class PQSMod_PFHeightColor : PQSMod public LandClass[] landClasses=null; public bool lerp = true; - new public void OnSetup() + public override void OnSetup() { requirements = PQS.ModiferRequirements.MeshColorChannel; blend = 1f; } - new public void OnVertexBuild(PQS.VertexBuildData data) + public override void OnVertexBuild(PQS.VertexBuildData data) { var height = (data.vertHeight - sphere.radiusMin) / (sphere.radiusMax - sphere.radiusMin); @@ -90,30 +90,26 @@ public PQSMod_PFOblate() { } - public void OnSetup() + public override void OnSetup() { this.requirements = PQS.ModiferRequirements.MeshCustomNormals; } - public double GetVertexMaxHeight() + public override double GetVertexMaxHeight() { return offset; } - public double GetVertexMinHeight() + public override double GetVertexMinHeight() { return offset; } - public void OnVertexBuildHeight(PQS.VertexBuildData vbData) + public override void OnVertexBuildHeight(PQS.VertexBuildData vbData) { var hei = Math.Sin(3.14159265358979 * vbData.v); hei = Math.Pow(hei, power); vbData.vertHeight = vbData.vertHeight + hei * offset; } - - private void Reset() - { - } } public class PQSMod_PFOffset : PQSMod @@ -123,28 +119,24 @@ public PQSMod_PFOffset() { } - public void OnSetup() + public override void OnSetup() { this.requirements = PQS.ModiferRequirements.MeshCustomNormals; } - public double GetVertexMaxHeight() + public override double GetVertexMaxHeight() { return offset; } - public double GetVertexMinHeight() + public override double GetVertexMinHeight() { return offset; } - public void OnVertexBuildHeight(PQS.VertexBuildData vbData) + public override void OnVertexBuildHeight(PQS.VertexBuildData vbData) { vbData.vertHeight = vbData.vertHeight+offset; } - - private void Reset() - { - } } public class PQSMod_PFDebug : PQSMod @@ -155,21 +147,21 @@ public PQSMod_PFDebug() { } - public void OnSetup() + public override void OnSetup() { this.requirements = PQS.ModiferRequirements.MeshCustomNormals; } - public double GetVertexMaxHeight() + public override double GetVertexMaxHeight() { return offset; } - public double GetVertexMinHeight() + public override double GetVertexMinHeight() { return offset; } - new public void OnVertexBuild(PQS.VertexBuildData data) + public override void OnVertexBuild(PQS.VertexBuildData data) { if (data.vertHeight < sphere.radius+5) { @@ -177,7 +169,7 @@ public double GetVertexMinHeight() } } - public void OnVertexBuildHeight(PQS.VertexBuildData vbData) + public override void OnVertexBuildHeight(PQS.VertexBuildData vbData) { if(vbData.vertHeight Date: Tue, 29 Apr 2014 16:02:01 +1000 Subject: [PATCH 3/4] Star Fix Module Handler Upgraded star fix module, directly from my plugin!. Requires a few more things in the main loader, but its a start... --- PlanetFactory/StarFixModule | 155 ++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 PlanetFactory/StarFixModule diff --git a/PlanetFactory/StarFixModule b/PlanetFactory/StarFixModule new file mode 100644 index 0000000..1fc0209 --- /dev/null +++ b/PlanetFactory/StarFixModule @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using System.Reflection; +using KSP.IO; + +namespace PlanetFactory +{ + + //Helper class! + public class CustomStar : Sun + { + public bool Toggle; + + public CustomStar() + { + useLocalSpaceSunLight = true; + } + + public void Awake() + { + //Override to stop Bad Things(tm) from happening! + } + } + + //Helper class! + public class FixedStar + { + public FixedStar( string IName, CustomStar ICStar) + { + Name = IName; + CStar = ICStar; + } + + public string Name; + public CustomStar CStar; + }; + + public class Detector : MonoBehaviour + { + //bool Toggle; + + Dictionary< string, FixedStar> Stars = new Dictionary(); + + public void AddStar( string Name, CustomStar CStar ) + { + Stars.Add( Name, new FixedStar( Name, CStar) ); + } + + void Update() + { + if( Stars.Count <= 0 ) + { + return; + } + + //TODO: Fix support for binary+ star systems. + foreach( FixedStar LoopedStar in Stars.Values ) + { + //Grab altitude + Vector3 pos = ScaledSpace.ScaledToLocalSpace( PlanetariumCamera.fetch.GetCameraTransform().position ); + Vector3 pos2; + if( FlightGlobals.ActiveVessel != null ) + { + pos2 = FlightGlobals.ActiveVessel.GetTransform().position; + } + double dist; + + dist = FlightGlobals.getAltitudeAtPos(pos, LoopedStar.CStar.sun); + + //In map mode? + if( PlanetariumCamera.fetch.enabled == true ) + { + if( dist < LoopedStar.CStar.sun.sphereOfInfluence ) + { + if( LoopedStar.CStar.Toggle == true ) + { + print ( "Scaled Enabling "+LoopedStar.Name+" Sun \n"); + LoopedStar.CStar.SunlightEnabled( true ); //Enable OUR stars light! + + Sun.Instance.SunlightEnabled( false ); + LoopedStar.CStar.Toggle = false; + + Planetarium.fetch.Sun = Utils.FindCB( LoopedStar.Name ); //Set the sun to OUR sun! + + foreach( ModuleDeployableSolarPanel panel in FindObjectsOfType( typeof( ModuleDeployableSolarPanel ) ) ) //Reboot solar panels + { + panel.OnStart( PartModule.StartState.None ); //todo: find out what the partstate does. + } + } + } + else if( LoopedStar.CStar.Toggle == false ) + { + print ( "Scaled Disabling "+LoopedStar.Name+" Sun\n" ); + LoopedStar.CStar.SunlightEnabled( false ); //Disable our star + Sun.Instance.SunlightEnabled( true ); //Enable Kerbol + LoopedStar.CStar.Toggle = true; + + Planetarium.fetch.Sun = Utils.FindCB( "Sun" ); //Reset this + foreach( ModuleDeployableSolarPanel panel in FindObjectsOfType( typeof( ModuleDeployableSolarPanel ) ) ) //Reboot solar panels + { + panel.OnStart( PartModule.StartState.None ); + } + } + } + else + { + //LocalSpace + //Grab positions + if( FlightGlobals.ActiveVessel != null ) + { + dist = FlightGlobals.getAltitudeAtPos(pos2, LoopedStar.CStar.sun); + if( dist < LoopedStar.CStar.sun.sphereOfInfluence ) + { + if( LoopedStar.CStar.Toggle == true ) + { + print ( "Local Enabling Reslah Sun \n"); + LoopedStar.CStar.SunlightEnabled( true ); + Sun.Instance.SunlightEnabled( false ); + + Planetarium.fetch.Sun = Utils.FindCB( LoopedStar.Name ); + + foreach( ModuleDeployableSolarPanel panel in FindObjectsOfType( typeof( ModuleDeployableSolarPanel ) ) ) + { + panel.OnStart( PartModule.StartState.None ); + } + LoopedStar.CStar.Toggle = false; + } + } + else + { + if( LoopedStar.CStar.Toggle == false ) + { + print ( "Local Disabling Reslah Sun\n" ); + LoopedStar.CStar.SunlightEnabled( false ); + Sun.Instance.SunlightEnabled( true ); + + Planetarium.fetch.Sun = Utils.FindCB( "Sun" ); + + + foreach( ModuleDeployableSolarPanel panel in FindObjectsOfType( typeof( ModuleDeployableSolarPanel ) ) ) + { + panel.OnStart( PartModule.StartState.None ); + } + LoopedStar.CStar.Toggle = true; + } + } + } + } + } + } + } +} + From 8cfc1e3b61fd058dbeae33340d0b283e02f5c6c6 Mon Sep 17 00:00:00 2001 From: Kittopia Creator Date: Tue, 29 Apr 2014 16:05:31 +1000 Subject: [PATCH 4/4] Added starfix data Starfix Data --- PlanetFactory/PFUtil.cs | 57 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/PlanetFactory/PFUtil.cs b/PlanetFactory/PFUtil.cs index ed79f7a..6ed5faa 100644 --- a/PlanetFactory/PFUtil.cs +++ b/PlanetFactory/PFUtil.cs @@ -619,6 +619,63 @@ public static string MeshToString(MeshFilter mf) } return sb.ToString(); } + + + //RelsahSystem code: + //Reslah fix ported for multiuse + public static void FixStar( string starName ) + { + //Get defualt stuff + GameObject Scenery = GameObject.Find("Scenery"); + Sun DefualtStar = Scenery.GetComponentInChildren(); + + //Create a new instance of "scenery star" + GameObject newSceneryStar = new GameObject( starName + "_scenery" ); + newSceneryStar.transform.parent = Scenery.transform; + + //Create a new lense flare, and dump the existing suns data to it. + LensFlare NewLenseFlare = newSceneryStar.AddComponent(); + NewLenseFlare.color = GameObject.Find("SunLight").GetComponentInChildren().color; + NewLenseFlare.flare = GameObject.Find("SunLight").GetComponentInChildren().flare; + + //Add the "light" + Light newLight = newSceneryStar.AddComponent(); + + //Create a new instance of "CustomStar" + CustomStar newStar = newSceneryStar.AddComponent(); + newStar.name = starName + "Sun"; + newStar.target = DefualtStar.target; + newStar.brightnessCurve = DefualtStar.brightnessCurve; + newStar.AU = DefualtStar.AU; + newStar.sun = Utils.FindCB( starName ); + newStar.sunFlare = NewLenseFlare; + newStar.localTime = DefualtStar.localTime; + newStar.fadeStart = DefualtStar.fadeStart; + newStar.fadeEnd = DefualtStar.fadeEnd; + + newLight.type = DefualtStar.light.type; + newLight.transform.position = Utils.FindCB( starName ).transform.position; + newLight.transform.parent = Utils.FindCB( starName ).transform.parent; + + newSceneryStar.transform.position = Utils.FindScaled( starName ).transform.position; + newSceneryStar.transform.parent = Utils.FindScaled( starName ).transform; + newSceneryStar.layer = Utils.FindScaled( starName ).layer; + + GameObject DetectorGOB; + + if( GameObject.FindObjectOfType( typeof( Detector ) ) == null ) //spawn a new detector + { + DetectorGOB = new GameObject( "Detector", typeof( Detector ) ); + GameObject.DontDestroyOnLoad( DetectorGOB ); + } + else + { + DetectorGOB = (GameObject)GameObject.FindObjectOfType( typeof( Detector ) ); + } + + Detector StarFixer = (Detector)DetectorGOB.GetComponent( typeof(Detector) ); + StarFixer.AddStar( starName, newStar ); + } }