// Use the nearest star as the AFG star
        private void AtmosphereLightPatch(CelestialBody body)
        {
            if (!body.afg)
            {
                return;
            }

            GameObject star           = KopernicusStar.GetBrightest(body).gameObject;
            Vector3    afgCamPosition = body.afg.mainCamera.transform.position;
            Vector3    distance       = body.scaledBody.transform.position - afgCamPosition;

            body.afg.lightDot = Mathf.Clamp01(Vector3.Dot(distance, afgCamPosition - star.transform.position) * body.afg.dawnFactor);
            body.afg.GetComponent <Renderer>().sharedMaterial.SetFloat(_lightDot, body.afg.lightDot);
        }
Example #2
0
        // Patch various references to point to the nearest star
        private static void PatchStarReferences(CelestialBody body)
        {
            GameObject star = KopernicusStar.GetNearest(body).gameObject;

            if (body.afg != null)
            {
                body.afg.sunLight = star;
            }
            if (body.scaledBody.GetComponent <MaterialSetDirection>() != null)
            {
                body.scaledBody.GetComponent <MaterialSetDirection>().target = star.transform;
            }
            foreach (PQSMod_MaterialSetDirection msd in
                     body.GetComponentsInChildren <PQSMod_MaterialSetDirection>(true))
            {
                msd.target = star.transform;
            }
        }
        // Apply the star patch to the center body
        private static void ApplyStarPatchSun()
        {
            // Sun
            GameObject     gob  = Sun.Instance.gameObject;
            KopernicusStar star = gob.AddComponent <KopernicusStar>();

            Utility.CopyObjectFields(Sun.Instance, star, false);
            DestroyImmediate(Sun.Instance);
            Sun.Instance = star;
            // SunFlare
            gob = SunFlare.Instance.gameObject;
            KopernicusSunFlare flare = gob.AddComponent <KopernicusSunFlare>();

            gob.name = star.sun.name;
            Utility.CopyObjectFields(SunFlare.Instance, flare, false);
            DestroyImmediate(SunFlare.Instance);
            SunFlare.Instance = star.lensFlare = flare;
        }
Example #4
0
        void Update()
        {
            // When StarLightSwitcher changes the active star
            if (KopernicusStar.Current != activeStar && activeFlares.ContainsKey(KopernicusStar.Current.name))
            {
                // Restore default sunFlare
                if (activeStar != null && oldFlare != null)
                {
                    activeStar.lensFlare.sunFlare.flare = oldFlare;
                }

                // Select current activeStar
                activeStar = KopernicusStar.Current;

                // Backup default flare and load activeFlare
                if (activeStar != null && activeStar.lensFlare.sunFlare != null)
                {
                    oldFlare = activeStar.lensFlare.sunFlare.flare;
                    activeStar.lensFlare.sunFlare.flare = activeFlares[activeStar.name];
                }
            }
        }
Example #5
0
        // Awake() - flag this class as don't destroy on load and register delegates
        void Awake()
        {
            // Don't run if Kopernicus isn't compatible
            if (!CompatibilityChecker.IsCompatible())
            {
                Destroy(this);
                return;
            }

            // Make sure the runtime utility isn't killed
            DontDestroyOnLoad(this);

            // Add handlers
            GameEvents.onPartUnpack.Add(OnPartUnpack);
            GameEvents.onLevelWasLoaded.Add(FixCameras);
            GameEvents.onLevelWasLoaded.Add(delegate(GameScenes scene)
            {
                if (HighLogic.LoadedSceneHasPlanetarium && MapView.fetch != null)
                {
                    MapView.fetch.max3DlineDrawDist = 20000f;
                }
                if (scene == GameScenes.MAINMENU)
                {
                    UpdateMenu();
                }
                if (scene == GameScenes.SPACECENTER)
                {
                    PatchFI();
                }
                foreach (CelestialBody body in PSystemManager.Instance.localBodies)
                {
                    GameObject star_ = KopernicusStar.GetNearest(body).gameObject;
                    if (body.afg != null)
                    {
                        body.afg.sunLight = star_;
                    }
                    if (body.scaledBody.GetComponent <MaterialSetDirection>() != null)
                    {
                        body.scaledBody.GetComponent <MaterialSetDirection>().target = star_.transform;
                    }
                    foreach (PQSMod_MaterialSetDirection msd in body.GetComponentsInChildren <PQSMod_MaterialSetDirection>(true))
                    {
                        msd.target = star_.transform;
                    }
                }
                foreach (TimeOfDayAnimation anim in Resources.FindObjectsOfTypeAll <TimeOfDayAnimation>())
                {
                    anim.target = KopernicusStar.GetNearest(FlightGlobals.GetHomeBody()).gameObject.transform;
                }
            });

            // Update Music Logic
            if (MusicLogic.fetch != null && FlightGlobals.fetch != null && FlightGlobals.GetHomeBody() != null)
            {
                MusicLogic.fetch.flightMusicSpaceAltitude = FlightGlobals.GetHomeBody().atmosphereDepth;
            }

            // Log
            Logger.Default.Log("[Kopernicus] RuntimeUtility Started");
            Logger.Default.Flush();
        }
