private void Start()
        {
            commNetParams = HighLogic.CurrentGame.Parameters.CustomParams <CommNet.CommNetParams>();
            int TrackingLevels = 3;

            CBK cbk = new CBK();

            if (cbk.founded)
            {
                TrackingLevels = cbk.levelsTracking;
            }

            float[] TrackingStationFloats = new float[TrackingLevels];  //{ 0.0f, 0.5f, 1.0f };
            for (int i = 0; i < TrackingLevels; i++)
            {
                TrackingStationFloats[i] = (float)i / (TrackingLevels - 1);
            }

            float CurrentTrackingStationFloat = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation);

            CurrentTrackingStationIndex = TrackingStationFloats.IndexOf(CurrentTrackingStationFloat);

            double[] DSNPowerModified     = new double[TrackingLevels];
            string[] DSNPowerModified_str = new string[TrackingLevels];
            for (int i = 0; i < TrackingLevels; i++)
            {
                double dsnPower = GameVariables.Instance.GetDSNRange(TrackingStationFloats[i]);
                DSNPowerModified[i]     = dsnPower /* * commNetParams.DSNModifier*/;
                DSNPowerModified_str[i] = Formatter.ValueExtraShortSpaced(DSNPowerModified[i]);
            }

            List <AvailablePart> partsDT = PartLoader.LoadedPartsList.Where
                                               (p => p.partPrefab.Modules.OfType <ModuleDataTransmitter>().Any()).ToList();

            double BuiltInPowerModified     = GetPowerMostCommonInternalAntenna(partsDT) * commNetParams.rangeModifier;
            string BuiltInPowerModified_str = Formatter.ValueExtraShortSpaced(BuiltInPowerModified);

            foreach (AvailablePart part in partsDT)
            {
                List <ModuleDataTransmitter> modules = part.partPrefab.Modules.OfType <ModuleDataTransmitter>().ToList();


                if (modules.Count == 0)
                {
                    continue;
                }

                var modinfos = part.moduleInfos.Where(i => modules[0].GUIName.Contains(i.moduleName)).ToList();

                if (modules.Count != modinfos.Count)
                {
                    continue;
                }

                for (int index = 0; index < modules.Count; index++)
                {
                    ModuleDataTransmitter    moduleDT = modules[index];
                    AvailablePart.ModuleInfo modinfo  = modinfos[index];

                    double antennaPowerModified = moduleDT.antennaPower * commNetParams.rangeModifier;

                    string[] DSNranges_str = new string[TrackingLevels];
                    double[] DSNranges     = new double[TrackingLevels];
                    for (int i = 0; i < TrackingLevels; i++)
                    {
                        DSNranges[i] = Math.Sqrt(DSNPowerModified[i] * antennaPowerModified);
                    }

                    if (moduleDT.CommType != AntennaType.INTERNAL)
                    {
                        string BuiltInranges_str = Formatter.DistanceShort(Math.Sqrt(BuiltInPowerModified * antennaPowerModified));

                        for (int i = 0; i < TrackingLevels; i++)
                        {
                            DSNranges_str[i] = Formatter.DistanceShort(DSNranges[i]);
                        }

                        modinfo.info =

                            Localizer.Format("#autoLOC_7001005", Formatter.ToTitleCase(moduleDT.antennaType.displayDescription()))
                            + Localizer.Format("#autoLOC_7001006", Formatter.ValueShort(antennaPowerModified))
                            + (moduleDT.CommCombinable
                            ? Localizer.Format("#CAE_Combinability_Exponent", moduleDT.CommCombinableExponent)

                            : Localizer.Format("#CAE_Not_Combinable"))
                            + Localizer.Format("#CAE_Title_vs");

                        if (moduleDT.CommType == AntennaType.RELAY)
                        {
                            modinfo.info += BuiltInPowerModified_str + Localizer.Format("#CAE_Built_In")
                                            + Localizer.Format("#CAE_Spaces") + BuiltInranges_str + "\n";
                        }

                        for (int i = 0; i < TrackingLevels; i++)
                        {
                            modinfo.info +=
                                SmartAlphaChannel(i) +
                                DSNPowerModified_str[i] + Localizer.Format("#CAE_DSN_LN", i + 1)
                                + Localizer.Format("#CAE_Spaces") + DSNranges_str[i]
                                + SmartAlphaChannel(i, false) + "\n";
                        }

                        modinfo.info += Localizer.Format("#autoLOC_236840" /*\n<b>Packet size: </b><<1>> Mits\n*/, moduleDT.packetSize.ToString("F1")).TrimEnd()
                                        + " & " + Localizer.Format("#CAE_EC", moduleDT.packetResourceCost.ToString("#.##")) + "\n"
                                        + Localizer.Format("#autoLOC_236841" /*<b>Bandwidth: </b><<1>> Mits/sec\n*/, (moduleDT.packetSize / moduleDT.packetInterval).ToString("F2"))

                                        + "\n" + Localizer.Format("#autoLOC_236842" /*\n\nWhen Transmitting:*/).Trim()
                                        + Localizer.Format("#CAE_Consumption",
                                                           Localizer.Format("#CAE_EC_Mit", moduleDT.DataResourceCost.ToString("#.#")))
                        ;
                    }
                    else // INTERNAL
                    {
                        for (int i = 0; i < TrackingLevels; i++)
                        {
                            DSNranges_str[i] = Formatter.DistanceExtraShort(DSNranges[i]);
                        }

                        string type = Formatter.ToTitleCase(moduleDT.CommType.displayDescription());
                        //Internal - ok
                        if (type.Length > 8)
                        {
                            type = type.Substring(0, 7) + ".";
                        }

                        modinfo.info =
                            Localizer.Format("#CAE_Type", type) + ", "
                            + Localizer.Format("#CAE_Rating", Formatter.ValueShort(antennaPowerModified))
                            + (moduleDT.CommCombinable ? ", e:" + moduleDT.CommCombinableExponent : "")
                            + Localizer.Format("#CAE_DSN_Short") + " ";


                        if (TrackingLevels % 4 == 0)
                        {
                            modinfo.info += "<nobr>";
                        }

                        for (int i = 0; i < TrackingLevels; i++)
                        {
                            modinfo.info +=
                                SmartAlphaChannel(i) +
                                DSNranges_str[i] + (i != (TrackingLevels - 1)?", ":"") +
                                SmartAlphaChannel(i, false);
                        }

                        if (TrackingLevels % 4 == 0)
                        {
                            modinfo.info += "</nobr>";
                        }

                        modinfo.info += Localizer.Format("#CAE_Orange", Localizer.Format("#autoLOC_236846"));  // #autoLOC_236846 = \n<i>Cannot transmit science</i>\n
                    }
                }
            }
        }
