コード例 #1
0
        public static void LoadConfig()
        {
            if (loaded)
            {
                return;
            }
            Log("Loading config...", LogLevel.Important);

            BodyTravelTimes = new Dictionary <CelestialBody, double>(FlightGlobals.Bodies.Count);
            CelestialBody homePlanet = GetPlanet(Planetarium.fetch.Home);

            foreach (CelestialBody body in FlightGlobals.Bodies)
            {
                if (body.isHomeWorld)
                {
                    BodyTravelTimes[body] = 0;
                }
                else if (body == Planetarium.fetch.Sun)
                {
                    BodyTravelTimes[body] = homePlanet.orbit.period;
                }
                else if (body.HasParent(homePlanet))
                {
                    BodyTravelTimes[body] = body.orbit.period / 5;
                }
                else
                {
                    BodyTravelTimes[body] = TimeBetweenLaunchWindows(homePlanet.orbit, GetPlanet(body).orbit) + HohmannMultiplier * HohmannTransferTime(homePlanet.orbit, GetPlanet(body).orbit);
                }
                Core.Log("Travel time for " + body.name + " is " + KSPUtil.PrintDateDeltaCompact(BodyTravelTimes[body], true, false), LogLevel.Important);
            }

            ConfigNode[] cfgArray = GameDatabase.Instance.GetConfigNodes("URGENT_CONTRACTS_CONFIG");
            foreach (ConfigNode cfg in cfgArray)
            {
                foreach (ConfigNode n in cfg.GetNodes("CONTRACT_RULE"))
                {
                    ContractRule rule = new ContractRule(n);
                    ContractRules.Add(rule);
                    Core.Log("Added contract from config file: " + rule, LogLevel.Important);
                }

                foreach (ConfigNode n in cfg.GetNodes("TRAVEL_TIME"))
                {
                    CelestialBody body = FlightGlobals.GetBodyByName(GetString(n, "Name"));
                    if (body == null)
                    {
                        continue;
                    }
                    BodyTravelTimes[body] = n.HasValue("TravelTime") ? GetDouble(n, "TravelTime") : (GetDouble(n, "TravelDays") * 21600);
                    Core.Log("Overriding travel time for " + body.name + " to be " + KSPUtil.PrintDateDeltaCompact(BodyTravelTimes[body], true, false), LogLevel.Important);
                }
            }
            if (cfgArray.Length == 0)
            {
                Core.Log("Config file not found!", LogLevel.Error);
            }

            loaded = true;
        }
        public SpaceDustTelescopeBackground(Vessel vessel,
                                            ProtoPartModuleSnapshot protoScope,
                                            PartModule prefabScope)
        {
            ves = vessel;
            protoTelescopeModule = protoScope;
            prefabScopeModule    = prefabScope;

            telescope = prefabScope as ModuleSpaceDustTelescope;


            bool.TryParse(protoTelescopeModule.moduleValues.GetValue("Enabled"), out Enabled);
            string tgtString = protoTelescopeModule.moduleValues.GetValue("Target");

            if (tgtString != "")
            {
                TargetBody = FlightGlobals.GetBodyByName(tgtString);
            }
            selectedInstruments = new List <SpaceDustInstrument>();
            foreach (ConfigNode c in protoTelescopeModule.moduleValues.GetNodes("SLOT"))
            {
                string instName = c.GetValue("Instrument");
                if (instName != "None")
                {
                    selectedInstruments.Add(SpaceDustInstruments.Instance.GetInstrument(instName));
                }
            }
        }
コード例 #3
0
 //public Collider DetermineCollider()
 //{
 //    if (p != null)
 //    {
 //        return p.collider;
 //    }
 //    else
 //    {
 //        Debug.Log("Part is null");
 //        return null;
 //
 //    }
 //    //if (p.gameObject.GetComponent<Collider>() != null)
 //    //{
 //    //    return p.gameObject.GetComponent<Collider>();
 //    //}
 //    //if (p.gameObject.GetComponent<MeshCollider>() != null)
 //    //{
 //    //    return p.gameObject.GetComponent<MeshCollider>();
 //    //}
 //    //if (p.gameObject.GetComponent<SphereCollider>() != null)
 //    //{
 //    //    return p.gameObject.GetComponent<SphereCollider>();
 //    //}
 //    //return null;
 //}
 //public void OnCollisionEnter(Collision collision)   //This object: WHEEL. Colliding object: PLANE
 //{
 //    Debug.Log("Collision!");
 //    if (collision.gameObject.name != plane.name && collision.gameObject.name.StartsWith("ParallaxPlane-"))
 //    {
 //        Debug.Log("Ignoring");
 //        Collider c = DetermineCollider();
 //        if (c != null)
 //        {
 //            Physics.IgnoreCollision(collision.collider, c);
 //        }
 //        else
 //        {
 //            Debug.Log("c is null");
 //        }
 //
 //
 //    }
 //    Debug.Log("Finished colliding - ignored");
 //}
 void Start()
 {
     if (FlightGlobals.currentMainBody == FlightGlobals.GetBodyByName("Minmus") && ParallaxSettings.flatMinmus == true)
     {
         return;
     }
     Debug.Log("Starting physics!");
     //float dist = gameObject.GetColliderBounds().size.y; //We need to make the plane start below the wheel
     plane       = GameObject.CreatePrimitive(PrimitiveType.Cube);
     plane.layer = 15;                                        //Set initial layer such that raycast ignores the plane
     plane.SetActive(true);
     plane.transform.localScale    = new Vector3(0.6f, 1f, 0.6f);
     plane.transform.rotation      = Quaternion.Euler(0f, 0f, 0f);
     plane.transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
     plane.transform.localPosition = Vector3.zero;
     plane.transform.position      = new Vector3(1000, 1000, 1000);// gameObject.transform.position;
     plane.GetComponent <MeshRenderer>().enabled = false;
     plane.GetComponent <Collider>().isTrigger   = false;
     plane.GetComponent <Collider>().enabled     = false;
     plane.tag  = FlightGlobals.currentMainBody.BiomeMap.GetAtt(FlightGlobals.ActiveVessel.latitude * UtilMath.Deg2Rad, FlightGlobals.ActiveVessel.longitude * UtilMath.Deg2Rad).name;
     plane.name = "ParallaxPlane-" + PhysicsValidator.planeCount.ToString();
     PhysicsValidator.planeCount++;
     //Vector3 meshbounds = gameObject.GetComponent<MeshFilter>().mesh.bounds.size;
     //bounds = Mathf.Max(meshbounds.x, meshbounds.y, meshbounds.z);
     //plane.transform.localScale = new Vector3(bounds / 4, 0.01f, bounds / 4);
     PhysicsValidator.planes.Add(plane, false);
 }