Example #6
0
        // Stuff
        void LateUpdate()
        {
            FixZooming();
            ApplyOrbitVisibility();
            RDFixer();

            // Remove buttons in map view for barycenters
            if (MapView.MapIsEnabled)
            {
                if (fields == null)
                {
                    FieldInfo mode_f    = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType.IsEnum && f.FieldType.IsNested);
                    FieldInfo context_f = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType == typeof(MapContextMenu));
                    FieldInfo cast_f    = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType == typeof(OrbitRenderer.OrbitCastHit));
                    fields = new FieldInfo[] { mode_f, context_f, cast_f };
                }
                if (FlightGlobals.ActiveVessel != null)
                {
                    OrbitTargeter targeter = FlightGlobals.ActiveVessel.orbitTargeter;
                    if (targeter == null)
                    {
                        return;
                    }
                    Int32 mode = (Int32)fields[0].GetValue(targeter);
                    if (mode == 2)
                    {
                        OrbitRenderer.OrbitCastHit cast = (OrbitRenderer.OrbitCastHit)fields[2].GetValue(targeter);
                        CelestialBody body = PSystemManager.Instance.localBodies.Find(b => b.name == cast.or?.discoveryInfo?.name?.Value);
                        if (body == null)
                        {
                            return;
                        }
                        if (body.Has("barycenter") || body.Has("notSelectable"))
                        {
                            if (cast.driver?.Targetable == null)
                            {
                                return;
                            }
                            MapContextMenu context = MapContextMenu.Create(body.name, new Rect(0.5f, 0.5f, 300f, 50f), cast, () =>
                            {
                                fields[0].SetValue(targeter, 0);
                                fields[1].SetValue(targeter, null);
                            }, new SetAsTarget(cast.driver.Targetable, () => FlightGlobals.fetch.VesselTarget));
                            fields[1].SetValue(targeter, context);
                        }
                    }
                }
            }


            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                if (body.afg == null)
                {
                    continue;
                }
                GameObject star_      = KopernicusStar.GetNearest(body).gameObject;
                Vector3    planet2cam = body.scaledBody.transform.position - body.afg.mainCamera.transform.position;
                body.afg.lightDot = Mathf.Clamp01(Vector3.Dot(planet2cam, body.afg.mainCamera.transform.position - star_.transform.position) * body.afg.dawnFactor);
                body.afg.GetComponent <Renderer>().material.SetFloat("_lightDot", body.afg.lightDot);
            }
        }
Example #7
0
        // Execute MainMenu functions
        void Start()
        {
            previous = PlanetariumCamera.fetch.initialTarget;
            PlanetariumCamera.fetch.targets
            .Where(m => m.celestialBody != null && (m.celestialBody.Has("barycenter") || m.celestialBody.Has("notSelectable")))
            .ToList()
            .ForEach(map => PlanetariumCamera.fetch.targets.Remove(map));

            // Stars
            GameObject     gob  = Sun.Instance.gameObject;
            KopernicusStar star = gob.AddComponent <KopernicusStar>();

            Utility.CopyObjectFields(Sun.Instance, star, false);
            DestroyImmediate(Sun.Instance);
            Sun.Instance = star;

            // Bodies
            Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> > fixes = new Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> >();

            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                // More stars
                if (body.flightGlobalsIndex != 0 && body.scaledBody.GetComponentsInChildren <SunShaderController>(true).Length > 0)
                {
                    GameObject     starObj = Instantiate(Sun.Instance.gameObject);
                    KopernicusStar star_   = starObj.GetComponent <KopernicusStar>();
                    star_.sun = body;
                    starObj.transform.parent        = Sun.Instance.transform.parent;
                    starObj.name                    = body.name;
                    starObj.transform.localPosition = Vector3.zero;
                    starObj.transform.localRotation = Quaternion.identity;
                    starObj.transform.localScale    = Vector3.one;
                    starObj.transform.position      = body.position;
                    starObj.transform.rotation      = body.rotation;
                }

                // Post spawn patcher
                if (body.Has("orbitPatches"))
                {
                    ConfigNode  orbitNode = body.Get <ConfigNode>("orbitPatches");
                    OrbitLoader loader    = new OrbitLoader(body);
                    Parser.LoadObjectFromConfigurationNode(loader, orbitNode, "Kopernicus");
                    body.orbitDriver.orbit = loader.orbit;
                    CelestialBody oldRef = body.referenceBody;
                    body.referenceBody.orbitingBodies.Remove(body);
                    body.orbit.referenceBody = body.orbitDriver.referenceBody = PSystemManager.Instance.localBodies.Find(b => b.transform.name == loader.referenceBody);
                    fixes.Add(body.transform.name, new KeyValuePair <CelestialBody, CelestialBody>(oldRef, body.referenceBody));
                    body.referenceBody.orbitingBodies.Add(body);
                    body.referenceBody.orbitingBodies = body.referenceBody.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
                    body.orbit.Init();
                    body.orbitDriver.UpdateOrbit();

                    // Calculations
                    if (!body.Has("sphereOfInfluence"))
                    {
                        body.sphereOfInfluence = body.orbit.semiMajorAxis * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.4);
                    }
                    if (!body.Has("hillSphere"))
                    {
                        body.hillSphere = body.orbit.semiMajorAxis * (1 - body.orbit.eccentricity) * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.333333333333333);
                    }
                    if (body.solarRotationPeriod)
                    {
                        double rotPeriod = Utility.FindBody(PSystemManager.Instance.systemPrefab.rootBody, body.transform.name).celestialBody.rotationPeriod;
                        double num1      = Math.PI * 2 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
                        body.rotationPeriod = rotPeriod * num1 / (num1 + rotPeriod);;
                    }
                }
            }

            // Update the order in the tracking station
            List <MapObject> trackingstation = new List <MapObject>();

            Utility.DoRecursive(PSystemManager.Instance.localBodies[0], cb => cb.orbitingBodies, cb =>
            {
                trackingstation.Add(PlanetariumCamera.fetch.targets.Find(t => t.celestialBody == cb));
            });
            PlanetariumCamera.fetch.targets.Clear();
            PlanetariumCamera.fetch.targets.AddRange(trackingstation);

            // Undo stuff
            foreach (CelestialBody b in PSystemManager.Instance.localBodies.Where(b_ => b_.Has("orbitPatches")))
            {
                fixes[b.transform.name].Value.orbitingBodies.Remove(b);
                fixes[b.transform.name].Key.orbitingBodies.Add(b);
                fixes[b.transform.name].Key.orbitingBodies = fixes[b.transform.name].Key.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
            }
            UpdateMenu();
        }