Exemple #2
0
        protected void VesselRecoveryRequested(Vessel v)
        {
            double        elapsedTime       = v.missionTime;
            List <string> retirementChanges = new List <string>();
            List <string> inactivity        = new List <string>();

            double UT = Planetarium.GetUniversalTime();

            foreach (ProtoCrewMember pcm in v.GetVesselCrew())
            {
                bool hasSpace      = false;
                bool hasOrbit      = false;
                bool hasEVA        = false;
                bool hasEVAOther   = false;
                bool hasOther      = false;
                bool hasOrbitOther = false;
                bool hasLandOther  = false;
                int  curFlight     = pcm.careerLog.Last().flight;
                foreach (FlightLog.Entry e in pcm.careerLog.Entries)
                {
                    if (e.type == "TRAINING_mission")
                    {
                        SetExpiration(pcm.name, e, Planetarium.GetUniversalTime());
                    }

                    if (e.flight != curFlight)
                    {
                        continue;
                    }

                    bool isOther = false;
                    if (!string.IsNullOrEmpty(e.target) && e.target != Planetarium.fetch.Home.name)
                    {
                        isOther = hasOther = true;
                    }

                    if (!string.IsNullOrEmpty(e.type))
                    {
                        switch (e.type)
                        {
                        case "Suborbit":
                            hasSpace = true;
                            break;

                        case "Orbit":
                            if (isOther)
                            {
                                hasOrbitOther = true;
                            }
                            else
                            {
                                hasOrbit = true;
                            }
                            break;

                        case "ExitVessel":
                            if (isOther)
                            {
                                hasEVAOther = true;
                            }
                            else
                            {
                                hasEVA = true;
                            }
                            break;

                        case "Land":
                            if (isOther)
                            {
                                hasLandOther = true;
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
                double multiplier = 1d;
                double constant   = 0.5d;
                if (hasSpace)
                {
                    multiplier += settings.recSpace.x;
                    constant   += settings.recSpace.y;
                }
                if (hasOrbit)
                {
                    multiplier += settings.recOrbit.x;
                    constant   += settings.recOrbit.y;
                }
                if (hasOther)
                {
                    multiplier += settings.recOtherBody.x;
                    constant   += settings.recOtherBody.y;
                }
                if (hasEVA)
                {
                    multiplier += settings.recEVA.x;
                    constant   += settings.recEVA.y;
                }
                if (hasEVAOther)
                {
                    multiplier += settings.recEVAOther.x;
                    constant   += settings.recEVAOther.y;
                }
                if (hasOrbitOther)
                {
                    multiplier += settings.recOrbitOther.x;
                    constant   += settings.recOrbitOther.y;
                }
                if (hasLandOther)
                {
                    multiplier += settings.recLandOther.x;
                    constant   += settings.recLandOther.y;
                }

                double retTime;
                if (kerbalRetireTimes.TryGetValue(pcm.name, out retTime))
                {
                    double offset = constant * 86400d * settings.retireOffsetBaseMult / (1 + Math.Pow(Math.Max(curFlight + settings.retireOffsetFlightNumOffset, 0d), settings.retireOffsetFlightNumPow)
                                                                                         * UtilMath.Lerp(settings.retireOffsetStupidMin, settings.retireOffsetStupidMax, pcm.stupidity));
                    if (offset > 0d)
                    {
                        retTime += offset;
                        kerbalRetireTimes[pcm.name] = retTime;
                        retirementChanges.Add("\n" + pcm.name + ", no earlier than " + KSPUtil.PrintDate(retTime, false));
                    }
                }

                multiplier /= (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1d);

                double inactiveTime = elapsedTime * multiplier + constant * 86400d;
                pcm.SetInactive(inactiveTime, false);
                inactivity.Add("\n" + pcm.name + ", until " + KSPUtil.PrintDate(inactiveTime + UT, true, false));
            }
            if (inactivity.Count > 0)
            {
                string msgStr = "The following crew members will be on leave:";
                foreach (string s in inactivity)
                {
                    msgStr += s;
                }

                if (retirementEnabled && retirementChanges.Count > 0)
                {
                    msgStr += "\n\nThe following retirement changes have occurred:";
                    foreach (string s in retirementChanges)
                    {
                        msgStr += s;
                    }
                }

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                             new Vector2(0.5f, 0.5f),
                                             "CrewUpdateNotification",
                                             "Crew Updates",
                                             msgStr,
                                             "OK",
                                             true,
                                             HighLogic.UISkin);
            }
        }
Exemple #3
0
        private void VesselRecoveryProcessing(ProtoVessel v, MissionRecoveryDialog mrDialog, float data)
        {
            Debug.Log("[VR] - Vessel recovery processing");

            List <string> retirementChanges = new List <string>();
            List <string> inactivity        = new List <string>();

            double UT = Planetarium.GetUniversalTime();

            // normally we would use v.missionTime, but that doesn't seem to update
            // when you're not actually controlling the vessel
            double elapsedTime = UT - v.launchTime;

            Debug.Log("[VR] mission elapsedTime: " + KSPUtil.PrintDateDeltaCompact(elapsedTime, true, true));

            // When flight duration was too short, mission training should not be set as expired.
            // This can happen when an on-the-pad failure occurs and the vessel is recovered.
            // We could perhaps override this if they're not actually in flight
            // (if the user didn't recover right from the pad I think this is a fair assumption)
            if (elapsedTime < settings.minFlightDurationSecondsForTrainingExpire)
            {
                Debug.Log("[VR] - mission time too short for crew to be inactive (elapsed time was " + elapsedTime + ", settings set for " + settings.minFlightDurationSecondsForTrainingExpire + ")");
                return;
            }

            foreach (ProtoCrewMember pcm in v.GetVesselCrew())
            {
                Debug.Log("[VR] - Found ProtoCrewMember: " + pcm.displayName);

                bool hasSpace       = false;
                bool hasOrbit       = false;
                bool hasEVA         = false;
                bool hasEVAOther    = false;
                bool hasOther       = false;
                bool hasOrbitOther  = false;
                bool hasLandOther   = false;
                int  curFlight      = pcm.careerLog.Last().flight;
                int  numFlightsDone = pcm.careerLog.Entries.Count(e => e.type == "Recover");
                foreach (FlightLog.Entry e in pcm.careerLog.Entries)
                {
                    if (e.type == "TRAINING_mission")
                    {
                        SetExpiration(pcm.name, e, Planetarium.GetUniversalTime());
                    }

                    if (e.flight != curFlight || e.type == "Nationality")
                    {
                        continue;
                    }

                    Debug.Log($"[VR]  processing flight entry: {e.type}; {e.target}");

                    bool isOther = false;
                    if (!string.IsNullOrEmpty(e.target) && e.target != Planetarium.fetch.Home.name)
                    {
                        Debug.Log($"[VR]    flight is beyond Earth");
                        isOther = hasOther = true;
                    }

                    if (!string.IsNullOrEmpty(e.type))
                    {
                        switch (e.type)
                        {
                        case "Suborbit":
                            hasSpace = true;
                            break;

                        case "Orbit":
                            if (isOther)
                            {
                                hasOrbitOther = true;
                            }
                            else
                            {
                                hasOrbit = true;
                            }
                            break;

                        case "ExitVessel":
                            if (isOther)
                            {
                                hasEVAOther = true;
                            }
                            else
                            {
                                hasEVA = true;
                            }
                            break;

                        case "Land":
                            if (isOther)
                            {
                                hasLandOther = true;
                            }
                            break;

                        default:
                            break;
                        }
                    }
                }
                double multiplier = 1d;
                double constant   = 0.5d;
                if (hasSpace)
                {
                    multiplier += settings.recSpace.x;
                    constant   += settings.recSpace.y;
                    Debug.Log($"[VR]  has space, mult {settings.recSpace.x}; constant {settings.recSpace.y}");
                }
                if (hasOrbit)
                {
                    multiplier += settings.recOrbit.x;
                    constant   += settings.recOrbit.y;
                    Debug.Log($"[VR]  has orbit, mult {settings.recOrbit.x}; constant {settings.recOrbit.y}");
                }
                if (hasOther)
                {
                    multiplier += settings.recOtherBody.x;
                    constant   += settings.recOtherBody.y;
                    Debug.Log($"[VR]  has other body, mult {settings.recOtherBody.x}; constant {settings.recOtherBody.y}");
                }
                if (hasOrbit && hasEVA)    // EVA should only count while in orbit, not when walking on Earth
                {
                    multiplier += settings.recEVA.x;
                    constant   += settings.recEVA.y;
                    Debug.Log($"[VR]  has EVA, mult {settings.recEVA.x}; constant {settings.recEVA.y}");
                }
                if (hasEVAOther)
                {
                    multiplier += settings.recEVAOther.x;
                    constant   += settings.recEVAOther.y;
                    Debug.Log($"[VR]  has EVA at another body, mult {settings.recEVAOther.x}; constant {settings.recEVAOther.y}");
                }
                if (hasOrbitOther)
                {
                    multiplier += settings.recOrbitOther.x;
                    constant   += settings.recOrbitOther.y;
                    Debug.Log($"[VR]  has orbit around another body, mult {settings.recOrbitOther.x}; constant {settings.recOrbitOther.y}");
                }
                if (hasLandOther)
                {
                    multiplier += settings.recLandOther.x;
                    constant   += settings.recLandOther.y;
                    Debug.Log($"[VR]  has landed on another body, mult {settings.recLandOther.x}; constant {settings.recLandOther.y}");
                }

                Debug.Log("[VR]  multiplier: " + multiplier);
                Debug.Log("[VR]  AC multiplier: " + (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1d));
                Debug.Log("[VR]  constant: " + constant);

                double retTime;
                if (kerbalRetireTimes.TryGetValue(pcm.name, out retTime))
                {
                    double offset = constant * 86400d * settings.retireOffsetBaseMult / (1 + Math.Pow(Math.Max(numFlightsDone + settings.retireOffsetFlightNumOffset, 0d), settings.retireOffsetFlightNumPow)
                                                                                         * UtilMath.Lerp(settings.retireOffsetStupidMin, settings.retireOffsetStupidMax, pcm.stupidity));

                    if (offset > 0d)
                    {
                        Debug.Log("[VR] retire date increased by: " + KSPUtil.PrintDateDeltaCompact(offset, true, false));
                        Debug.Log($"[VR]  constant: {constant}; curFlight: {numFlightsDone}; stupidity: {pcm.stupidity}");

                        retTime += offset;
                        kerbalRetireTimes[pcm.name] = retTime;
                        retirementChanges.Add("\n" + pcm.name + ", no earlier than " + KSPUtil.PrintDate(retTime, false));
                    }
                }

                multiplier /= (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1d);

                double inactiveTime = elapsedTime * multiplier + constant * 86400d;
                Debug.Log("[VR] inactive for: " + KSPUtil.PrintDateDeltaCompact(inactiveTime, true, false));

                pcm.SetInactive(inactiveTime, false);
                inactivity.Add("\n" + pcm.name + ", until " + KSPUtil.PrintDate(inactiveTime + UT, true, false));
            }
            if (inactivity.Count > 0)
            {
                Debug.Log("[VR] - showing on leave message");

                string msgStr = "The following crew members will be on leave:";
                foreach (string s in inactivity)
                {
                    msgStr += s;
                }

                if (retirementEnabled && retirementChanges.Count > 0)
                {
                    msgStr += "\n\nThe following retirement changes have occurred:";
                    foreach (string s in retirementChanges)
                    {
                        msgStr += s;
                    }
                }

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                             new Vector2(0.5f, 0.5f),
                                             "CrewUpdateNotification",
                                             "Crew Updates",
                                             msgStr,
                                             "OK",
                                             true,
                                             HighLogic.UISkin);
            }
        }
        private void OnGUI()
        {
            GUI.skin = HighLogic.Skin;
            if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX)
            {
                hasKredits = false;
                ACLevel    = 5;
            }
            if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
            {
                hasKredits = false;
                ACLevel    = 5;
            }
            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                hasKredits = true;
                ACLevel    = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex);
            }

            GUILayout.BeginArea(_areaRect);
            {
                GUILayout.Label("Recruit new Kerbalnaut"); // Testing Renaming Label Works

                // Gender selection
                GUILayout.BeginHorizontal("box");
                KGender = GUILayout.Toolbar(KGender, KGendArray);
                GUILayout.EndHorizontal();

                // Career selection
                GUILayout.BeginVertical("box");
                if (KolonyACOptions.KolonistHiringEnabled)
                {
                    _recruitableKolonists = _kolonists.Select(k => k.Name).ToArray();
                }
                else
                {
                    _recruitableKolonists = _kolonists.Select(k => k.Name).Take(3).ToArray();
                }
                KCareer = GUILayout.SelectionGrid(KCareer, _recruitableKolonists, 4);

                // Adding a section for 'number/bulk hire' here using the int array kBulk
                if (cbulktest() < 1)
                {
                    GUILayout.Label("Bulk hire Option: You can not hire any more kerbals at this time!");
                }
                else
                {
                    GUILayout.Label("Bulk hire Selector: " + KBulki);
                    KBulk  = GUILayout.HorizontalSlider(KBulk, 1, cbulktest());
                    KBulki = Convert.ToInt32(KBulk);
                }

                GUI.contentColor = basecolor;
                GUILayout.EndVertical();

                if (KolonyACOptions.CustomKerbonautsEnabled)
                {
                    // Courage Brains and BadS flag selections
                    GUILayout.BeginVertical("box");
                    GUILayout.Label("Courage:  " + Math.Truncate(KCourage));
                    KCourage = GUILayout.HorizontalSlider(KCourage, 0, 100);
                    GUILayout.Label("Stupidity:  " + Math.Truncate(KStupidity));
                    KStupidity = GUILayout.HorizontalSlider(KStupidity, 0, 100);
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Is this Kerbal Fearless?");
                    KFearless = GUILayout.Toggle(KFearless, "Fearless");
                    GUILayout.EndHorizontal();
                    GUILayout.EndVertical();

                    // Level selection
                    GUILayout.BeginVertical("box");
                    GUILayout.Label("Select Your Level:");

                    // If statements for level options
                    if (kerExp == false)
                    {
                        GUILayout.Label("Level 5 - Mandatory for Career with no EXP enabled.");
                    }
                    else
                    {
                        if (ACLevel == 0)
                        {
                            KLevel = GUILayout.Toolbar(KLevel, KLevelStringsZero);
                        }
                        if (ACLevel == 0.5)
                        {
                            KLevel = GUILayout.Toolbar(KLevel, KLevelStringsOne);
                        }
                        if (ACLevel == 1)
                        {
                            KLevel = GUILayout.Toolbar(KLevel, KLevelStringsTwo);
                        }
                        if (ACLevel == 5)
                        {
                            GUILayout.Label("Level 5 - Mandatory for Sandbox or Science Mode.");
                        }
                    }
                    GUILayout.EndVertical();
                }

                if (hasKredits == true)
                {
                    GUILayout.BeginHorizontal("window");
                    GUILayout.BeginVertical();
                    //GUILayout.FlexibleSpace();
                    if (costMath() <= Funding.Instance.Funds)
                    {
                        GUILayout.Label("Cost: " + costMath(), HighLogic.Skin.textField);
                    }
                    else
                    {
                        GUI.color = Color.red;
                        GUILayout.Label("Insufficient Funds - Cost: " + costMath(), HighLogic.Skin.textField);
                        GUI.color = basecolor;
                    }
                    // GUILayout.FlexibleSpace();
                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();

                if (hTest)
                {
                    if (GUILayout.Button(hireStatus(), GUILayout.Width(200f)))
                    {
                        kHire();
                    }
                }
                if (!hTest)
                {
                    GUILayout.Button(hireStatus(), GUILayout.Width(200f));
                }

                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();

                GUILayout.EndArea();
            }
        }
 private int cbulktest()
 {
     if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
     {
         crewWeCanHire = Mathf.Clamp(GameVariables.Instance.GetActiveCrewLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex)) - HighLogic.CurrentGame.CrewRoster.GetActiveCrewCount(), 0, 10);
     }
     return(crewWeCanHire);
 }