コード例 #4
0
        private void BuildHomes()
        {
            ConfigNode KopernicusNode = null;

            foreach (ConfigNode n in GameDatabase.Instance.GetConfigNodes("Kopernicus"))
            {
                KopernicusNode = n;
            }

            if (KopernicusNode != null)
            {
                foreach (ConfigNode bodyNode in KopernicusNode.GetNodes("Body"))
                {
                    string t    = bodyNode.GetValue("name");
                    string name = t.Equals("Kerbin") ? FlightGlobals.GetHomeBodyName() : t;

                    if (FlightGlobals.GetBodyByName(name) is CelestialBody body &&
                        bodyNode.GetNode("PQS") is ConfigNode pqsNode &&
                        pqsNode.GetNode("Mods") is ConfigNode pqsModNode)
                    {
                        foreach (ConfigNode cityNode in pqsModNode.GetNodes("City2"))
                        {
                            bool result = false;
                            if (cityNode.TryGetValue("RACommNetStation", ref result) && result)
                            {
                                BuildHome(cityNode, body);
                            }
                        }
                    }
                }
            }
        }
コード例 #5
0
        private void CalculateRates()
        {
            double currentPeMeters, currentApMeters, theOrbit = 0.0;

            ModuleDeployableSolarPanel pm = part.Modules.GetModule <ModuleDeployableSolarPanel>();
            float timeEfficEvaluated      = pm.timeEfficCurve.Evaluate(daysElapsed);

            solarEfficiency = timeEfficEvaluated * 100;
            double currentOutput = pm.chargeRate * timeEfficEvaluated;

            if (HighLogic.LoadedSceneIsEditor)
            {
                currentPeMeters = _getAU(FlightGlobals.GetBodyByName(selectedBody).orbit.PeA);
                currentApMeters = _getAU(FlightGlobals.GetBodyByName(selectedBody).orbit.ApA);
                solarOutputPe   = Math.Round(_getModifier(currentPeMeters) * currentOutput * 1000, 2).ToString() + " Watts";
                solarOutputAp   = Math.Round(_getModifier(currentApMeters) * currentOutput * 1000, 2).ToString() + " Watts";

                //solarOutputPe = currentPe.ToString() + " Watts";
                //solarOutputAp = currentAp.ToString() + " Watts";
            }

            if (HighLogic.LoadedSceneIsFlight)
            {
                double mod = _getModifier(currentOrbit);
                theOrbit     = Math.Round(mod * currentOutput * 1000, 2);
                futureOutput = theOrbit.ToString() + " Watts";
            }
        }
コード例 #6
0
 public GUIOrbitEditor(MissionProfile missionProfile)
 {
     this.body = FlightGlobals.GetBodyByName(missionProfile.bodyName);
     if (this.body == null)  // in case this flight was registered on a now-invalid body
     {
         this.body = FlightGlobals.GetHomeBody();
     }
     this.missionProfile = missionProfile;
     Reset();
 }
コード例 #7
0
        public Orbit GetOrbit()
        {
            CelestialBody returnBody = FlightGlobals.GetBodyByName(celestialBody);

            if (returnBody == null)
            {
                return(null);
            }
            return(new Orbit(inclination, eccentricity, semiMajorAxis, LAN, argumentOfPeriapsis, meanAnomalyAtEpoch, t, returnBody));
        }
コード例 #8
0
 public override void Load(ConfigNode node)
 {
     base.Load(node);
     ConfigNode.LoadObjectFromConfig(this, node);
     body = FlightGlobals.GetBodyByName(bodyName);
     if (body is CelestialBody)
     {
         transform.SetParent(body.transform);
         transform.localPosition = body.GetRelSurfacePosition(latLonAlt.x, latLonAlt.y, latLonAlt.z);
         transform.localRotation = Quaternion.identity;
     }
 }