Example #8
0
        // Awake() - flag this class as don't destroy on load and register delegates
        void Awake()
        {
            // Don't run if Kopernicus isn't compatible
            if (!CompatibilityChecker.IsCompatible())
            {
                Destroy(this);
                return;
            }

            // Make sure the runtime utility isn't killed
            DontDestroyOnLoad(this);

            // Init the runtime logging
            new Logger("Kopernicus.Runtime").SetAsActive();

            // Add handlers
            GameEvents.onPartUnpack.Add(OnPartUnpack);
            GameEvents.onLevelWasLoaded.Add(FixCameras);
            GameEvents.OnMapEntered.Add(delegate { _mapDirty = true; });
            GameEvents.onLevelWasLoaded.Add(delegate(GameScenes scene)
            {
                //if (MapView.fetch != null)
                //    MapView.fetch.max3DlineDrawDist = Single.MaxValue;
                if (scene == GameScenes.SPACECENTER)
                {
                    PatchFI();
                }
                foreach (CelestialBody body in PSystemManager.Instance.localBodies)
                {
                    GameObject star = KopernicusStar.GetNearest(body).gameObject;
                    if (body.afg != null)
                    {
                        body.afg.sunLight = star;
                    }
                    if (body.scaledBody.GetComponent <MaterialSetDirection>() != null)
                    {
                        body.scaledBody.GetComponent <MaterialSetDirection>().target = star.transform;
                    }

                    foreach (PQSMod_MaterialSetDirection msd in body.GetComponentsInChildren <PQSMod_MaterialSetDirection>(true))
                    {
                        msd.target = star.transform;
                    }

                    // Contract Weight
                    if (ContractSystem.ContractWeights != null)
                    {
                        if (body.Has("contractWeight"))
                        {
                            if (ContractSystem.ContractWeights.ContainsKey(body.name))
                            {
                                ContractSystem.ContractWeights[body.name] = body.Get <Int32>("contractWeight");
                            }
                            else
                            {
                                ContractSystem.ContractWeights.Add(body.name, body.Get <Int32>("contractWeight"));
                            }
                        }
                    }
                }

                foreach (TimeOfDayAnimation anim in Resources.FindObjectsOfTypeAll <TimeOfDayAnimation>())
                {
                    anim.target = KopernicusStar.GetNearest(FlightGlobals.GetHomeBody()).gameObject.transform;
                }
#if FALSE
                foreach (TimeOfDayAnimation anim in Resources.FindObjectsOfTypeAll <TimeOfDayAnimation>())
                {
                    anim.gameObject.AddOrGetComponent <KopernicusStarTimeOfDay>();
                }

                foreach (GalaxyCubeControl control in Resources.FindObjectsOfTypeAll <GalaxyCubeControl>())
                {
                    control.gameObject.AddOrGetComponent <KopernicusStarGalaxyCubeControl>();
                }

                foreach (SkySphereControl control in Resources.FindObjectsOfTypeAll <SkySphereControl>())
                {
                    control.gameObject.AddOrGetComponent <KopernicusStarSkySphereControl>();
                }
#endif
            });
            GameEvents.onProtoVesselLoad.Add(TransformBodyReferencesOnLoad);
            GameEvents.onProtoVesselSave.Add(TransformBodyReferencesOnSave);

            // Update Music Logic
            if (MusicLogic.fetch != null && FlightGlobals.fetch != null && FlightGlobals.GetHomeBody() != null)
            {
                MusicLogic.fetch.flightMusicSpaceAltitude = FlightGlobals.GetHomeBody().atmosphereDepth;
            }

            // Log
            Logger.Default.Log("[Kopernicus] RuntimeUtility Started");
            Logger.Default.Flush();
        }