Exemple #6
0
        public List <string> MeetsFacilityRequirements(bool highestFacility = true)
        {
            List <string> failedReasons = new List <string>();

            if (!Utilities.CurrentGameIsCareer())
            {
                return(failedReasons);
            }

            if (Type == ListType.VAB)
            {
                KCT_LaunchPad selectedPad = highestFacility ? KCTGameStates.ActiveKSC.GetHighestLevelLaunchPad() : KCTGameStates.ActiveKSC.ActiveLPInstance;
                float         launchpadNormalizedLevel = 1f * selectedPad.level / KCTGameStates.BuildingMaxLevelCache["LaunchPad"];

                double totalMass = GetTotalMass();
                if (totalMass > GameVariables.Instance.GetCraftMassLimit(launchpadNormalizedLevel, true))
                {
                    failedReasons.Add($"Mass limit exceeded, currently at {totalMass:N} tons");
                }
                if (ExtractedPartNodes.Count > GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding), true))
                {
                    failedReasons.Add("Part Count limit exceeded");
                }
                CraftWithinSizeLimits sizeCheck = new CraftWithinSizeLimits(GetShipSize(), ShipName, SpaceCenterFacility.LaunchPad, GameVariables.Instance.GetCraftSizeLimit(launchpadNormalizedLevel, true));
                if (!sizeCheck.Test())
                {
                    failedReasons.Add("Size limits exceeded");
                }
            }
            else if (Type == ListType.SPH)
            {
                double totalMass = GetTotalMass();
                if (totalMass > GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway), false))
                {
                    failedReasons.Add($"Mass limit exceeded, currently at {totalMass:N} tons");
                }
                if (ExtractedPartNodes.Count > GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar), false))
                {
                    failedReasons.Add("Part Count limit exceeded");
                }
                CraftWithinSizeLimits sizeCheck = new CraftWithinSizeLimits(GetShipSize(), ShipName, SpaceCenterFacility.Runway, GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway), false));
                if (!sizeCheck.Test())
                {
                    failedReasons.Add("Size limits exceeded");
                }
            }

            return(failedReasons);
        }
Exemple #7
0
        public void UpdateUpkeep()
        {
            float[] costs;
            EnsureFacilityLvlCostsLoaded();

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.LaunchPad, out costs))
            {
                if (kctResearchRate > 0d)
                {
                    int lC = costs.Length;
                    for (int i = 0; i < padLevels; i++)
                    {
                        padCosts[i] = 0d;
                        if (i < lC)
                        {
                            padCosts[i] = maintenanceCostMult * settings.facilityLevelCostMult * kctPadCounts[i] * Math.Pow(SumCosts(costs, i), settings.facilityLevelCostPow);
                        }
                    }
                    padCost = 0;
                    for (int i = padLevels; i-- > 0;)
                    {
                        padCost += padCosts[i];
                    }
                }
                else
                {
                    padCost = settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.LaunchPad) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
                }
            }

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.Runway, out costs))
            {
                runwayCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
            }

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.VehicleAssemblyBuilding, out costs))
            {
                vabCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
            }

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.SpaceplaneHangar, out costs))
            {
                sphCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
            }

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.ResearchAndDevelopment, out costs))
            {
                rndCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.ResearchAndDevelopment) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
            }

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.MissionControl, out costs))
            {
                mcCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.MissionControl) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
            }

            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.TrackingStation, out costs))
            {
                tsCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, (int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation) * (costs.Length - 0.95f))), settings.facilityLevelCostPow);
            }

            trainingUpkeep = 0d;
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.AstronautComplex, out costs))
            {
                float lvl    = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex);
                int   lvlInt = (int)(lvl * (costs.Length - 0.95f));
                acCost = maintenanceCostMult * settings.facilityLevelCostMult * Math.Pow(SumCosts(costs, lvlInt), settings.facilityLevelCostPow);
                if (CrewHandler.Instance?.ActiveCourses != null)
                {
                    double courses = CrewHandler.Instance.ActiveCourses.Count(c => c.Started);
                    if (courses > 0)
                    {
                        courses -= lvlInt * settings.freeCoursesPerLevel;
                        if (courses > 0d)
                        {
                            trainingUpkeep = acCost * (courses * (settings.courseMultiplierDivisor / (settings.courseMultiplierDivisor + lvlInt)));
                        }
                    }
                }
            }

            double nautYearlyUpkeep = maintenanceCostMult * settings.nautYearlyUpkeepBase + ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) * maintenanceCostMult * settings.nautYearlyUpkeepAdd;

            nautBaseUpkeep     = 0d;
            nautInFlightUpkeep = 0d;
            nautTotalUpkeep    = 0d;
            double perNaut   = nautYearlyUpkeep * (1d / 365d);
            int    nautCount = 0;

            for (int i = HighLogic.CurrentGame.CrewRoster.Count; i-- > 0;)
            {
                var k = HighLogic.CurrentGame.CrewRoster[i];
                if (k.rosterStatus == ProtoCrewMember.RosterStatus.Dead || k.rosterStatus == ProtoCrewMember.RosterStatus.Missing ||
                    k.type != ProtoCrewMember.KerbalType.Crew)
                {
                    continue;
                }

                ++nautCount;
                if (k.rosterStatus == ProtoCrewMember.RosterStatus.Assigned)
                {
                    nautInFlightUpkeep += maintenanceCostMult * settings.nautInFlightDailyRate;
                }
                else
                {
                    // TODO we really should track this independently, in crewhandler, for fast
                    // use since this runs every frame or so.
                    for (int j = k.flightLog.Count; j-- > 0;)
                    {
                        var e = k.flightLog[j];
                        if (e.type == "TRAINING_proficiency" && TrainingDatabase.HasName(e.target, "Orbit"))
                        {
                            nautBaseUpkeep += maintenanceCostMult * settings.nautOrbitProficiencyDailyRate;
                            break;
                        }
                    }
                }
            }

            nautBaseUpkeep += nautCount * perNaut;
            nautTotalUpkeep = nautBaseUpkeep + trainingUpkeep + nautInFlightUpkeep;

            researchUpkeep = maintenanceCostMult * kctResearchRate * settings.kctResearchMult;

            totalUpkeep = facilityUpkeep + integrationUpkeep + researchUpkeep + nautTotalUpkeep;
        }
Exemple #8
0
        protected override void CreateNode()
        {
            if (comm == null)
            {
                comm = new RACommNode(nodeTransform)
                {
                    OnNetworkPreUpdate      = new Action(OnNetworkPreUpdate),
                    isHome                  = true,
                    isControlSource         = true,
                    isControlSourceMultiHop = true
                };
            }
            comm.name        = nodeName;
            comm.displayName = displaynodeName;
            comm.antennaRelay.Update(!isPermanent ? GameVariables.Instance.GetDSNRange(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)) : antennaPower, GameVariables.Instance.GetDSNRangeCurve(), false);
//            Vector3d pos = (nodeTransform == null) ? transform.position : nodeTransform.position;
//            body.GetLatLonAlt(pos, out lat, out lon, out alt);

            RACommNode t = comm as RACommNode;

            t.ParentBody = body;
            int   maxTL   = HighLogic.CurrentGame.Parameters.CustomParams <RAParameters>().MaxTechLevel;
            float fTSLvl  = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation);
            int   tsLevel = (HighLogic.CurrentGame.Mode == Game.Modes.CAREER) ? Convert.ToInt32(1 + (fTSLvl * maxTL)) : maxTL;

            // Config node contains a list of antennas to build.
            //Debug.LogFormat("Building all antennas for tech level {0} from {1}", tsLevel, config);
            t.RAAntennaList = new List <RealAntenna> {
            };
            foreach (ConfigNode antNode in config.GetNodes("Antenna"))
            {
                //Debug.LogFormat("Building an antenna for {0}", antNode);
                int targetLevel = Int32.Parse(antNode.GetValue("TechLevel"));
                if (tsLevel >= targetLevel)
                {
                    RealAntenna ant = new RealAntennaDigital(name)
                    {
                        ParentNode = comm
                    };
                    ant.LoadFromConfigNode(antNode);
                    ant.ProcessUpgrades(tsLevel, antNode);
                    ant.TechLevelInfo = TechLevelInfo.GetTechLevel(tsLevel);
                    t.RAAntennaList.Add(ant);
                }
                else
                {
                    //Debug.LogFormat("Skipped because current techLevel {0} is less than required {1}", tsLevel, targetLevel);
                }
            }
        }
Exemple #9
0
 public override bool MeetRequirements()
 {
     if (Planetarium.fetch.Home.orbitingBodies.Count < 2)
     {
         return(GameVariables.Instance.UnlockedSpaceObjectDiscovery(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)));
     }
     else
     {
         return(ProgressTracking.Instance.NodeComplete(new string[] { Planetarium.fetch.Home.orbitingBodies[1].bodyName, "Orbit" }) && GameVariables.Instance.UnlockedSpaceObjectDiscovery(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)));
     }
 }
Exemple #10
0
 bool CheckEVAUnlocked(Vessel vessel)
 {
     return(GameVariables.Instance.EVAIsPossible(GameVariables.Instance.UnlockedEVA(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex)), vessel));
 }