コード例 #9
0
        public void FixedUpdate()
        {
            if (!enable)
            {
                return;
            }
            //We only do this every one week of elapsed game time.
            double currentTime = Planetarium.GetUniversalTime();

            if (currentTime - ResearchBodies.Instance.RBgameSettings.lastTimeCheckedSOIs > oneWeek)
            {
                List <string> itemsToRemove = new List <string>();
                var           dictEnum      = Database.instance.VesselsInSOI.GetEnumerator();
                while (dictEnum.MoveNext())
                {
                    var           entry = dictEnum.Current;
                    CelestialBody body  = FlightGlobals.GetBodyByName(entry.Key);
                    if (body == null)
                    {
                        itemsToRemove.Add(entry.Key);
                        continue;
                    }
                    if (Database.instance.CelestialBodies[body].researchState >= 100)
                    {
                        itemsToRemove.Add(entry.Key);
                        continue;
                    }

                    for (int i = 0; i < entry.Value.vesselSOIInfo.Count; i++)
                    {
                        if (currentTime - entry.Value.vesselSOIInfo[i].timeEnteredSoi > oneMonth)
                        {
                            int level      = Mathf.RoundToInt(ScenarioUpgradeableFacilities.GetFacilityLevel("Observatory") + 1);
                            int percentage = lvl1InSoiPercentage;
                            if (level == 2)
                            {
                                percentage = lvl2InSoiPercentage;
                            }

                            Research(body, percentage);
                            entry.Value.SetVesselTimes(currentTime);
                        }
                    }
                }
                dictEnum.Dispose();

                for (int i = 0; i < itemsToRemove.Count; i++)
                {
                    Database.instance.VesselsInSOI.Remove(itemsToRemove[i]);
                }
                ResearchBodies.Instance.RBgameSettings.lastTimeCheckedSOIs = currentTime;
            }
        }
コード例 #10
0
        private void CalculateRates()
        {
            ModuleDeployableSolarPanel pm = part.Modules.GetModule <ModuleDeployableSolarPanel>();
            float timeEfficEvaluated      = pm.timeEfficCurve.Evaluate(daysElapsed);

            solarEfficiency = timeEfficEvaluated * 100;
            float currentOutputW = pm.chargeRate * timeEfficEvaluated * 1000;

            float currentPeAU = ConvertToAU(FlightGlobals.GetBodyByName(selectedBody).orbit.PeA);
            float currentApAU = ConvertToAU(FlightGlobals.GetBodyByName(selectedBody).orbit.ApA);

            solarOutputPe = DistanceScaling(currentPeAU) * currentOutputW;
            solarOutputAp = DistanceScaling(currentApAU) * currentOutputW;
        }
コード例 #11
0
ファイル: SunLight.cs プロジェクト: Mecripp/CrewLight
        private bool IsSunShine()
        {
            Vector3d   vesselPos = vessel.GetWorldPos3D();
            Vector3d   sunPos    = FlightGlobals.GetBodyByName("Sun").position;
            RaycastHit hit;

            if (Physics.Raycast(vesselPos, sunPos, out hit, Mathf.Infinity, CLSettings.layerMask))
            {
                if (hit.transform.name == "Sun")
                {
                    return(true);
                }
            }
            return(false);
        }
コード例 #12
0
        /// <summary>
        /// Builds a ScaledObject
        /// </summary>
        internal void Build()
        {
            Debug.Log("[INSTANTIATOR_ScaledObject]: Building object [" + name + "].");
            CelestialBody targetBody = FlightGlobals.GetBodyByName(body);
            GameObject    obj        = GameObject.CreatePrimitive(PrimitiveType.Cube);

            if (type == "Billboard")
            {
                obj.transform.SetParent(targetBody.scaledBody.GetComponentInChildren <SunCoronas>().transform);
                obj.transform.localPosition = Vector3.zero;
                obj.transform.localScale    = scale;
                obj.GetComponent <Renderer>().material.shader = shader;
                obj.GetComponent <Renderer>().material.SetTexture("_MainTex", tex);
                obj.layer = targetBody.scaledBody.layer;
                obj.name  = name;
            }
            else
            {
                obj.transform.SetParent(targetBody.scaledBody.transform);
                if (type == "Sphere")
                {
                    obj.GetComponent <MeshFilter>().mesh = FlightGlobals.GetBodyByName("Sun").scaledBody.GetComponentInChildren <MeshFilter>().mesh;
                }
                obj.GetComponent <MeshFilter>().mesh.RecalculateBounds();
                obj.GetComponent <MeshFilter>().mesh.RecalculateNormals();
                obj.transform.localPosition = Vector3.zero;
                obj.transform.localScale    = scale;
                obj.GetComponent <Renderer>().material.shader = shader;
                obj.GetComponent <Renderer>().material.SetTexture("_MainTex", tex);
                obj.transform.rotation = rotation;
                if (ignoreLight)
                {
                    obj.layer = 9;
                }
                else
                {
                    obj.layer = 10;
                }
                obj.name = name;
                if (invertNormals)
                {
                    InvertNormals(obj.GetComponent <MeshFilter>());
                }
            }
        }