Example #9
0
        // Stuff
        void LateUpdate()
        {
            FixZooming();
            ApplyOrbitVisibility();
            RDFixer();
            ApplyOrbitIconCustomization();

            // Prevent the orbit lines from flickering
            PlanetariumCamera.Camera.farClipPlane = 1e14f;

            // Remove buttons in map view for barycenters
            if (MapView.MapIsEnabled)
            {
                if (fields == null)
                {
                    FieldInfo mode_f    = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType.IsEnum && f.FieldType.IsNested);
                    FieldInfo context_f = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType == typeof(MapContextMenu));
                    #if !KSP131
                    FieldInfo cast_f = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType == typeof(OrbitRendererBase.OrbitCastHit));
                    #else
                    FieldInfo cast_f = typeof(OrbitTargeter).GetFields(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(f => f.FieldType == typeof(OrbitRenderer.OrbitCastHit));
                    #endif
                    fields = new FieldInfo[] { mode_f, context_f, cast_f };
                }
                if (FlightGlobals.ActiveVessel != null)
                {
                    OrbitTargeter targeter = FlightGlobals.ActiveVessel.orbitTargeter;
                    if (targeter == null)
                    {
                        return;
                    }
                    Int32 mode = (Int32)fields[0].GetValue(targeter);
                    if (mode == 2)
                    {
                        #if !KSP131
                        OrbitRendererBase.OrbitCastHit cast = (OrbitRendererBase.OrbitCastHit)fields[2].GetValue(targeter);
                        #else
                        OrbitRenderer.OrbitCastHit cast = (OrbitRenderer.OrbitCastHit)fields[2].GetValue(targeter);
                        #endif
                        CelestialBody body = PSystemManager.Instance.localBodies.Find(b => b.name == cast.or?.discoveryInfo?.name?.Value);
                        if (body == null)
                        {
                            return;
                        }
                        if (body.Has("barycenter") || !body.Get("selectable", true))
                        {
                            if (cast.driver?.Targetable == null)
                            {
                                return;
                            }
                            MapContextMenu context = MapContextMenu.Create(body.name, new Rect(0.5f, 0.5f, 300f, 50f), cast, () =>
                            {
                                fields[0].SetValue(targeter, 0);
                                fields[1].SetValue(targeter, null);
                            }, new SetAsTarget(cast.driver.Targetable, () => FlightGlobals.fetch.VesselTarget));
                            fields[1].SetValue(targeter, context);
                        }
                    }
                }
            }

            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                if (body.afg == null)
                {
                    continue;
                }
                GameObject star_      = KopernicusStar.GetNearest(body).gameObject;
                Vector3    planet2cam = body.scaledBody.transform.position - body.afg.mainCamera.transform.position;
                body.afg.lightDot = Mathf.Clamp01(Vector3.Dot(planet2cam, body.afg.mainCamera.transform.position - star_.transform.position) * body.afg.dawnFactor);
                body.afg.GetComponent <Renderer>().sharedMaterial.SetFloat("_lightDot", body.afg.lightDot);
            }

            // Update the names of the presets in the settings dialog
            if (HighLogic.LoadedScene == GameScenes.SETTINGS)
            {
                foreach (SettingsTerrainDetail detail in Resources.FindObjectsOfTypeAll <SettingsTerrainDetail>())
                {
                    detail.displayStringValue = true;
                    detail.stringValues       = _details ?? (_details = Templates.PresetDisplayNames.ToArray());
                }
            }
        }