Exemple #11
0
        public List <string> MeetsFacilityRequirements(bool highestFacility = true)
        {
            List <string> failedReasons = new List <string>();

            if (!KCT_Utilities.CurrentGameIsCareer())
            {
                return(failedReasons);
            }

            ShipTemplate template = new ShipTemplate();

            template.LoadShip(shipNode);

            if (this.type == KCT_BuildListVessel.ListType.VAB)
            {
                KCT_LaunchPad selectedPad = highestFacility ? KCT_GameStates.ActiveKSC.GetHighestLevelLaunchPad() : KCT_GameStates.ActiveKSC.ActiveLPInstance;
                float         launchpadNormalizedLevel = 1.0f * selectedPad.level / KCT_GameStates.BuildingMaxLevelCache["LaunchPad"];

                if (this.GetTotalMass() > GameVariables.Instance.GetCraftMassLimit(launchpadNormalizedLevel, true))
                {
                    failedReasons.Add("Mass limit exceeded");
                }
                if (this.ExtractedPartNodes.Count > GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding), true))
                {
                    failedReasons.Add("Part Count limit exceeded");
                }
                PreFlightTests.CraftWithinSizeLimits sizeCheck = new PreFlightTests.CraftWithinSizeLimits(template, SpaceCenterFacility.LaunchPad, GameVariables.Instance.GetCraftSizeLimit(launchpadNormalizedLevel, true));
                if (!sizeCheck.Test())
                {
                    failedReasons.Add("Size limits exceeded");
                }
            }
            else if (this.type == KCT_BuildListVessel.ListType.SPH)
            {
                if (this.GetTotalMass() > GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway), false))
                {
                    failedReasons.Add("Mass limit exceeded");
                }
                if (this.ExtractedPartNodes.Count > GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar), false))
                {
                    failedReasons.Add("Part Count limit exceeded");
                }
                PreFlightTests.CraftWithinSizeLimits sizeCheck = new PreFlightTests.CraftWithinSizeLimits(template, SpaceCenterFacility.Runway, GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway), false));
                if (!sizeCheck.Test())
                {
                    failedReasons.Add("Size limits exceeded");
                }
            }
            return(failedReasons);
        }
Exemple #12
0
        private void OnGUI()
        {
            GUI.skin = HighLogic.Skin;
            var roster = HighLogic.CurrentGame.CrewRoster;

            GUIContent[] KGendArray = new GUIContent[2] {
                KMale, KFemale
            };
            if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX)
            {
                hasKredits = false;
                ACLevel    = 5;
            }
            if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
            {
                hasKredits = false;
                ACLevel    = 1;
            }
            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                hasKredits = true;
                ACLevel    = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex);
            }


            GUILayout.BeginArea(_windowRect, _customWindowSkin);
            {
                GUILayout.Label("Kerbal Science Institute: Placement Services"); // Testing Renaming Label Works

                // Gender selection
                GUILayout.BeginHorizontal("box");
                KGender = GUILayout.Toolbar(KGender, KGendArray);
                GUILayout.EndHorizontal();

                // Career selection
                GUILayout.BeginVertical("box");
                KCareer = GUILayout.Toolbar(KCareer, KCareerStrings);
                GUILayout.Label("Pilots can use SAS and ships at vector markers.");
                GUILayout.Label("Scientists can reset experiements and science gains.");
                GUILayout.Label("Engineers help drills, repack chutes and fix some items.");
                GUILayout.Label("Note: Some mods give additional effects to some careers.");
                GUI.contentColor = basecolor;
                GUILayout.EndVertical();

                // Courage Brains and BadS flag selections
                GUILayout.BeginVertical("box");
                GUILayout.Label("Courage:  " + Math.Truncate(KCourage));
                KCourage = GUILayout.HorizontalSlider(KCourage, 0, 100);
                GUILayout.Label("Stupidity:  " + Math.Truncate(KStupidity));
                KStupidity = GUILayout.HorizontalSlider(KStupidity, 0, 100);
                GUILayout.BeginHorizontal();
                GUILayout.Label("Is this Kerbal Fearless?");
                KFearless = GUILayout.Toggle(KFearless, "Fearless");
                GUILayout.EndHorizontal();
                GUILayout.EndVertical();

                // Level selection
                GUILayout.BeginVertical("box");
                GUILayout.Label("Select Your Level:");

                // If statements for level options
                if (ACLevel == 0)
                {
                    KLevel = GUILayout.Toolbar(KLevel, KLevelStringsZero);
                }
                if (ACLevel == 0.5)
                {
                    KLevel = GUILayout.Toolbar(KLevel, KLevelStringsOne);
                }
                if (ACLevel == 1)
                {
                    KLevel = GUILayout.Toolbar(KLevel, KLevelStringsTwo);
                }
                if (ACLevel == 5)
                {
                    GUILayout.Label("Level 5 - Manditory for Sandbox or Science Mode.");
                }
                GUILayout.EndVertical();

                if (hasKredits == true)
                {
                    GUILayout.BeginHorizontal("window");
                    GUILayout.BeginVertical();
                    GUILayout.FlexibleSpace();

                    if (costMath() <= Funding.Instance.Funds)
                    {
                        GUILayout.Label("Cost: " + costMath(), HighLogic.Skin.textField);
                    }
                    else
                    {
                        GUI.color = Color.red;
                        GUILayout.Label("Insufficient Funds - Cost: " + costMath(), HighLogic.Skin.textField);
                        GUI.color = basecolor;
                    }
                    GUILayout.FlexibleSpace();
                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();

                if (hTest)
                {
                    if (GUILayout.Button(hireStatus(), GUILayout.Width(200f)))
                    {
                        kHire();
                    }
                }
                if (!hTest)
                {
                    GUILayout.Button(hireStatus(), GUILayout.Width(200f));
                }

                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();

                GUILayout.EndArea();
            }
        }
Exemple #13
0
        public override void OnStart(PartModule.StartState state)
        {
            if ((!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight) || !CompatibilityChecker.IsAllCompatible())
            {
                return;
            }
            //Identification of the RealChuteModule
            if (this.part.Modules.Contains("RealChuteModule"))
            {
                this.rcModule = this.part.Modules["RealChuteModule"] as RealChuteModule;
            }
            else
            {
                return;
            }
            this.secondaryChute = this.rcModule.secondaryChute;
            if (!string.IsNullOrEmpty(this.textureLibrary))
            {
                this.textureLib.TryGetConfig(this.textureLibrary, ref this.textures);
            }
            this.bodies = AtmoPlanets.fetch;
            this.body   = this.bodies.GetBody(this.planets);

            //Initializes ChuteTemplates
            if (this.chutes.Count <= 0)
            {
                if (this.node == null && !PersistentManager.instance.TryGetNode <ProceduralChute>(this.part.name, ref this.node))
                {
                    return;
                }
                LoadChutes();
            }
            this.chutes.ForEach(c => c.Initialize());
            if (this.sizes.Count <= 0)
            {
                this.sizes = this.sizeLib.GetSizes(this.part.partInfo.name);
            }

            //Creates an instance of the texture library
            this.editorGUI = new EditorGUI(this);
            if (HighLogic.LoadedSceneIsEditor)
            {
                //Windows initiation
                this.editorGUI.window = new Rect(5, 370, 420, Screen.height - 375);
                this.chutes.ForEach(c =>
                {
                    c.templateGUI.materialsWindow = new Rect(this.editorGUI.matX, this.editorGUI.matY, 375, 275);
                    c.templateGUI.drag            = new Rect(0, 0, 375, 25);
                });
                this.editorGUI.failedWindow         = new Rect(Screen.width / 2 - 150, Screen.height / 2 - 150, 300, 300);
                this.editorGUI.successfulWindow     = new Rect(Screen.width / 2 - 150, Screen.height / 2 - 25, 300, 50);
                this.editorGUI.presetsWindow        = new Rect(Screen.width / 2 - 200, Screen.height / 2 - 250, 400, 500);
                this.editorGUI.presetsSaveWindow    = new Rect(Screen.width / 2 - 175, Screen.height / 2 - 110, 350, 220);
                this.editorGUI.presetsWarningWindow = new Rect(Screen.width / 2 - 100, Screen.height / 2 - 50, 200, 100);

                if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
                {
                    float level = 0;
                    switch (EditorDriver.editorFacility)
                    {
                    case EditorFacility.VAB:
                        level = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding); break;

                    case EditorFacility.SPH:
                        level = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar); break;

                    default:
                        break;
                    }
                    if (GameVariables.Instance.UnlockedActionGroupsStock(level))
                    {
                        Events.ForEach(e => e.guiActiveEditor = false);
                    }
                }
                else
                {
                    Events.ForEach(e => e.guiActiveEditor = false);
                }

                //Gets the original part state
                if (this.textures != null && this.caseID == -1)
                {
                    if (this.caseID == -1)
                    {
                        if (this.textures.TryGetCase(this.currentCase, ref this.parachuteCase))
                        {
                            this.caseID = this.textures.GetCaseIndex(this.parachuteCase.name);
                        }
                    }
                    else
                    {
                        this.textures.TryGetCase(this.caseID, this.type, ref this.parachuteCase);
                    }
                    this.lastCaseID = this.caseID;
                }

                if (!this.initiated)
                {
                    if (!this.bodies.TryGetBodyIndex("Kerbin", ref this.planets))
                    {
                        this.planets = 0;
                    }
                    this.body = this.bodies.GetBody(planets);

                    //Identification of the values from the RealChuteModule
                    this.mustGoDown     = this.rcModule.mustGoDown;
                    this.deployOnGround = this.rcModule.deployOnGround;
                    this.timer          = this.rcModule.timer + "s";
                    this.cutSpeed       = this.rcModule.cutSpeed.ToString();
                    if (this.rcModule.spareChutes != -1)
                    {
                        this.spares = this.rcModule.spareChutes.ToString();
                    }
                    this.originalSize = this.part.transform.GetChild(0).localScale;
                    this.initiated    = true;
                }
            }
            else if (this.textures != null)
            {
                this.textures.TryGetCase(this.caseID, this.type, ref this.parachuteCase);
                this.lastCaseID = this.caseID;
            }

            if (this.parent == null)
            {
                this.parent = this.part.FindModelTransform(this.rcModule.parachutes[0].parachuteName).parent;
            }

            //Updates the part
            if (this.textures != null)
            {
                UpdateCaseTexture(this.part, this.rcModule);
                this.editorGUI.cases    = this.textures.caseNames;
                this.editorGUI.canopies = this.textures.canopyNames;
                this.editorGUI.models   = this.textures.modelNames;
            }
            UpdateScale(this.part, this.rcModule);
        }