コード例 #13
0
        private void ApplyOrbit(OrbitalData orbitData)
        {
            Vessel updateVessel = FlightGlobals.ActiveVessel;

            updateVessel.GoOnRails();
            CelestialBody updateBody = FlightGlobals.GetBodyByName(orbitData.celestialBody);

            Orbit updateOrbit = orbitData.GetOrbit();

            updateOrbit.Init();
            updateOrbit.UpdateFromUT(Planetarium.GetUniversalTime());

            //Positional Error Tracking
            double latitude  = updateBody.GetLatitude(updateOrbit.pos);
            double longitude = updateBody.GetLongitude(updateOrbit.pos);
            double altitude  = updateBody.GetAltitude(updateOrbit.pos);

            updateVessel.latitude              = latitude;
            updateVessel.longitude             = longitude;
            updateVessel.altitude              = altitude;
            updateVessel.protoVessel.latitude  = latitude;
            updateVessel.protoVessel.longitude = longitude;
            updateVessel.protoVessel.altitude  = altitude;
            VesselUtil.CopyOrbit(updateOrbit, updateVessel.orbitDriver.orbit);
            updateVessel.orbitDriver.updateFromParameters();

            /*
             * if (!updateVessel.packed)
             * {
             *  var fudgeVel = updateBody.inverseRotation ? updateBody.getRFrmVelOrbit(updateVessel.orbitDriver.orbit) : Vector3d.zero;
             *  updateVessel.SetWorldVelocity(updateVessel.orbitDriver.orbit.vel.xzy - fudgeVel - Krakensbane.GetFrameVelocity());
             * }
             */

            updateVessel.SetRotation(updateVessel.mainBody.bodyTransform.rotation * orbitData.rot);
            if (updateVessel.packed)
            {
                updateVessel.srfRelRotation       = orbitData.rot;
                updateVessel.protoVessel.rotation = updateVessel.srfRelRotation;
            }
        }
コード例 #14
0
        /// <summary>
        /// Finds every last planet in every star system.
        /// </summary>
        /// <returns>A List of CelestialBody</returns>
        public List <CelestialBody> GetEveryLastPlanet()
        {
            if (lastPlanets.Count > 0)
            {
                return(lastPlanets);
            }
            if (stars.Count == 0)
            {
                GetStars();
            }

            int           count = stars.Count;
            CelestialBody body;

            for (int index = 0; index < count; index++)
            {
                // Check for override first.
                if (lastPlanetOverrides.ContainsKey(stars[index].bodyName))
                {
                    body = FlightGlobals.GetBodyByName(stars[index].bodyName);
                    if (body != null)
                    {
                        lastPlanets.Add(body);
                        lastPlanetByStar.Add(stars[index], body);
                    }
                }

                // Try to figure it out based on distance.
                body = getLastPlanet(stars[index]);
                if (body != null)
                {
                    lastPlanets.Add(body);
                    lastPlanetByStar.Add(stars[index], body);
                }
            }

            return(lastPlanets);
        }