Example #10
0
        // Execute MainMenu functions
        void Start()
        {
            previous = PlanetariumCamera.fetch.initialTarget;
            PlanetariumCamera.fetch.targets
            .Where(m => m.celestialBody != null && (m.celestialBody.Has("barycenter") || !m.celestialBody.Get("selectable", true)))
            .ToList()
            .ForEach(map => PlanetariumCamera.fetch.targets.Remove(map));

            // Stars
            GameObject     gob  = Sun.Instance.gameObject;
            KopernicusStar star = gob.AddComponent <KopernicusStar>();

            Utility.CopyObjectFields(Sun.Instance, star, false);
            DestroyImmediate(Sun.Instance);
            Sun.Instance = star;

            // LensFlares
            gob = SunFlare.Instance.gameObject;
            KopernicusSunFlare flare = gob.AddComponent <KopernicusSunFlare>();

            gob.name = star.sun.name;
            Utility.CopyObjectFields(SunFlare.Instance, flare, false);
            DestroyImmediate(SunFlare.Instance);
            SunFlare.Instance = star.lensFlare = flare;

            // Bodies
            Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> > fixes = new Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> >();

            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                // More stars
                if (body.flightGlobalsIndex != 0 && body.scaledBody.GetComponentsInChildren <SunShaderController>(true).Length > 0)
                {
                    GameObject starObj = Instantiate(Sun.Instance.gameObject);
                    star     = starObj.GetComponent <KopernicusStar>();
                    star.sun = body;
                    starObj.transform.parent        = Sun.Instance.transform.parent;
                    starObj.name                    = body.name;
                    starObj.transform.localPosition = Vector3.zero;
                    starObj.transform.localRotation = Quaternion.identity;
                    starObj.transform.localScale    = Vector3.one;
                    starObj.transform.position      = body.position;
                    starObj.transform.rotation      = body.rotation;

                    GameObject flareObj = Instantiate(SunFlare.Instance.gameObject);
                    flare                            = flareObj.GetComponent <KopernicusSunFlare>();
                    star.lensFlare                   = flare;
                    flareObj.transform.parent        = SunFlare.Instance.transform.parent;
                    flareObj.name                    = body.name;
                    flareObj.transform.localPosition = Vector3.zero;
                    flareObj.transform.localRotation = Quaternion.identity;
                    flareObj.transform.localScale    = Vector3.one;
                    flareObj.transform.position      = body.position;
                    flareObj.transform.rotation      = body.rotation;
                }

                // Post spawn patcher
                if (body.Has("orbitPatches"))
                {
                    ConfigNode  orbitNode = body.Get <ConfigNode>("orbitPatches");
                    OrbitLoader loader    = new OrbitLoader(body);
                    Parser.LoadObjectFromConfigurationNode(loader, orbitNode, "Kopernicus");
                    CelestialBody oldRef = body.referenceBody;
                    body.referenceBody.orbitingBodies.Remove(body);

                    CelestialBody newRef = UBI.GetBody(loader.referenceBody);
                    if (newRef != null)
                    {
                        body.orbit.referenceBody = body.orbitDriver.referenceBody = newRef;
                    }
                    else
                    {
                        // Log the exception
                        Debug.Log("Exception: PostSpawnOrbit reference body for \"" + body.name + "\" could not be found. Missing body name is \"" + loader.referenceBody + "\".");

                        // Open the Warning popup
                        Injector.DisplayWarning();
                    }

                    fixes.Add(body.transform.name, new KeyValuePair <CelestialBody, CelestialBody>(oldRef, body.referenceBody));
                    body.referenceBody.orbitingBodies.Add(body);
                    body.referenceBody.orbitingBodies = body.referenceBody.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
                    body.orbit.Init();
                    body.orbitDriver.UpdateOrbit();

                    // Calculations
                    if (!body.Has("sphereOfInfluence"))
                    {
                        body.sphereOfInfluence = body.orbit.semiMajorAxis * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.4);
                    }
                    if (!body.Has("hillSphere"))
                    {
                        body.hillSphere = body.orbit.semiMajorAxis * (1 - body.orbit.eccentricity) * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.333333333333333);
                    }
                    if (body.solarRotationPeriod)
                    {
                        Double rotPeriod = Utility.FindBody(PSystemManager.Instance.systemPrefab.rootBody, body.transform.name).celestialBody.rotationPeriod;
                        Double num1      = Math.PI * 2 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
                        body.rotationPeriod = rotPeriod * num1 / (num1 + rotPeriod);;
                    }
                }
            }

            // Update the order in the tracking station
            List <MapObject> trackingstation = new List <MapObject>();

            Utility.DoRecursive(PSystemManager.Instance.localBodies[0], cb => cb.orbitingBodies, cb =>
            {
                trackingstation.Add(PlanetariumCamera.fetch.targets.Find(t => t.celestialBody == cb));
            });
            PlanetariumCamera.fetch.targets.Clear();
            PlanetariumCamera.fetch.targets.AddRange(trackingstation);

            // Update the initialTarget of the tracking station
            Resources.FindObjectsOfTypeAll <PlanetariumCamera>().FirstOrDefault().initialTarget = Resources.FindObjectsOfTypeAll <ScaledMovement>().FirstOrDefault(o => o.celestialBody.isHomeWorld);

            // Undo stuff
            foreach (CelestialBody b in PSystemManager.Instance.localBodies.Where(b_ => b_.Has("orbitPatches")))
            {
                fixes[b.transform.name].Value.orbitingBodies.Remove(b);
                fixes[b.transform.name].Key.orbitingBodies.Add(b);
                fixes[b.transform.name].Key.orbitingBodies = fixes[b.transform.name].Key.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
            }


            #if !KSP131
            if (ExpansionsLoader.IsExpansionInstalled("MakingHistory"))
            {
                PQSCity2[] cities = FindObjectsOfType <PQSCity2>();
                foreach (String site in Templates.RemoveLaunchSites)
                {
                    // Remove the launch site from the list if it exists
                    if (PSystemSetup.Instance.LaunchSites.Any(s => s.name == site))
                    {
                        PSystemSetup.Instance.RemoveLaunchSite(site);
                    }

                    PQSCity2 city = cities.FirstOrDefault(c =>
                                                          c.gameObject.name == site || c.gameObject.name == site + "(Clone)");

                    // Kill the PQSCity if it exists
                    if (city != null)
                    {
                        Destroy(city.gameObject);
                    }
                }
                // PSystemSetup.RemoveLaunchSite does not remove launch sites from PSystemSetup.StockLaunchSites
                // Currently an ArgumentOutOfRangeException can result when they are different lists because of a bug in stock code
                try
                {
                    FieldInfo    stockLaunchSitesField  = typeof(PSystemSetup).GetField("stocklaunchsites", BindingFlags.NonPublic | BindingFlags.Instance);
                    LaunchSite[] stockLaunchSites       = (LaunchSite[])stockLaunchSitesField.GetValue(PSystemSetup.Instance);
                    LaunchSite[] updateStockLaunchSites = stockLaunchSites.Where(site => !Templates.RemoveLaunchSites.Contains(site.name)).ToArray();
                    if (stockLaunchSites.Length != updateStockLaunchSites.Length)
                    {
                        stockLaunchSitesField.SetValue(PSystemSetup.Instance, updateStockLaunchSites);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Default.Log("Failed to remove launch sites from 'stockLaunchSites' field. Exception information follows.");
                    Logger.Default.LogException(ex);
                }
            }
            #endif
#if FALSE
            // AFG-Ception
            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                if (body.afg == null)
                {
                    continue;
                }

                foreach (KopernicusStar s in KopernicusStar.Stars)
                {
                    AtmosphereFromGround afg;
                    if (s != Sun.Instance)
                    {
                        afg = Instantiate(body.afg.gameObject)
                              .GetComponent <AtmosphereFromGround>();
                        Utility.CopyObjectFields(body.afg, afg, false);
                        afg.transform.parent        = body.afg.transform.parent;
                        afg.transform.localPosition = body.afg.transform.localPosition;
                        afg.transform.localScale    = body.afg.transform.localScale;
                        afg.transform.localRotation = body.afg.transform.localRotation;
                        afg.gameObject.layer        = body.afg.gameObject.layer;
                    }
                    else
                    {
                        afg = body.afg;
                    }

                    afg.gameObject.AddComponent <KopernicusStarAFG>().Star = s;
                }
            }