Exemple #14
0
        public string MaximumVesselMass()
        {
            SpaceCenterFacility rolloutFacility = (EditorDriver.editorFacility == EditorFacility.VAB) ? SpaceCenterFacility.LaunchPad : SpaceCenterFacility.Runway;
            float maximumVesselMass             = GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(rolloutFacility));

            if (maximumVesselMass < float.MaxValue)
            {
                return(string.Format("{0} t", maximumVesselMass.ToString("F3")));
            }
            else
            {
                return("Unlimited");
            }
        }
        private void LaunchShip(CraftTemplate ship, string launchSiteName)
        {
            // From EditorLogic, see launchVessel(), proceedWithVesselLaunch(), and goForLaunch()
            var manifest = VesselCrewManifest.FromConfigNode(ship.InnerTemplate.config);

            manifest = HighLogic.CurrentGame.CrewRoster.DefaultCrewForVessel(ship.InnerTemplate.config, manifest);
            PreFlightCheck preFlightCheck = new PreFlightCheck(
                () =>
            {
                SafeHouse.Logger.Log("Launch new vessel!");
                FlightDriver.StartWithNewLaunch(ship.FilePath, EditorLogic.FlagURL, launchSiteName, manifest);
            },
                () =>
            {
                SafeHouse.Logger.LogError("Could not launch vessel, did not pass preflight...");
            });

            if (launchSiteName.Equals("runway", System.StringComparison.OrdinalIgnoreCase))
            {
                preFlightCheck.AddTest(new CraftWithinPartCountLimit(ship.InnerTemplate, SpaceCenterFacility.SpaceplaneHangar, GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar), false)));
                preFlightCheck.AddTest(new CraftWithinSizeLimits(ship.InnerTemplate, SpaceCenterFacility.Runway, GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway), false)));
                preFlightCheck.AddTest(new CraftWithinMassLimits(ship.InnerTemplate, SpaceCenterFacility.Runway, (double)GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway), false)));
            }
            else if (launchSiteName.Equals("launchpad", System.StringComparison.OrdinalIgnoreCase))
            {
                preFlightCheck.AddTest(new CraftWithinPartCountLimit(ship.InnerTemplate, SpaceCenterFacility.VehicleAssemblyBuilding, GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding), true)));
                preFlightCheck.AddTest(new CraftWithinSizeLimits(ship.InnerTemplate, SpaceCenterFacility.LaunchPad, GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.LaunchPad), true)));
                preFlightCheck.AddTest(new CraftWithinMassLimits(ship.InnerTemplate, SpaceCenterFacility.LaunchPad, (double)GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.LaunchPad), true)));
            }
            else
            {
                throw new KOSException("Failed to lauch vessel, unrecognized lauch site: " + launchSiteName + ". Expected \"Runway\" or \"LaunchPad\".");
            }
            preFlightCheck.AddTest(new ExperimentalPartsAvailable(manifest));
            preFlightCheck.AddTest(new CanAffordLaunchTest(ship.InnerTemplate, Funding.Instance));
            preFlightCheck.AddTest(new FacilityOperational(launchSiteName, launchSiteName));
            preFlightCheck.AddTest(new NoControlSources(manifest));
            preFlightCheck.AddTest(new LaunchSiteClear(launchSiteName, launchSiteName, HighLogic.CurrentGame));
            preFlightCheck.RunTests();
            shared.Cpu.GetCurrentOpcode().AbortProgram = true;
            SafeHouse.Logger.Log("Craft waiting for preflight checks!");
        }
Exemple #16
0
        private static void DrawOrbits(Camera cam)
        {
            GL.PushMatrix();

            GL.LoadProjectionMatrix(cam.projectionMatrix);
            GL.modelview = cam.worldToCameraMatrix;

            bool showOrbits =
                GameVariables.Instance.GetOrbitDisplayMode(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)) >=
                GameVariables.OrbitDisplayMode.AllOrbits;

            double degStep     = 2;
            int    pointsCount = (int)Math.Floor(360d / degStep);
            double radStep     = degStep * UtilMath.Deg2Rad;

            foreach (OrbitDriver orbitDriver in Planetarium.Orbits)
            {
                //Vessel vessel = orbitDriver.vessel;
                //if (vessel != null)
                //{
                //
                //    print(vessel.name + " " + orbitDriver.updateMode + " "
                //        + orbitDriver.Renderer.drawMode + " "
                //        + MapViewFiltering.CheckAgainstFilter(vessel) + " "
                //        + (vessel.vesselType == VesselType.Debris && !orbitDriver.Renderer.isFocused));
                //}

                if (!orbitDriver.Renderer || orbitDriver.Renderer.discoveryInfo == null)
                {
                    continue;
                }

                bool visible = showOrbits &&
                               orbitDriver.Renderer.discoveryInfo.HaveKnowledgeAbout(DiscoveryLevels.StateVectors);
                //&& (vessel == null || !MapViewFiltering.CheckAgainstFilter(vessel));  // Add back when I do render for PatchedConicRenderer
                //&& !(vessel.vesselType == VesselType.Debris && !orbitDriver.Renderer.isFocused);

                if (!visible)
                {
                    continue;
                }

                material.SetPass(0);

                GL.Begin(GL.LINES);

                GL.Color(orbitDriver.Renderer.orbitColor.A(0.9f));
                Orbit  orbit         = orbitDriver.orbit;
                double semiMinorAxis = orbit.semiMinorAxis;

                if (orbit.eccentricity < 1d)
                {
                    // Make sure to have a point where we are so the orbit line is actually ON the body/vessel
                    double  eccentricAnomalyOrigin = orbit.eccentricAnomaly;
                    Vector3 first    = ScaledSpace.LocalToScaledSpace(orbit.getPositionFromEccAnomalyWithSemiMinorAxis(eccentricAnomalyOrigin, semiMinorAxis));
                    Vector3 previous = first;
                    for (int i = 1; i < pointsCount; ++i)
                    {
                        double eccentricAnomaly = (eccentricAnomalyOrigin + i * radStep) % (2 * Mathf.PI);

                        Vector3 point = ScaledSpace.LocalToScaledSpace(orbit.getPositionFromEccAnomalyWithSemiMinorAxis(eccentricAnomaly, semiMinorAxis));

                        GL.Vertex3(previous.x, previous.y, previous.z);
                        GL.Vertex3(point.x, point.y, point.z);

                        previous = point;
                    }

                    GL.Vertex3(previous.x, previous.y, previous.z);
                    GL.Vertex3(first.x, first.y, first.z);
                }
                else
                {
                    double start = -Math.Acos(-(1d / orbit.eccentricity));
                    double end   = -start;
                    double step  = (end - start) / (pointsCount - 1);

                    double eccentricAnomalyOrigin = orbit.eccentricAnomaly;

                    Vector3 first = ScaledSpace.LocalToScaledSpace(orbit.getPositionFromEccAnomalyWithSemiMinorAxis(eccentricAnomalyOrigin, semiMinorAxis));

                    int     i                = 1;
                    Vector3 previous         = first;
                    double  eccentricAnomaly = eccentricAnomalyOrigin - step;
                    while (eccentricAnomaly > start)
                    {
                        Vector3 point =
                            ScaledSpace.LocalToScaledSpace(orbit.getPositionFromEccAnomalyWithSemiMinorAxis(eccentricAnomaly, semiMinorAxis));

                        GL.Vertex3(previous.x, previous.y, previous.z);
                        GL.Vertex3(point.x, point.y, point.z);
                        previous = point;

                        i++;
                        eccentricAnomaly = eccentricAnomalyOrigin - i * step;
                    }

                    i                = 1;
                    previous         = first;
                    eccentricAnomaly = eccentricAnomalyOrigin + step;
                    while (eccentricAnomaly < end)
                    {
                        Vector3 point =
                            ScaledSpace.LocalToScaledSpace(orbit.getPositionFromEccAnomalyWithSemiMinorAxis(eccentricAnomaly, semiMinorAxis));

                        GL.Vertex3(previous.x, previous.y, previous.z);
                        GL.Vertex3(point.x, point.y, point.z);
                        previous = point;

                        i++;
                        eccentricAnomaly = eccentricAnomalyOrigin + i * step;
                    }
                }
                GL.End();
            }

            GL.PopMatrix();
        }
Exemple #17
0
 private bool surfaceSamplesUnlocked() // checking that the appropriate career unlocks are flagged
 {
     return(GameVariables.Instance.UnlockedEVA(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex)) &&
            GameVariables.Instance.UnlockedFuelTransfer(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.ResearchAndDevelopment)));
 }
Exemple #18
0
 private void OnVesselRollout(ShipConstruct ship)
 {
     if (!BudgetSettings.instance.launchCostsEnabled)
     {
         return;
     }
     if (ship.shipFacility == EditorFacility.VAB)
     {
         launchCosts += BudgetSettings.instance.launchCostsVAB * ((int)Math.Round(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.LaunchPad) * ScenarioUpgradeableFacilities.GetFacilityLevelCount(SpaceCenterFacility.LaunchPad)) + 1);
     }
     else
     {
         launchCosts += BudgetSettings.instance.launchCostsSPH * ((int)Math.Round(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway) * ScenarioUpgradeableFacilities.GetFacilityLevelCount(SpaceCenterFacility.Runway)) + 1);
     }
 }
 // 0.90 added a building upgrade to unlock Orbit visualization and patched conics
 // Unfortunately when patchedConics are disabled vessel.patchedConicSolver is null
 // So we need to add a lot of sanity check and/or disable modules
 public static bool patchedConicsUnlocked(this Vessel vessel)
 {
     return(GameVariables.Instance.GetOrbitDisplayMode(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)) == GameVariables.OrbitDisplayMode.PatchedConics);
 }
        public static int BuildingUpgradeLevel(SpaceCenterFacility facility)
        {
            int lvl = 0;

            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER && Settings1.Instance.UseUpgrades)
            {
                lvl = (int)Math.Round((ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility) * ScenarioUpgradeableFacilities.GetFacilityLevel(facility)));
            }
            else
            {
                lvl = ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility); //returns 2 for VAB in Sandbox
            }
            return(lvl);
        }
        private string hireStatus()
        {
            string bText = "Hire Applicant";

            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                double kredits = Funding.Instance.Funds;
                if (costMath() > kredits)
                {
                    bText = "Not Enough Funds!";
                    hTest = false;
                }
                if (HighLogic.CurrentGame.CrewRoster.GetActiveCrewCount() >= GameVariables.Instance.GetActiveCrewLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex)))
                {
                    bText = "Roster is Full!";
                    hTest = false;
                }
                else
                {
                    hTest = true;
                }
            }
            return(bText);
        }