コード例 #15
0
        public void IdentifyResourceBand(string resourceName, ResourceBand band, string bodyName)
        {
            if (!IsIdentified(resourceName, band.name, bodyName))
            {
                List <SpaceDustDiscoveryData> toIdentify = distributionData.FindAll(x =>
                                                                                    (x.ResourceName == resourceName) &&
                                                                                    (x.BandName == band.name) &&
                                                                                    (x.BodyName == bodyName));

                if (toIdentify == null || toIdentify.Count == 0)
                {
                    distributionData.Add(new SpaceDustDiscoveryData(resourceName, band.name, bodyName, true, true));
                }
                else
                {
                    foreach (SpaceDustDiscoveryData data in toIdentify)
                    {
                        data.Discovered       = true;
                        data.discoveryPercent = 100;
                        data.Identified       = true;
                        data.identifyPercent  = 100;
                    }
                }
                if (HighLogic.LoadedSceneIsFlight)
                {
                    ScreenMessage msg = new ScreenMessage(Localizer.Format("#LOC_SpaceDust_Message_Identified", resourceName, bodyName), 5f, ScreenMessageStyle.UPPER_CENTER);
                    ScreenMessages.PostScreenMessage(msg);
                }
                Utils.Log($"[SpaceDustScenario]: Identified {resourceName} in {band.name} at {bodyName}");
                if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER || HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
                {
                    float scienceValue = FlightGlobals.GetBodyByName(bodyName).scienceValues.InSpaceHighDataValue *band.identifyScienceReward;
                    Utils.Log($"[SpaceDustScenario]: Added {scienceValue} science because  {band.name} at {bodyName} was identified");

                    ResearchAndDevelopment.Instance.AddScience(scienceValue, TransactionReasons.ScienceTransmission);
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Load a planned node from a config node from the save file
        /// </summary>
        /// <param name="cfg">ConfigNode to load from</param>
        public PlanningNodeModel(ConfigNode cfg)
        {
            string bodyName = "";

            if (cfg.TryGetValue("origin", ref bodyName))
            {
                origin = FlightGlobals.GetBodyByName(bodyName);
            }
            cfg.TryGetValue("name", ref name);
            cfg.TryGetValue("burnTime", ref burnTime);
            cfg.TryGetValue("deltaV", ref deltaV);
            if (!cfg.TryGetValue("color", ref color))
            {
                // No saved color, pick one randomly
                color = GetBodyColor(null);
            }
            uint vesId = 0;

            if (cfg.TryGetValue("vessel", ref vesId))
            {
                vesselId = vesId;
            }
        }
コード例 #17
0
        private void BuildHomes()
        {
            ConfigNode KopernicusNode = null;

            foreach (ConfigNode n in GameDatabase.Instance.GetConfigNodes("Kopernicus"))
            {
                KopernicusNode = n;
            }

            if (KopernicusNode != null)
            {
                var sb = StringBuilderCache.Acquire();
                sb.Append($"{ModTag} Building homes: ");
                foreach (ConfigNode bodyNode in KopernicusNode.GetNodes("Body"))
                {
                    string t    = bodyNode.GetValue("name");
                    string name = t.Equals("Kerbin") ? FlightGlobals.GetHomeBodyName() : t;

                    if (FlightGlobals.GetBodyByName(name) is CelestialBody body &&
                        bodyNode.GetNode("PQS") is ConfigNode pqsNode &&
                        pqsNode.GetNode("Mods") is ConfigNode pqsModNode)
                    {
                        foreach (ConfigNode cityNode in pqsModNode.GetNodes("City2"))
                        {
                            bool result = false;
                            if (cityNode.TryGetValue("RACommNetStation", ref result) && result)
                            {
                                CommNetHome h = BuildHome(cityNode, body);
                                sb.Append($"{h.nodeName}  ");
                            }
                        }
                    }
                }
                Debug.Log(sb.ToStringAndRelease());
            }
        }
コード例 #18
0
        private void SunLightEVA(Vessel vessel, KerbalEVA kerbal)
        {
            if (CLSettings.onForEVASpace && (vessel.situation == Vessel.Situations.ESCAPING ||
                                             vessel.situation == Vessel.Situations.FLYING ||
                                             vessel.situation == Vessel.Situations.ORBITING ||
                                             vessel.situation == Vessel.Situations.SUB_ORBITAL))
            {
                kerbal.lampOn = true;
                return;
            }
            if (CLSettings.onForEVALanded && (vessel.situation == Vessel.Situations.LANDED ||
                                              vessel.situation == Vessel.Situations.PRELAUNCH ||
                                              vessel.situation == Vessel.Situations.SPLASHED))
            {
                kerbal.lampOn = true;
                return;
            }

            bool       isSunShine = false;
            RaycastHit hit;
            Vector3d   vesselPos = vessel.GetWorldPos3D();
            Vector3d   sunPos    = FlightGlobals.GetBodyByName("Sun").position;

            if (Physics.Raycast(vesselPos, sunPos, out hit, Mathf.Infinity, CLSettings.layerMask))
            {
                if (hit.transform.name == "Sun")
                {
                    isSunShine = true;
                }
            }

            if (!isSunShine)
            {
                kerbal.lampOn = true;
            }
        }
コード例 #19
0
ファイル: Core.cs プロジェクト: GarwelGarwel/SpaceAge
 public static string GetBodyDisplayName(string bodyName) =>
 bodyName != null ? (FlightGlobals.GetBodyByName(bodyName)?.displayName ?? bodyName) : bodyName;
コード例 #20
0
        void Awake()
        {
            foreach (ConfigNode city in GameDatabase.Instance.GetConfigNodes("CITY"))
            {
                // check for a name, we need one
                if (!city.HasValue("name"))
                {
                    continue;
                }

                // create the new city
                GameObject cityObject = new GameObject();
                cityObject.name = city.GetValue("name");
                PQSCity2 pqsCity = cityObject.AddComponent <PQSCity2>();
                pqsCity.objectName = cityObject.name;

                // read and set values, using defaults when none are defined
                if (city.HasValue("verticalOffset"))
                {
                    pqsCity.alt = double.Parse(city.GetValue("verticalOffset"));
                    pqsCity.snapHeightOffset = double.Parse(city.GetValue("verticalOffset"));
                }
                CelestialBody body = FlightGlobals.GetHomeBody();
                if (city.HasValue("body"))
                {
                    body = FlightGlobals.GetBodyByName(city.GetValue("body"));
                }
                pqsCity.sphere = body.pqsController;
                if (city.HasValue("lat"))
                {
                    pqsCity.lat = double.Parse(city.GetValue("lat"));
                }
                if (city.HasValue("lon"))
                {
                    pqsCity.lon = double.Parse(city.GetValue("lon"));
                }
                if (city.HasValue("rotation"))
                {
                    pqsCity.rotation = double.Parse(city.GetValue("rotation"));
                }
                if (city.HasValue("snapToSurface"))
                {
                    pqsCity.snapToSurface = city.GetValue("snapToSurface").Equals("true", StringComparison.OrdinalIgnoreCase);
                }
                if (city.HasValue("displayName"))
                {
                    pqsCity.displayobjectName = city.GetValue("displayName");
                }
                else
                {
                    pqsCity.displayobjectName = cityObject.name;
                }

                // all the subnodes
                ConfigNode[] lods           = city.GetNodes("LOD");
                String[]     flagTransforms = city.GetValues("flagTransform");
                ConfigNode[] launchSites    = city.GetNodes("LAUNCHSITE");

                // load the LODs and models
                List <PQSCity2.LodObject> lodObjects = new List <PQSCity2.LodObject>();
                foreach (ConfigNode lod in lods)
                {
                    // create a new LodObject
                    PQSCity2.LodObject lodObject = new PQSCity2.LodObject();

                    // define the distance to stop rendering
                    if (lod.HasValue("visibleRange"))
                    {
                        lodObject.visibleRange = float.Parse(lod.GetValue("visibleRange"));
                    }
                    else
                    {
                        lodObject.visibleRange = 25000;
                    }

                    // read the models attached to this LOD
                    ConfigNode[]      models  = lod.GetNodes("MODEL");
                    List <GameObject> objects = new List <GameObject>();
                    foreach (ConfigNode model in models)
                    {
                        // make sure the model exists
                        if (!model.HasValue("model") | !GameDatabase.Instance.ExistsModel(model.GetValue("model")))
                        {
                            continue;
                        }

                        // get an instance of the model
                        GameObject modelInstance = GameDatabase.Instance.GetModel(model.GetValue("model"));

                        // attach it to the city
                        modelInstance.transform.parent = cityObject.transform;

                        // set the transform values if defined
                        if (model.HasValue("position"))
                        {
                            modelInstance.transform.localPosition = ConfigNode.ParseVector3(model.GetValue("position"));
                        }
                        if (model.HasValue("rotation"))
                        {
                            modelInstance.transform.localEulerAngles = ConfigNode.ParseVector3(model.GetValue("rotation"));
                        }
                        if (model.HasValue("scale"))
                        {
                            modelInstance.transform.localScale = ConfigNode.ParseVector3(model.GetValue("scale"));
                        }

                        // move to the local scenery layer
                        modelInstance.SetLayerRecursive(15);

                        // add the model to the list
                        //objects.Add(modelInstance);
                        modelInstance.SetActive(true);

                        // force all colliders to be concave
                        MeshCollider[] mColliders = modelInstance.GetComponentsInChildren <MeshCollider>(true);
                        foreach (MeshCollider collider in mColliders)
                        {
                            collider.convex = false;
                        }
                    }

                    // add the object list to the lodObject
                    lodObject.objects = objects.ToArray();

                    // add the lodObject to the lodObject list
                    lodObjects.Add(lodObject);
                }

                // add the LODs to the PQSCity
                pqsCity.objects = lodObjects.ToArray();

                // set the flag transforms
                if (flagTransforms.Length != 0)
                {
                    // add the flag handler component
                    CityFlag cityFlag = cityObject.AddComponent <CityFlag>();

                    // add each transform to the handler
                    foreach (string flagTransform in flagTransforms)
                    {
                        cityFlag.flagObjects.Add(CityUtils.FindChild(flagTransform, cityObject));
                    }
                }

                // finalize the PQSCity
                cityObject.transform.parent = body.pqsController.transform;
                pqsCity.Orientate();

                // add a CommNet antenna if defined
                if (city.HasNode("COMMNET"))
                {
                    // reference the confignode for future reference
                    ConfigNode commNet = city.GetNode("COMMNET");

                    // create the CommNetHome
                    CommNet.CommNetHome cNetHome = cityObject.AddComponent <CommNet.CommNetHome>();

                    // set the internal name
                    cNetHome.nodeName = cityObject.name;

                    // get the values from the config
                    if (commNet.HasValue("nodeName"))
                    {
                        cNetHome.displaynodeName = commNet.GetValue("nodeName");
                    }
                    else
                    {
                        cNetHome.displaynodeName = pqsCity.displayobjectName;
                    }
                    if (commNet.HasValue("antennaPower"))
                    {
                        cNetHome.antennaPower = double.Parse(commNet.GetValue("antennaPower"));
                    }
                    if (commNet.HasValue("isKSC"))
                    {
                        cNetHome.isKSC = commNet.GetValue("isKSC").Equals("true", StringComparison.OrdinalIgnoreCase);
                    }
                    if (commNet.HasValue("isPermanent"))
                    {
                        cNetHome.isPermanent = commNet.GetValue("isPermanent").Equals("true", StringComparison.OrdinalIgnoreCase);
                    }
                    if (city.HasValue("commNetTransform"))
                    {
                        cNetHome.nodeTransform = CityUtils.FindChild(city.GetValue("commNetTransform"), cityObject).transform;
                    }
                    else
                    {
                        cNetHome.nodeTransform = cityObject.transform;
                    }
                }

                // setup the launch sites (Making History required)
                foreach (ConfigNode site in launchSites)
                {
                    // we need a name
                    if (!site.HasValue("name"))
                    {
                        continue;
                    }

                    // create the spawnpoint
                    LaunchSite.SpawnPoint spawnPoint = new LaunchSite.SpawnPoint();
                    spawnPoint.name = site.GetValue("name");

                    // select the facility
                    EditorFacility facility = EditorFacility.VAB;
                    if (site.HasValue("facility") && site.GetValue("facility") == "SPH")
                    {
                        facility = EditorFacility.SPH;
                    }

                    // find and reparent the spawnTransform
                    // reparenting is done to ensure that it works
                    Transform spawnTransform = CityUtils.FindChild(site.GetValue("transform"), cityObject).transform;
                    spawnTransform.SetParent(cityObject.transform);

                    // create the launchsite
                    LaunchSite launchSite = new LaunchSite(site.GetValue("name"), body.pqsController.name, site.GetValue("title"), new LaunchSite.SpawnPoint[] { spawnPoint }, cityObject.name + "/" + spawnTransform.name, facility);

                    // change the mapIcon
                    // todo: remove mapIcon
                    if (facility == EditorFacility.VAB)
                    {
                        launchSite.nodeType = KSP.UI.Screens.Mapview.MapNode.SiteType.LaunchSite;
                    }
                    else
                    {
                        launchSite.nodeType = KSP.UI.Screens.Mapview.MapNode.SiteType.Runway;
                    }

                    // finalize the LaunchSite
                    launchSite.Setup(pqsCity, new PQS[] { body.pqsController });
                    PSystemSetup.Instance.AddLaunchSite(launchSite);
                }
            }
        }
コード例 #21
0
        void Update()
        {
            if (FlightGlobals.currentMainBody == FlightGlobals.GetBodyByName("Minmus") && ParallaxSettings.flatMinmus == true)
            {
                DisablePlane();
                return;
            }
            CheckIfEnabled();
            if (wheelDeploy != null)
            {
                if ((wheelDeploy as ModuleWheelDeployment).deployedPosition == 1)
                {
                    if ((wheelDeploy as ModuleWheelDeployment).Position < 1)
                    {
                        wheelsHaveBeenRetracted = true;
                        DisablePlane();
                        return;
                    }
                }
                else if ((wheelDeploy as ModuleWheelDeployment).deployedPosition == 0)
                {
                    if ((wheelDeploy as ModuleWheelDeployment).Position > 0)
                    {
                        wheelsHaveBeenRetracted = true;
                        DisablePlane();
                        return;
                    }
                }
                if (wheelsHaveBeenRetracted == true)
                {
                    RestartWheels(p);
                    Debug.Log("Restarting after retract");
                    dampingFrames           = 0;
                    wheelsHaveBeenRetracted = false;
                }
            }

            if (wheelsHaveBeenRetracted == true)
            {
                DisablePlane();
                return;
            }

            if (TimeWarp.CurrentRate > 1 && TimeWarp.WarpMode == TimeWarp.Modes.HIGH)
            {
                wheelsHaveBeenInWarp = true;
                DisablePlane();
                return;
            }

            if ((wheelsHaveBeenInWarp == true && TimeWarp.CurrentRate == 1))
            {
                RestartWheels(p);
                dampingFrames        = dampingFrames - 10;
                wheelsHaveBeenInWarp = false;
                DisablePlane();
                return;
            }

            if (ParallaxOnDemandLoader.finishedMainLoad == false)
            {
                DisablePlane();
                return;
            }

            if (p.vessel.packed == true)  //Vessel is time warping so we don't need to do anything here
            {
                DisablePlane();
                packed  = true;
                started = true;
                return;
            }

            if (packed == true) //Vessel has finished time warping and needs re-initializing
            {
                DisablePlane();
                packed = false;
                Debug.Log("[Parallax Physics] Restarting after unpack...");
                Destroy(plane);
                Start();
            }

            //plane.layer = 0;    //Layer has to be set to 0 to avoid raycast on layer 15
            if (p == null)
            {
                DisablePlane();
                return;
            }

            if (wheelPivot == null)
            {
                DisablePlane();
                return;
            }

            if ((thisBody != FlightGlobals.currentMainBody.name) || started == false)    //Body change, reassign textures
            {
                if (ParallaxShaderLoader.parallaxBodies.ContainsKey(FlightGlobals.currentMainBody.name) == false)
                {
                    return;
                }
                Debug.Log("[Parallax Physics] Body changed! Getting new values...");
                Material a = ParallaxShaderLoader.parallaxBodies[FlightGlobals.currentMainBody.name].ParallaxBodyMaterial.ParallaxMaterial;
                tex                  = PhysicsTexHolder.displacementTex;
                normalLow            = PhysicsTexHolder.physicsTexLow;
                normalMid            = PhysicsTexHolder.physicsTexMid;
                normalHigh           = PhysicsTexHolder.physicsTexHigh;
                normalSteep          = PhysicsTexHolder.physicsTexSteep;
                _ST                  = (a.GetTextureScale("_SurfaceTexture"));
                blendLowStart        = a.GetFloat("_LowStart");
                blendLowEnd          = a.GetFloat("_LowEnd");
                blendHighStart       = a.GetFloat("_HighStart");
                blendHighEnd         = a.GetFloat("_HighEnd");
                steepPower           = a.GetFloat("_SteepPower");
                planetOrigin         = a.GetVector("_PlanetOrigin");
                planetRadius         = a.GetFloat("_PlanetRadius");
                _Displacement_Scale  = a.GetFloat("_displacement_scale");
                _Displacement_Offset = a.GetFloat("_displacement_offset");
                Debug.Log("[Parallax Physics] Success!");
                thisBody = FlightGlobals.currentMainBody.name;
                RestartWheels(p);
            }

            origin = PhysicsStarter.GetPos(wheelPivot.transform);

            if (p.vessel.srf_velocity.magnitude < 0.025f && dampingFrames >= 150) //Vessel is "landed"
            {
                plane.layer = 15;
                started     = true;
                return;
            }
            else
            {
                plane.layer = 15;
            }

            approximateRay.origin    = origin;
            approximateRay.direction = -PhysicsStarter.terrainNormal;
            if (UnityEngine.Physics.Raycast(approximateRay, out hitApproximateRay, 5f, layerMask))
            {
                samplePoint  = hitApproximateRay.point;
                sampleNormal = hitApproximateRay.normal;
            }
            else
            {
                started = true;
                return;
            }
            float displacement = GetDisplacement(new Vector2(wheelPivot.transform.position.x, wheelPivot.transform.position.y), tex, _ST);
            //float mass = (float)p.vessel.totalMass;
            //float massInfluence = (mass * (float)FlightGlobals.currentMainBody.GeeASL * 9.8f); //Weight in Newtons
            //massInfluence = (1f - Mathf.Clamp((massInfluence - 186f) / (9800), 0, 1)); //~1000 tons and displacement doesn't matter much. Starts influencing after a 20 ton ship and depends on gravity
            //displacement *= massInfluence;

            float craftUpsideDownNess = Vector3.Dot(PhysicsStarter.terrainNormal, p.transform.up);  //Value of 1 - Wheel is properly oriented. Value of -1 - Wheel is upside-f****n-down mate

            if (craftUpsideDownNess <= 0.4f && !p.isKerbalEVA())
            {
                //We got 1.3 to play about with
                //Will use 0.3 of it to lower the plane to the ground
                //craftUpsideDownNess = Mathf.Clamp(craftUpsideDownNess, 0, 0.3f) / 0.3f;   //0 to 1
                //displacement *= craftUpsideDownNess;    //Lower plane to the ground when the wheel is tilting too much. Probs played too many FPS games smh
                //dampingFrames = (int)((float)dampingFrames * craftUpsideDownNess);
                dampingFrames = 0;
                //craftOvertipped = true;
                displacement = -50;
                //displacement
            }

            if (lastDisplacement == 10000)
            {
                lastDisplacement = displacement;    //First contact with the ground
            }

            Vector3 forward = Vector3.Normalize(gameObject.GetComponent <Rigidbody>().velocity);
            Vector3 tangent = Vector3.Cross(forward, sampleNormal); //Vector to rotate plane around
            Vector3 disp    = new Vector3((displacement * _Displacement_Scale + _Displacement_Offset - 0.5f) * sampleNormal.x, (displacement * _Displacement_Scale + _Displacement_Offset - 0.5f) * sampleNormal.y, (displacement * _Displacement_Scale + _Displacement_Offset - 0.5f) * sampleNormal.z);

            if (dampingFrames <= 150)
            {
                dampingFrames++;
            }
            if (hitApproximateRay.collider.gameObject.name.Split(' ')[0] != FlightGlobals.currentMainBody.name) //If not casting down to terrain but instead hitting runway / scatter
            {
                plane.GetComponent <Collider>().enabled = false;
                plane.transform.position       = samplePoint;
                PhysicsValidator.planes[plane] = true;
                started = true;
                return;
            }
            if (started == false || dampingFrames <= 150)
            {
                if (dampingFrames == 1)
                {
                    ScreenMessages.PostScreenMessage("[Parallax Collisions] Damping...", 3f, ScreenMessageStyle.UPPER_LEFT);
                }
                Vector3 disp2 = new Vector3((displacement * _Displacement_Scale + _Displacement_Offset) * sampleNormal.x, (displacement * _Displacement_Scale + _Displacement_Offset) * sampleNormal.y, (displacement * _Displacement_Scale + _Displacement_Offset) * sampleNormal.z);
                plane.transform.position = samplePoint + (disp2 * ((float)dampingFrames / 150f)) + new Vector3(-0.5f * sampleNormal.x, -0.5f * sampleNormal.y, -0.5f * sampleNormal.z);    //Slowly raise plane from terrain ground
                started = true;
                plane.GetComponent <Collider>().enabled = true;
                PhysicsValidator.planes[plane]          = true;
                if (dampingFrames == 150)
                {
                    ScreenMessages.PostScreenMessage("[Parallax Collisions] Finished Damping!", 3f, ScreenMessageStyle.UPPER_LEFT);
                }
                return;
            }

            plane.transform.position = samplePoint + disp;

            float rotationPercentage = 1 - ((lastDisplacement * _Displacement_Scale - _Displacement_Offset) / (displacement * _Displacement_Scale - _Displacement_Offset));

            lastDisplacement = displacement;
            plane.transform.Rotate(tangent, rotationPercentage * 180);
            //plane.GetComponent<Collider>().enabled = true;
            EnablePlane();
            PhysicsValidator.planes[plane] = true;
            started = true;
        }
コード例 #22
0
        private Orbit generateOrbit(WBISpaceAnomaly anomaly)
        {
            Orbit         orbit     = null;
            int           bodyIndex = 0;
            CelestialBody body      = null;

            switch (anomaly.spawnMode)
            {
            case WBIAnomalySpawnModes.fixedOrbit:
                body = FlightGlobals.GetBodyByName(anomaly.fixedBody);
                if (body != null)
                {
                    double inclination = anomaly.fixedInclination;
                    if (inclination < 0)
                    {
                        inclination = UnityEngine.Random.Range(0, 90);
                    }
                    return(new Orbit(inclination, anomaly.fixedEccentricity, anomaly.fixedSMA, 0, 0, 0, Planetarium.GetUniversalTime(), body));
                }
                break;

            case WBIAnomalySpawnModes.randomOrbit:
                List <CelestialBody> bodies = FlightGlobals.fetch.bodies;
                bodyIndex = UnityEngine.Random.Range(0, bodies.Count - 1);
                body      = bodies[bodyIndex];
                break;

            case WBIAnomalySpawnModes.randomSolarOrbit:
                List <CelestialBody> stars = BlueshiftScenario.shared.GetStars();
                bodyIndex = UnityEngine.Random.Range(0, stars.Count - 1);
                body      = stars[bodyIndex];
                break;

            case WBIAnomalySpawnModes.randomPlanetOrbit:
                List <CelestialBody> planets = BlueshiftScenario.shared.GetPlanets();
                bodyIndex = UnityEngine.Random.Range(0, planets.Count - 1);
                body      = planets[bodyIndex];
                break;

            case WBIAnomalySpawnModes.everyLastPlanet:
                body = FlightGlobals.GetBodyByName(anomaly.fixedBody);
                break;
            }

            if (body != null)
            {
                switch (orbitType)
                {
                case WBIAnomalyOrbitTypes.elliptical:
                    orbit = Orbit.CreateRandomOrbitAround(body);
                    break;

                case WBIAnomalyOrbitTypes.flyBy:
                    orbit = Orbit.CreateRandomOrbitFlyBy(body, UnityEngine.Random.Range(0, anomaly.maxDaysToClosestApproach));
                    break;

                case WBIAnomalyOrbitTypes.random:
                    if (UnityEngine.Random.Range(1, 100) >= anomaly.flyByOrbitChance)
                    {
                        orbit = Orbit.CreateRandomOrbitFlyBy(body, UnityEngine.Random.Range(0, anomaly.maxDaysToClosestApproach));
                    }
                    else
                    {
                        orbit = Orbit.CreateRandomOrbitAround(body);
                    }
                    break;
                }
            }

            return(orbit);
        }