#endif
        }
Example #11
0
        // Execute MainMenu functions
        void Start()
        {
            previous = PlanetariumCamera.fetch.initialTarget;
            PlanetariumCamera.fetch.targets
            .Where(m => m.celestialBody != null && (m.celestialBody.Has("barycenter") || !m.celestialBody.Get("selectable", true)))
            .ToList()
            .ForEach(map => PlanetariumCamera.fetch.targets.Remove(map));

            // Stars
            GameObject     gob  = Sun.Instance.gameObject;
            KopernicusStar star = gob.AddComponent <KopernicusStar>();

            Utility.CopyObjectFields(Sun.Instance, star, false);
            DestroyImmediate(Sun.Instance);
            Sun.Instance = star;

            // LensFlares
            gob = SunFlare.Instance.gameObject;
            KopernicusSunFlare flare = gob.AddComponent <KopernicusSunFlare>();

            gob.name = star.sun.name;
            Utility.CopyObjectFields(SunFlare.Instance, flare, false);
            DestroyImmediate(SunFlare.Instance);
            SunFlare.Instance = star.lensFlare = flare;

            // Bodies
            Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> > fixes = new Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> >();

            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                // More stars
                if (body.flightGlobalsIndex != 0 && body.scaledBody.GetComponentsInChildren <SunShaderController>(true).Length > 0)
                {
                    GameObject starObj = Instantiate(Sun.Instance.gameObject);
                    star     = starObj.GetComponent <KopernicusStar>();
                    star.sun = body;
                    starObj.transform.parent        = Sun.Instance.transform.parent;
                    starObj.name                    = body.name;
                    starObj.transform.localPosition = Vector3.zero;
                    starObj.transform.localRotation = Quaternion.identity;
                    starObj.transform.localScale    = Vector3.one;
                    starObj.transform.position      = body.position;
                    starObj.transform.rotation      = body.rotation;

                    GameObject flareObj = Instantiate(SunFlare.Instance.gameObject);
                    flare                            = flareObj.GetComponent <KopernicusSunFlare>();
                    star.lensFlare                   = flare;
                    flareObj.transform.parent        = SunFlare.Instance.transform.parent;
                    flareObj.name                    = body.name;
                    flareObj.transform.localPosition = Vector3.zero;
                    flareObj.transform.localRotation = Quaternion.identity;
                    flareObj.transform.localScale    = Vector3.one;
                    flareObj.transform.position      = body.position;
                    flareObj.transform.rotation      = body.rotation;
                }

                // Post spawn patcher
                if (body.Has("orbitPatches"))
                {
                    ConfigNode  orbitNode = body.Get <ConfigNode>("orbitPatches");
                    OrbitLoader loader    = new OrbitLoader(body);
                    Parser.LoadObjectFromConfigurationNode(loader, orbitNode, "Kopernicus");
                    CelestialBody oldRef = body.referenceBody;
                    body.referenceBody.orbitingBodies.Remove(body);

                    CelestialBody newRef = PSystemManager.Instance.localBodies.FirstOrDefault(b => b.transform.name == loader.referenceBody);
                    if (newRef != null)
                    {
                        body.orbit.referenceBody = body.orbitDriver.referenceBody = newRef;
                    }
                    else
                    {
                        // Log the exception
                        Debug.Log("Exception: PostSpawnOrbit reference body for \"" + body.name + "\" could not be found. Missing body name is \"" + loader.referenceBody + "\".");

                        // Open the Warning popup
                        Injector.DisplayWarning();
                    }

                    fixes.Add(body.transform.name, new KeyValuePair <CelestialBody, CelestialBody>(oldRef, body.referenceBody));
                    body.referenceBody.orbitingBodies.Add(body);
                    body.referenceBody.orbitingBodies = body.referenceBody.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
                    body.orbit.Init();
                    body.orbitDriver.UpdateOrbit();

                    // Calculations
                    if (!body.Has("sphereOfInfluence"))
                    {
                        body.sphereOfInfluence = body.orbit.semiMajorAxis * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.4);
                    }
                    if (!body.Has("hillSphere"))
                    {
                        body.hillSphere = body.orbit.semiMajorAxis * (1 - body.orbit.eccentricity) * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.333333333333333);
                    }
                    if (body.solarRotationPeriod)
                    {
                        Double rotPeriod = Utility.FindBody(PSystemManager.Instance.systemPrefab.rootBody, body.transform.name).celestialBody.rotationPeriod;
                        Double num1      = Math.PI * 2 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
                        body.rotationPeriod = rotPeriod * num1 / (num1 + rotPeriod);;
                    }
                }
            }

            // Update the order in the tracking station
            List <MapObject> trackingstation = new List <MapObject>();

            Utility.DoRecursive(PSystemManager.Instance.localBodies[0], cb => cb.orbitingBodies, cb =>
            {
                trackingstation.Add(PlanetariumCamera.fetch.targets.Find(t => t.celestialBody == cb));
            });
            PlanetariumCamera.fetch.targets.Clear();
            PlanetariumCamera.fetch.targets.AddRange(trackingstation);

            // Update the initialTarget of the tracking station
            Resources.FindObjectsOfTypeAll <PlanetariumCamera>().FirstOrDefault().initialTarget = Resources.FindObjectsOfTypeAll <ScaledMovement>().FirstOrDefault(o => o.celestialBody.isHomeWorld);

            // Undo stuff
            foreach (CelestialBody b in PSystemManager.Instance.localBodies.Where(b_ => b_.Has("orbitPatches")))
            {
                fixes[b.transform.name].Value.orbitingBodies.Remove(b);
                fixes[b.transform.name].Key.orbitingBodies.Add(b);
                fixes[b.transform.name].Key.orbitingBodies = fixes[b.transform.name].Key.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
            }