Exemple #22
0
        public List <string> MeetsFacilityRequirements()
        {
            List <string> failedReasons = new List <string>();

            if (!KCT_Utilities.CurrentGameIsCareer())
            {
                return(failedReasons);
            }

            ShipTemplate template = new ShipTemplate();

            template.LoadShip(shipNode);

            if (this.type == KCT_BuildListVessel.ListType.VAB)
            {
                if (this.GetTotalMass() > GameVariables.Instance.GetCraftMassLimit(KCT_GameStates.ActiveKSC.ActiveLPInstance.level / 2.0F))
                {
                    failedReasons.Add("Mass limit exceeded");
                }
                if (this.ExtractedPartNodes.Count > GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding)))
                {
                    failedReasons.Add("Part Count limit exceeded");
                }
                PreFlightTests.CraftWithinSizeLimits sizeCheck = new PreFlightTests.CraftWithinSizeLimits(template, SpaceCenterFacility.LaunchPad, GameVariables.Instance.GetCraftSizeLimit(KCT_GameStates.ActiveKSC.ActiveLPInstance.level / 2.0F));
                if (!sizeCheck.Test())
                {
                    failedReasons.Add("Size limits exceeded");
                }
            }
            else if (this.type == KCT_BuildListVessel.ListType.SPH)
            {
                if (this.GetTotalMass() > GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway)))
                {
                    failedReasons.Add("Mass limit exceeded");
                }
                if (this.ExtractedPartNodes.Count > GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar)))
                {
                    failedReasons.Add("Part Count limit exceeded");
                }
                PreFlightTests.CraftWithinSizeLimits sizeCheck = new PreFlightTests.CraftWithinSizeLimits(template, SpaceCenterFacility.Runway, GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway)));
                if (!sizeCheck.Test())
                {
                    failedReasons.Add("Size limits exceeded");
                }
            }
            return(failedReasons);
        }
        private string hireStatus(out bool hTest)
        {
            string bText = Localizer.Format("#TRPHire_Button_Hire");

            hTest = true;
            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                double kredits = Funding.Instance.Funds;
                if (costMath() > kredits)
                {
                    bText = Localizer.Format("#TRPHire_Button_NotEnoughFunds");
                    hTest = false;
                }
                else if (HighLogic.CurrentGame.CrewRoster.GetActiveCrewCount() >= GameVariables.Instance.GetActiveCrewLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex)))
                {
                    bText = Localizer.Format("#TRPHire_Button_RosterFull");
                    hTest = false;
                }
                else if (isNameConflict())
                {
                    bText = Localizer.Format("#TRPHire_Button_NameConflict");
                    hTest = false;
                }
                else
                {
                    hTest = true;
                }
            }
            return(bText);
        }
Exemple #24
0
        private void VesselRecoveryProcessing(ProtoVessel v, MissionRecoveryDialog mrDialog, float data)
        {
            Debug.Log("[RP-0] - Vessel recovery processing");

            var retirementChanges = new List <string>();
            var inactivity        = new List <string>();

            double UT = KSPUtils.GetUT();

            // normally we would use v.missionTime, but that doesn't seem to update
            // when you're not actually controlling the vessel
            double elapsedTime = UT - v.launchTime;

            Debug.Log($"[RP-0] mission elapsedTime: {KSPUtil.PrintDateDeltaCompact(elapsedTime, true, true)}");

            // When flight duration was too short, mission training should not be set as expired.
            // This can happen when an on-the-pad failure occurs and the vessel is recovered.
            // We could perhaps override this if they're not actually in flight
            // (if the user didn't recover right from the pad I think this is a fair assumption)
            if (elapsedTime < Settings.minFlightDurationSecondsForTrainingExpire)
            {
                Debug.Log($"[RP-0] - mission time too short for crew to be inactive (elapsed time was {elapsedTime}, settings set for {Settings.minFlightDurationSecondsForTrainingExpire})");
                return;
            }

            var validStatuses = new List <string>
            {
                FlightLog.EntryType.Flight.ToString(), Situation_FlightHigh, FlightLog.EntryType.Suborbit.ToString(),
                FlightLog.EntryType.Orbit.ToString(), FlightLog.EntryType.ExitVessel.ToString(),
                FlightLog.EntryType.Land.ToString(), FlightLog.EntryType.Flyby.ToString()
            };

            foreach (ProtoCrewMember pcm in v.GetVesselCrew())
            {
                Debug.Log("[RP-0] - Found ProtoCrewMember: " + pcm.displayName);

                var    allFlightsDict = new Dictionary <string, int>();
                int    curFlight      = pcm.careerLog.Last().flight;
                double inactivityMult = 0;
                double retirementMult = 0;

                foreach (FlightLog.Entry e in pcm.careerLog.Entries)
                {
                    if (e.type == "Nationality")
                    {
                        continue;
                    }
                    if (e.type == TrainingType_Mission)
                    {
                        SetExpiration(pcm.name, e, KSPUtils.GetUT());
                    }

                    if (validStatuses.Contains(e.type))
                    {
                        int situationCount;
                        var key = $"{e.target}-{e.type}";
                        if (allFlightsDict.ContainsKey(key))
                        {
                            situationCount      = allFlightsDict[key];
                            allFlightsDict[key] = ++situationCount;
                        }
                        else
                        {
                            situationCount = 1;
                            allFlightsDict.Add(key, situationCount);
                        }

                        if (e.flight != curFlight)
                        {
                            continue;
                        }

                        if (TryGetBestSituationMatch(e.target, e.type, "Retire", out double situationMult))
                        {
                            double countMult = 1 + Math.Pow(situationCount - 1, Settings.retireOffsetFlightNumPow);
                            retirementMult += situationMult / countMult;
                        }

                        if (TryGetBestSituationMatch(e.target, e.type, "Inactive", out double inactivMult))
                        {
                            inactivityMult += inactivMult;
                        }
                    }
                }

                Debug.Log("[RP-0]  retirementMult: " + retirementMult);
                Debug.Log("[RP-0]  inactivityMult: " + inactivityMult);

                double acMult = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) + 1;
                Debug.Log("[RP-0]  AC multiplier: " + acMult);

                if (KerbalRetireTimes.TryGetValue(pcm.name, out double retTime))
                {
                    double stupidityPenalty = UtilMath.Lerp(Settings.retireOffsetStupidMin, Settings.retireOffsetStupidMax, pcm.stupidity);
                    Debug.Log($"[RP-0]  stupidityPenalty for {pcm.stupidity}: {stupidityPenalty}");
                    double retireOffset = retirementMult * 86400 * Settings.retireOffsetBaseMult / stupidityPenalty;

                    if (retireOffset > 0)
                    {
                        KerbalRetireIncreases.TryGetValue(pcm.name, out double retIncreaseTotal);
                        retIncreaseTotal += retireOffset;
                        if (retIncreaseTotal > Settings.retireIncreaseCap)
                        {
                            // Cap the total retirement increase at a specific number of years
                            retireOffset    -= retIncreaseTotal - Settings.retireIncreaseCap;
                            retIncreaseTotal = Settings.retireIncreaseCap;
                        }
                        KerbalRetireIncreases[pcm.name] = retIncreaseTotal;

                        string sRetireOffset = KSPUtil.PrintDateDelta(retireOffset, false, false);
                        Debug.Log("[RP-0] retire date increased by: " + sRetireOffset);

                        retTime += retireOffset;
                        KerbalRetireTimes[pcm.name] = retTime;
                        retirementChanges.Add($"\n{pcm.name}, +{sRetireOffset}, no earlier than {KSPUtil.PrintDate(retTime, false)}");
                    }
                }

                inactivityMult = Math.Max(1, inactivityMult);
                double elapsedTimeDays  = elapsedTime / 86400;
                double inactiveTimeDays = Math.Pow(Math.Max(Settings.inactivityMinFlightDurationDays, elapsedTimeDays), Settings.inactivityFlightDurationExponent) *
                                          Math.Min(Settings.inactivityMaxSituationMult, inactivityMult) / acMult;
                double inactiveTime = inactiveTimeDays * 86400;
                Debug.Log("[RP-0] inactive for: " + KSPUtil.PrintDateDeltaCompact(inactiveTime, true, false));

                pcm.SetInactive(inactiveTime, false);
                inactivity.Add($"\n{pcm.name}, until {KSPUtil.PrintDate(inactiveTime + UT, true, false)}");
            }

            if (inactivity.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("The following crew members will be on leave:");
                foreach (string s in inactivity)
                {
                    sb.Append(s);
                }

                if (RetirementEnabled && retirementChanges.Count > 0)
                {
                    sb.Append("\n\nThe following retirement changes have occurred:");
                    foreach (string s in retirementChanges)
                    {
                        sb.Append(s);
                    }
                }

                PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
                                             new Vector2(0.5f, 0.5f),
                                             "CrewUpdateNotification",
                                             "Crew Updates",
                                             sb.ToString(),
                                             "OK",
                                             true,
                                             HighLogic.UISkin);
            }
        }
        private void OnGUI()
        {
            GUI.skin = HighLogic.Skin;
            var roster = HighLogic.CurrentGame.CrewRoster;

            GUIContent[] KGendArray = new GUIContent[3] {
                KMale, KFemale, KGRandom
            };
            if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX)
            {
                hasKredits = false;
                ACLevel    = 5;
            }
            if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
            {
                hasKredits = false;
                ACLevel    = 5;
            }
            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                hasKredits = true;
                ACLevel    = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex);
            }

            GUILayout.BeginArea(_areaRect);
            {
                GUILayout.Label(Localizer.Format("#TRPHire_Title"));

                // Gender selection
                GUILayout.BeginHorizontal("box");
                KGender = GUILayout.Toolbar(KGender, KGendArray);
                GUILayout.EndHorizontal();

                // Career selection
                GUILayout.BeginVertical("box");
                KCareer = GUILayout.SelectionGrid(KCareer, traits.KCareerGrid, traits.KCareerCnt);
                // Adding a section for 'number/bulk hire' here using the int array kBulk
                if (cbulktest() < 1)
                {
                    GUILayout.Label(Localizer.Format("#TRPHire_BulkHireNo"));
                    KBulk  = 0;
                    KBulki = 0;
                }
                else
                {
                    GUILayout.Label(Localizer.Format("#TRPHire_BulkHireSelector") + ": " + KBulki);
                    KBulk  = GUILayout.HorizontalSlider(KBulk, 1, cbulktest());
                    KBulki = Convert.ToInt32(KBulk);
                }



                GUI.contentColor = basecolor;
                GUILayout.EndVertical();

                if (KBulki > 0)
                {
                    GUIStyle style = new GUIStyle(HighLogic.Skin.label);
                    style.normal.textColor   = Color.white;
                    style.active.textColor   = Color.white;
                    style.focused.background = null;

                    GUILayout.BeginHorizontal();

                    GUILayout.BeginVertical(GUILayout.Width(_areaRect.width * 0.48f));
                    for (int i = 0; i < KBulki; i += 2)
                    {
                        KNames[KGender, i] = GUILayout.TextField(KNames[KGender, i], style);
                    }
                    GUILayout.EndVertical();

                    if (KBulki > 1)
                    {
                        GUILayout.BeginVertical(GUILayout.Width(_areaRect.width * 0.48f));
                        for (int i = 1; i < KBulki; i += 2)
                        {
                            KNames[KGender, i] = GUILayout.TextArea(KNames[KGender, i], style);
                        }
                        GUILayout.EndVertical();
                    }

                    GUILayout.EndHorizontal();
                }


                // Courage Brains and BadS flag selections
                GUILayout.BeginVertical("box");
                GUILayout.Label(Courage + ":  " + Math.Truncate(KCourage));
                KCourage = GUILayout.HorizontalSlider(KCourage, 0, 100);
                GUILayout.Label(Stupidity + ":  " + Math.Truncate(KStupidity));
                KStupidity = GUILayout.HorizontalSlider(KStupidity, 0, 100);

                GUILayout.BeginHorizontal();
                GUILayout.Label(Localizer.Format("#TRPHire_IsFearless"));
                KFearless = GUILayout.Toggle(KFearless, Badass);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label(Localizer.Format("#TRPHire_IsVeteran"));
                KVeteran = GUILayout.Toggle(KVeteran, Veteran);
                GUILayout.EndHorizontal();
                GUILayout.EndVertical();

                // Level selection
                GUILayout.BeginVertical("box");
                GUILayout.Label(Localizer.Format("#TRPHire_SelectLevel"));

                // If statements for level options
                if (kerExp == false)
                {
                    GUILayout.Label(Localizer.Format("#TRPHire_Level5CareerNoExp"));
                }
                else
                {
                    if (ACLevel == 0)
                    {
                        KLevel = GUILayout.Toolbar(KLevel, KLevelStringsZero);
                    }
                    if (ACLevel == 0.5)
                    {
                        KLevel = GUILayout.Toolbar(KLevel, KLevelStringsOne);
                    }
                    if (ACLevel == 1)
                    {
                        KLevel = GUILayout.Toolbar(KLevel, KLevelStringsTwo);
                    }
                    if (ACLevel == 5)
                    {
                        GUILayout.Label(Localizer.Format("#TRPHire_Level5SandboxOrScience"));
                    }
                }
                GUILayout.EndVertical();

                if (hasKredits == true)
                {
                    GUILayout.BeginHorizontal("window");
                    GUILayout.BeginVertical();
                    int cost = costMath();
                    //GUILayout.FlexibleSpace();
                    string rock = "";
                    if (Orbital.eclipseToday != null)
                    {
                        rock = Orbital.eclipseToday.displayName;
                    }
                    if (rock != "")
                    {
                        if (rock.Substring(rock.Length - 2, 1) == "^")
                        {
                            rock = rock.Substring(0, rock.Length - 2);
                        }
                    }

                    string MaxDiscount  = Localizer.Format("#TRPHire_MaxDiscount", HighLogic.CurrentGame.Parameters.CustomParams <HireSettings3>().max_discount) + "\n";
                    string NewYear      = Localizer.Format("#TRPHire_NewYear") + " ";
                    string BlackMunday  = Localizer.Format("#TRPHire_BlackMunday", rock) + " ";
                    string YourDiscount = Localizer.Format("#TRPHire_YourDiscount", KDiscount * 100) + "\n";
                    string TotalCost    = Localizer.Format("#TRPHire_TotalCost", cost);

                    string msg = (KDiscountOverFlow ? MaxDiscount : "")
                                 + (KDiscount != 0 ? (KNewYear ? NewYear : "") + (KBlackMunday ? BlackMunday : "") + YourDiscount : "")
                                 + TotalCost;
                    if (cost <= Funding.Instance.Funds)
                    {
                        GUILayout.Label(msg, HighLogic.Skin.textField);
                    }
                    else
                    {
                        GUI.color = Color.red;
                        GUILayout.Label(msg, HighLogic.Skin.textField);
                        GUI.color = basecolor;
                    }

                    // GUILayout.FlexibleSpace();
                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();

                if (hTest)
                {
                    if (GUILayout.Button(hireStatus(out hTest), GUILayout.Width(200f)))
                    {
                        if (hTest)
                        {
                            kHire();
                        }
                    }
                }
                if (!hTest)
                {
                    GUILayout.Button(hireStatus(out hTest), GUILayout.Width(250f));
                }

                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();

                GUILayout.EndArea();
            }
        }
Exemple #26
0
        public void updateUpkeep()
        {
            float[] costs;

            // Pad
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.LaunchPad, out costs))
            {
                if (kctResearchRate > 0d)
                {
                    int lC = costs.Length;
                    for (int i = 0; i < padLevels; i++)
                    {
                        padCosts[i] = 0d;
                        if (i < lC)
                        {
                            padCosts[i] = settings.facilityLevelCostMult * kctPadCounts[i] * Math.Pow(costs[i], settings.facilityLevelCostPow);
                        }
                    }
                    padCost = 0;
                    for (int i = padLevels; i-- > 0;)
                    {
                        padCost += padCosts[i];
                    }
                }
                else
                {
                    padCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.LaunchPad) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
                }
            }

            // Runway
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.Runway, out costs))
            {
                runwayCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.Runway) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            //VAB
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.VehicleAssemblyBuilding, out costs))
            {
                vabCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            //SPH
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.SpaceplaneHangar, out costs))
            {
                sphCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            //RnD
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.ResearchAndDevelopment, out costs))
            {
                rndCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.ResearchAndDevelopment) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            // MC
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.MissionControl, out costs))
            {
                mcCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.MissionControl) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            // TS
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.TrackingStation, out costs))
            {
                tsCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            // AC
            if (facilityLevelCosts.TryGetValue(SpaceCenterFacility.AstronautComplex, out costs))
            {
                acCost = settings.facilityLevelCostMult * Math.Pow(costs[(int)(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) * (costs.Length - 0.95f))], settings.facilityLevelCostPow);
            }

            nautYearlyUpkeep = settings.nautYearlyUpkeepBase + ((double)ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) * settings.nautYearlyUpkeepAdd);
            nautUpkeep       = HighLogic.CurrentGame.CrewRoster.GetActiveCrewCount() * nautYearlyUpkeep * (1d / 365d);

            researchUpkeep = kctResearchRate * settings.kctResearchMult;

            totalUpkeep = facilityUpkeep + integrationUpkeep + researchUpkeep + nautUpkeep;
        }
Exemple #27
0
        public void ClobberEngineersReport()
        {
            if (!HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            EnsureLocalizationsCached();

            ShipConstruct ship = EditorLogic.fetch.ship;

            SpaceCenterFacility launchFacility;

            switch (EditorDriver.editorFacility)
            {
            default:
            case EditorFacility.VAB:
                launchFacility = SpaceCenterFacility.LaunchPad;
                break;

            case EditorFacility.SPH:
                launchFacility = SpaceCenterFacility.Runway;
                break;
            }

            bool isLP = launchFacility == SpaceCenterFacility.LaunchPad;
            //partCount = ship.parts.Count;
            //partLimit = GameVariables.Instance.GetPartCountLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(editorFacility), editorFacility == SpaceCenterFacility.VehicleAssemblyBuilding);

            float   totalMass = Utilities.GetShipMass(ship, true, out _, out _);
            Vector3 craftSize = Utilities.GetShipSize(ship, true);

            float   massLimit;
            Vector3 maxSize;

            if (PresetManager.Instance.ActivePreset.GeneralSettings.Enabled && PresetManager.Instance.ActivePreset.GeneralSettings.BuildTimes)
            {
                massLimit = isLP ? KCTGameStates.ActiveKSC.ActiveLPInstance.SupportedMass : GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(launchFacility), false);
                maxSize   = isLP ? KCTGameStates.ActiveKSC.ActiveLPInstance.SupportedSize : GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(launchFacility), false);
            }
            else
            {
                massLimit = GameVariables.Instance.GetCraftMassLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(launchFacility), isLP);
                maxSize   = GameVariables.Instance.GetCraftSizeLimit(ScenarioUpgradeableFacilities.GetFacilityLevel(launchFacility), isLP);
            }

            string neutralColorHex = XKCDColors.HexFormat.KSPNeutralUIGrey;

            //string partCountColorHex = partCount <= partLimit ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;
            //partCountLH.text = partCountLH.text = KSP.Localization.Localizer.Format("#autoLOC_443389", neutralColorHex);

            //if (partLimit < int.MaxValue)
            //{
            //    partCountRH.text = "<color=" + partCountColorHex + ">" + partCount.ToString("0") + " / " + partLimit.ToString("0") + "</color>";
            //}
            //else
            //{
            //    partCountRH.text = "<color=" + partCountColorHex + ">" + partCount.ToString("0") + "</color>";
            //}

            string partMassColorHex = totalMass <= massLimit ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;

            _refERpartMassLH.text = KSP.Localization.Localizer.Format("#autoLOC_443401", neutralColorHex);

            if (massLimit < float.MaxValue)
            {
                _refERpartMassRH.text = KSP.Localization.Localizer.Format("#autoLOC_443405", partMassColorHex, totalMass.ToString("N3"), massLimit.ToString("N1"));
            }
            else
            {
                _refERpartMassRH.text = KSP.Localization.Localizer.Format("#autoLOC_443409", partMassColorHex, totalMass.ToString("N3"));
            }

            string sizeForeAftHex = craftSize.y <= maxSize.y ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;
            string sizeSpanHex    = craftSize.x <= maxSize.x ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;
            string sizeTHgtHex    = craftSize.z <= maxSize.z ? XKCDColors.HexFormat.KSPBadassGreen : XKCDColors.HexFormat.KSPNotSoGoodOrange;


            _refERsizeLH.text = "<line-height=110%><color=" + neutralColorHex + ">" + _cacheAutoLOC_443417 + "</color>\n<color=" +
                                neutralColorHex + ">" + _cacheAutoLOC_443418 + "</color>\n<color=" +
                                neutralColorHex + ">" + _cacheAutoLOC_443419 + "</color>\n<color=" +
                                neutralColorHex + ">" + _cacheAutoLOC_443420 + "</color></line-height>";

            if (maxSize.x < float.MaxValue && maxSize.y < float.MaxValue && maxSize.z < float.MaxValue)
            {
                _refERsizeRH.text =
                    "<line-height=110%>  \n<color=" + sizeForeAftHex + ">" + KSPUtil.LocalizeNumber(craftSize.y, "0.0") + _cacheAutoLOC_7001411 +
                    " / " + KSPUtil.LocalizeNumber(maxSize.y, "0.0") + _cacheAutoLOC_7001411 + "</color>\n<color=" +
                    sizeSpanHex + ">" + KSPUtil.LocalizeNumber(craftSize.x, "0.0") + _cacheAutoLOC_7001411 + " / " +
                    KSPUtil.LocalizeNumber(maxSize.x, "0.0") +
                    _cacheAutoLOC_7001411 + "</color>\n<color=" + sizeTHgtHex + ">" + KSPUtil.LocalizeNumber(craftSize.z, "0.0") + _cacheAutoLOC_7001411 + " / " +
                    KSPUtil.LocalizeNumber(maxSize.z, "0.0") + _cacheAutoLOC_7001411 + "</color></line-height>";
            }
            else
            {
                _refERsizeRH.text = "<line-height=110%> \n<color=" + sizeForeAftHex + ">" + KSPUtil.LocalizeNumber(craftSize.y, "0.0") + _cacheAutoLOC_7001411 +
                                    "</color>\n<color=" + sizeSpanHex + ">" + KSPUtil.LocalizeNumber(craftSize.x, "0.0") + _cacheAutoLOC_7001411 +
                                    "</color>\n<color=" + sizeTHgtHex + ">" + KSPUtil.LocalizeNumber(craftSize.z, "0.0") + _cacheAutoLOC_7001411 + "</color></line-height>";
            }

            bool allGood = //partCount <= partLimit &&
                           totalMass <= massLimit &&
                           craftSize.x <= maxSize.x &&
                           craftSize.y <= maxSize.y &&
                           craftSize.z <= maxSize.z;

            _refERappFrame.header.color = allGood ? XKCDColors.ElectricLime : XKCDColors.Orange;

            if (!allGood)
            {
                EngineersReport.Instance.appLauncherButton.sprite.color = XKCDColors.Orange;
            }
            if (allGood)
            {
                EngineersReport.Instance.appLauncherButton.sprite.color = Color.white;
            }
        }
        protected override void CreateNode()
        {
            if (comm == null)
            {
                comm = new RACommNode(nodeTransform)
                {
                    OnNetworkPreUpdate      = new Action(OnNetworkPreUpdate),
                    isHome                  = true,
                    isControlSource         = true,
                    isControlSourceMultiHop = true
                };
            }
            comm.name        = nodeName;
            comm.displayName = displaynodeName;
            comm.antennaRelay.Update(!isPermanent ? GameVariables.Instance.GetDSNRange(ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.TrackingStation)) : antennaPower, GameVariables.Instance.GetDSNRangeCurve(), false);