#if FALSE
            // AFG-Ception
            foreach (CelestialBody body in PSystemManager.Instance.localBodies)
            {
                if (body.afg == null)
                {
                    continue;
                }

                foreach (KopernicusStar s in KopernicusStar.Stars)
                {
                    AtmosphereFromGround afg;
                    if (s != Sun.Instance)
                    {
                        afg = Instantiate(body.afg.gameObject)
                              .GetComponent <AtmosphereFromGround>();
                        Utility.CopyObjectFields(body.afg, afg, false);
                        afg.transform.parent        = body.afg.transform.parent;
                        afg.transform.localPosition = body.afg.transform.localPosition;
                        afg.transform.localScale    = body.afg.transform.localScale;
                        afg.transform.localRotation = body.afg.transform.localRotation;
                        afg.gameObject.layer        = body.afg.gameObject.layer;
                    }
                    else
                    {
                        afg = body.afg;
                    }

                    afg.gameObject.AddComponent <KopernicusStarAFG>().Star = s;
                }
            }
#endif
        }
Example #12
0
        // Awake() - flag this class as don't destroy on load and register delegates
        void Awake()
        {
            // Don't run if Kopernicus isn't compatible
            if (!CompatibilityChecker.IsCompatible())
            {
                Destroy(this);
                return;
            }

            // Make sure the runtime utility isn't killed
            DontDestroyOnLoad(this);

            // Add handlers
            GameEvents.onPartUnpack.Add(OnPartUnpack);
            GameEvents.onLevelWasLoaded.Add(FixCameras);
            GameEvents.onLevelWasLoaded.Add(delegate(GameScenes scene)
            {
                if (HighLogic.LoadedSceneHasPlanetarium && MapView.fetch != null)
                {
                    MapView.fetch.max3DlineDrawDist = 20000f;
                }
                if (scene == GameScenes.MAINMENU)
                {
                    UpdateMenu();
                }
                if (scene == GameScenes.SPACECENTER)
                {
                    PatchFI();
                }
                foreach (CelestialBody body in PSystemManager.Instance.localBodies)
                {
                    GameObject star_ = KopernicusStar.GetNearest(body).gameObject;
                    if (body.afg != null)
                    {
                        body.afg.sunLight = star_;
                    }
                    if (body.scaledBody.GetComponent <MaterialSetDirection>() != null)
                    {
                        body.scaledBody.GetComponent <MaterialSetDirection>().target = star_.transform;
                    }
                    foreach (PQSMod_MaterialSetDirection msd in body.GetComponentsInChildren <PQSMod_MaterialSetDirection>(true))
                    {
                        msd.target = star_.transform;
                    }
                }
                foreach (TimeOfDayAnimation anim in Resources.FindObjectsOfTypeAll <TimeOfDayAnimation>())
                {
                    anim.target = KopernicusStar.GetNearest(FlightGlobals.GetHomeBody()).gameObject.transform;
                }
            });

            // Update Music Logic
            if (MusicLogic.fetch != null && FlightGlobals.fetch != null && FlightGlobals.GetHomeBody() != null)
            {
                MusicLogic.fetch.flightMusicSpaceAltitude = FlightGlobals.GetHomeBody().atmosphereDepth;
            }

            // Stars
            GameObject     gob  = Sun.Instance.gameObject;
            KopernicusStar star = gob.AddComponent <KopernicusStar>();

            Utility.CopyObjectFields(Sun.Instance, star, false);
            DestroyImmediate(Sun.Instance);
            Sun.Instance = star;

            // More stars
            foreach (CelestialBody body in PSystemManager.Instance.localBodies.Where(b => b.flightGlobalsIndex != 0 && b.scaledBody.GetComponentsInChildren <SunShaderController>(true).Length > 0))
            {
                GameObject     starObj = Instantiate(Sun.Instance.gameObject);
                KopernicusStar star_   = starObj.GetComponent <KopernicusStar>();
                star_.sun = body;
                starObj.transform.parent        = Sun.Instance.transform.parent;
                starObj.name                    = body.name;
                starObj.transform.localPosition = Vector3.zero;
                starObj.transform.localRotation = Quaternion.identity;
                starObj.transform.localScale    = Vector3.one;
                starObj.transform.position      = body.position;
                starObj.transform.rotation      = body.rotation;
            }

            // Log
            Logger.Default.Log("[Kopernicus]: RuntimeUtility Started");
            Logger.Default.Flush();
        }
 void GetTarget()
 {
     body   = PSystemManager.Instance.localBodies.Find(b => b.scaledBody.name == transform.parent.name);
     target = KopernicusStar.GetNearest(body).sun.scaledBody.transform;
 }
            /// <summary>
            /// Small method to handle flux
            /// </summary>
            public static void Flux(ModularFlightIntegrator fi, KopernicusStar star)
            {
                // Nullchecks
                if (fi.Vessel == null || fi.Vessel.state == Vessel.State.DEAD || fi.CurrentMainBody == null)
                {
                    return;
                }

                // Get sunVector
                RaycastHit raycastHit;
                fi.Vessel.directSunlight = false;
                Vector3d scaledSpace = ScaledSpace.LocalToScaledSpace(fi.IntegratorTransform.position);
                double scale = Math.Max((star.sun.scaledBody.transform.position - scaledSpace).magnitude, 1);
                Vector3 sunVector = (star.sun.scaledBody.transform.position - scaledSpace) / scale;
                Ray ray = new Ray(ScaledSpace.LocalToScaledSpace(fi.IntegratorTransform.position), sunVector);

                // Get Body flux
                fi.solarFlux = 0;
                fi.sunDot = Vector3d.Dot(fi.sunVector, fi.Vessel.upAxis);
                fi.CurrentMainBody.GetAtmoThermalStats(true, FlightIntegrator.sunBody, fi.sunVector, fi.sunDot, fi.Vessel.upAxis, fi.altitude, out fi.atmosphereTemperatureOffset, out fi.bodyEmissiveFlux, out fi.bodyAlbedoFlux);
                Vector3d scaleFactor = ((Vector3d)star.sun.scaledBody.transform.position - fi.CurrentMainBody.scaledBody.transform.position) * (double)ScaledSpace.ScaleFactor;

                // Get Solar Flux
                double realDistanceToSun = 0;
                if (!Physics.Raycast(ray, out raycastHit, Single.MaxValue, ModularFI.ModularFlightIntegrator.SunLayerMask))
                {
                    fi.Vessel.directSunlight = true;
                    realDistanceToSun = scale * ScaledSpace.ScaleFactor - star.sun.Radius;
                }
                else if (raycastHit.transform.GetComponent<ScaledMovement>().celestialBody == star.sun)
                {
                    realDistanceToSun = ScaledSpace.ScaleFactor * raycastHit.distance;
                    fi.Vessel.directSunlight = true;
                }
                if (fi.Vessel.directSunlight)
                {
                    fi.solarFlux = PhysicsGlobals.SolarLuminosity/(12.5663706143592*realDistanceToSun*realDistanceToSun);
                }
            }
            /// <summary>
            /// Small method to handle flux
            /// </summary>
            public static void Flux(ModularFlightIntegrator fi, KopernicusStar star)
            {
                // Nullchecks
                if (fi.Vessel == null || fi.Vessel.state == Vessel.State.DEAD || fi.CurrentMainBody == null)
                {
                    return;
                }

                // Get sunVector
                RaycastHit raycastHit;
                Vector3d scaledSpace = ScaledSpace.LocalToScaledSpace(fi.IntegratorTransform.position);
                double scale = Math.Max((star.sun.scaledBody.transform.position - scaledSpace).magnitude, 1);
                Vector3 sunVector = (star.sun.scaledBody.transform.position - scaledSpace) / scale;
                Ray ray = new Ray(ScaledSpace.LocalToScaledSpace(fi.IntegratorTransform.position), sunVector);

                // Get Body flux
                Vector3d scaleFactor = ((Vector3d)star.sun.scaledBody.transform.position - fi.CurrentMainBody.scaledBody.transform.position) * (double)ScaledSpace.ScaleFactor;
                fi.bodySunFlux = star.sunFlare == fi.CurrentMainBody ? 0 : PhysicsGlobals.SolarLuminosity / Math.PI * 4 * scaleFactor.sqrMagnitude;

                // Get Solar Flux
                double realDistanceToSun = 0;
                bool localDirectSunLight = false;
                if (!Physics.Raycast(ray, out raycastHit, Single.MaxValue, ModularFI.ModularFlightIntegrator.SunLayerMask))
                {
                    localDirectSunLight = true;
                    realDistanceToSun = scale * ScaledSpace.ScaleFactor - star.sun.Radius;
                }
                else if (raycastHit.transform.GetComponent<ScaledMovement>().celestialBody == star.sun)
                {
                    realDistanceToSun = ScaledSpace.ScaleFactor * raycastHit.distance;
                    localDirectSunLight = true;
                }
                if (localDirectSunLight)
                {
                    fi.solarFlux = PhysicsGlobals.SolarLuminosity/(12.5663706143592*realDistanceToSun*realDistanceToSun);
                    if (!fi.Vessel.directSunlight)
                        fi.Vessel.directSunlight = true;
                }
            }