//            Vector3d pos = (nodeTransform == null) ? transform.position : nodeTransform.position;
//            body.GetLatLonAlt(pos, out lat, out lon, out alt);

            RACommNode t = comm as RACommNode;

            t.ParentBody = body;
            int tsLevel = RACommNetScenario.GroundStationTechLevel;

            // Config node contains a list of antennas to build.
            t.RAAntennaList = new List <RealAntenna> {
            };
            foreach (ConfigNode antNode in config.GetNodes("Antenna"))
            {
                //Debug.LogFormat("Building an antenna for {0}", antNode);
                int targetLevel = Int32.Parse(antNode.GetValue("TechLevel"));
                if (tsLevel >= targetLevel)
                {
                    RealAntenna ant = new RealAntennaDigital(name)
                    {
                        ParentNode = comm
                    };
                    ant.LoadFromConfigNode(antNode);
                    ant.ProcessUpgrades(tsLevel, antNode);
                    ant.TechLevelInfo = TechLevelInfo.GetTechLevel(tsLevel);
                    t.RAAntennaList.Add(ant);
                }
            }
        }
        protected override void DrawUI()
        {
            var expSituation = ScienceUtil.GetExperimentSituation(FlightGlobals.ActiveVessel);

            GUILayout.BeginVertical();
            {
                var observers = manager.Observers;

                if (observers.All(eo => !eo.Available))
                {
                    GUILayout.Label(Localizer.Format("#ScienceAlert_Available"));//"(no experiments available)"
                }
                else
                {
                    doAll = false;
                    if (GUILayout.Button(Localizer.Format("#ScienceAlert_DeployAll"), Settings.Skin.button))//"Deploy All"
                    {
                        doAll = true;
                        noEva = false;
                    }

                    if (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) > 0 || expSituation == ExperimentSituations.SrfLanded)
                    {
                        if (GUILayout.Button(Localizer.Format("#ScienceAlert_DeployexEVA"), Settings.Skin.button, GUILayout.Height(35)))//"Deploy All except EVA"
                        {
                            doAll = true;
                            noEva = true;
                        }
                    }
                }
                if (AnyAvailableScienceContainers() > 0)
                {
                    if (msc != null && msc.Count > 0)
                    {
                        if (GUILayout.Button(Localizer.Format("#ScienceAlert_CollectAll"), Settings.Skin.button))//"Collect All"
                        {
                            foreach (var m in msc)
                            {
                                m.CollectAllEvent();
                            }
                        }
                    }
                    else
                    {
                        GUI.enabled = false;
                        GUILayout.Button(Localizer.Format("#ScienceAlert_Nocontainers"));//"Collect All (no science containers available)"
                        GUI.enabled = true;
                    }
                }

                if (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.AstronautComplex) == 0 && (expSituation != ExperimentSituations.SrfLanded ||
                                                                                                                  !FlightGlobals.ActiveVessel.mainBody.isHomeWorld))
                {
                    noEva = true;
                }
                //-----------------------------------------------------
                // Experiment list
                //-----------------------------------------------------

                for (int i = observers.Count() - 1; i >= 0; i--)
                {
                    if (observers[i].Available)
                    {
                        var content = new GUIContent(observers[i].ExperimentTitle);
                        color = "";
                        if (!observers[i].rerunnable)
                        {
                            color = lblYellowColor;
                        }
                        if (!observers[i].resettable)
                        {
                            color = lblRedColor;
                        }
                        if (Settings.Instance.ShowReportValue)
                        {
                            content.text += $" ({observers[i].NextReportValue:0.#})";
                        }
                        if (color != "")
                        {
                            content.text = Colorized(color, content.text);
                        }

                        if (noEva && observers[i].Experiment.id == "evaReport")
                        {
                            continue;
                        }
                        if (!doAll && !GUILayout.Button(content, Settings.Skin.button, GUILayout.ExpandHeight(false)))
                        {
                            continue;
                        }

                        Log.Debug("Deploying {0}", observers[i].ExperimentTitle);
                        AudioPlayer.Audio.PlayUI("click2");
                        observers[i].Deploy();
                    }
                }
            }

            GUILayout.EndVertical();
        }
Exemple #30
0
        public void DoAllScience()
        {
            var DMagic = new DMagicFactory();

#if false
            if (Events["DoAllScience"].guiName == "Perform All Science")
            {
                Events["DoAllScience"].guiName = Localizer.Format("#AYA_ANTENNA_UI_SCIENCE_PERFORM_ALL");
            }
#endif
            foreach (Part eachPart in vessel.Parts)                                 //Cycle through each part on the vessel
            {
                foreach (ModuleScienceExperiment thisExperiment
                         in eachPart.FindModulesImplementing <ModuleScienceExperiment>())                                       //Cycle through each ModuleScienceExperiment module in the part
                {
                    if (thisExperiment != null)                                                                                 //Only continue it if it's actually a ModuleScienceExperiment (which it should always be but hey)
                    {
                        if (thisExperiment.experimentActionName == "Take Surface Sample")                                       //If it's a surface sample, we need to make sure it's not locked out.
                        {
                            if (ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.ResearchAndDevelopment) > 0) // Are you allowed to do surface samples? NOTE: 0 is tier 1. 0.5 is tier 2. 1 is tier 3. These could change if more tiers are added.
                            {
                                if (!thisExperiment.Deployed)
                                {
                                    thisExperiment.DeployExperiment(); //Deploy the experiment if it's not already deployed
                                                                       //print ("AYA: Deployed Surface Sample that had not yet been deployed");
                                }
                                //else print ("AYA: Did not deploy Surface Sample as it had previously been deployed.");
                            }
                            //else print ("AYA: Did not deploy Surface Sample as R&D is the lowest tier.");
                        }
                        else if (thisExperiment.experimentID.Substring(0, 3) == "WBI") //If it's a WBI experiment, from M.O.L.E., don't do it becuase those are special.
                        {
                            // Do nothing
                        }
                        else if (!thisExperiment.Deployed)
                        {
                            thisExperiment.DeployExperiment(); //Deploy the experiment if it's not already deployed
                                                               //print ("AYA: Deployed experiment that had not been previously deployed.");
                        }
                        //else print ("AYA: Did not deploy experiment.");
                    }
                }
            }


            Vessel v = FlightGlobals.ActiveVessel;
            _DMModuleScienceAnimates        = null;
            _DMModuleScienceAnimateGenerics = null;
            if (v != null && HighLogic.LoadedScene == GameScenes.FLIGHT)
            {
                _DMModuleScienceAnimates        = v.FindPartModulesImplementing <ModuleScienceExperiment>().Where(x => DMagic.inheritsFromOrIsDMModuleScienceAnimate(x)).ToList();
                _DMModuleScienceAnimateGenerics = v.FindPartModulesImplementing <ModuleScienceExperiment>().Where(x => DMagic.inheritsFromOrIsDMModuleScienceAnimateGeneric(x)).ToList();
            }

            // If possible run with DMagic new API
            if (_DMModuleScienceAnimateGenerics != null && _DMModuleScienceAnimateGenerics.Count > 0)
            {
                DMModuleScienceAnimateGeneric NewDMagicInstance = DMagic.GetDMModuleScienceAnimateGeneric();
                if (NewDMagicInstance != null)
                {
                    IEnumerable <ModuleScienceExperiment> lm;

                    lm = _DMModuleScienceAnimateGenerics.Where(x => (
                                                                   !x.Inoperable &&
                                                                   ((int)x.Fields.GetValue("experimentLimit") > 1 ? NewDMagicInstance.canConduct(x) : NewDMagicInstance.canConduct(x) && (x.rerunnable))
                                                                   ));
                    if (lm != null)
                    {
                        ModuleScienceExperiment m = null;
                        for (int i = 0; i < lm.Count(); i++)
                        {
                            m = lm.ElementAt(i);

                            if (m != null)
                            {
                                //_logger.Debug("Running DMModuleScienceAnimateGenerics Experiment " + m.experimentID + " on part " + m.part.partInfo.name);
                                NewDMagicInstance.gatherScienceData(m);
                            }
                        }
                    }
                }
            }


            // If possible run with DMagic DMAPI
            if (_DMModuleScienceAnimates != null && _DMModuleScienceAnimates.Count > 0)
            {
                DMAPI DMAPIInstance = DMagic.GetDMAPI();
                if (DMAPIInstance != null)
                {
                    IEnumerable <ModuleScienceExperiment> lm;

                    lm = _DMModuleScienceAnimates.Where(x =>
                    {
                        return(!x.Inoperable &&
                               ((int)x.Fields.GetValue("experimentLimit") > 1 ? DMAPIInstance.experimentCanConduct(x) : DMAPIInstance.experimentCanConduct(x) && (x.rerunnable)));
                    });

                    ModuleScienceExperiment m = null;

                    for (int i = 0; i < lm.Count(); i++)
                    {
                        m = lm.ElementAt(i);
                        if (m != null)
                        {
                            //_logger.Trace("Running DMModuleScienceAnimates Experiment " + m.experimentID + " on part " + m.part.partInfo.name);
                            DMAPIInstance.deployDMExperiment(m);
                        }
                    }
                }
            }
        }