Esempio n. 1
0
        void FixName(ProtoCrewMember kerbal)
        {
            if (specialNames.HasValue(kerbal.name.Replace(' ', '_')))
            {
                kerbal.ChangeName(specialNames.GetValue(kerbal.name.Replace(' ', '_')));
            }
            else
            {
                bool coolFirst = false;
                bool coolLast  = false;


                // Cool First
                if (Pick(100) < 20)
                {
                    coolFirst = true;
                    if (kerbal.gender == ProtoCrewMember.Gender.Male)
                    {
                        kerbal.ChangeName(Pick(coolM) + " Kerman");
                    }
                    else
                    {
                        kerbal.ChangeName(Pick(coolF) + " Kerman");
                    }
                }

                // Cool Last
                if (Pick(100) < 20)
                {
                    coolLast = true;
                }

                if (coolLast)
                {
                    kerbal.ChangeName(kerbal.name.Replace("Kerman", Pick(lastCool)));
                }
                else
                {
                    kerbal.ChangeName(kerbal.name.Replace("Kerman", Pick(lastBoring)));
                }


                // Veteran
                if (coolFirst && coolLast)
                {
                    kerbal.veteran = true;
                }
                else
                {
                    kerbal.veteran = false;
                }
            }
        }
Esempio n. 2
0
 //Defends against bug #172
 private void CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(ConfigNode progressTrackingNode)
 {
     foreach (ConfigNode possibleNode in progressTrackingNode.nodes)
     {
         //Recursion (noun): See Recursion.
         CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(possibleNode);
     }
     //The kerbals are kept in a ConfigNode named 'crew', with 'crews' as a comma space delimited array of names.
     if (progressTrackingNode.name == "crew")
     {
         string kerbalNames = progressTrackingNode.GetValue("crews");
         if (!String.IsNullOrEmpty(kerbalNames))
         {
             string[] kerbalNamesSplit = kerbalNames.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
             foreach (string kerbalName in kerbalNamesSplit)
             {
                 if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
                 {
                     DarkLog.Debug("Generating missing kerbal from ProgressTracking: " + kerbalName);
                     ProtoCrewMember pcm = CrewGenerator.RandomCrewMemberPrototype(ProtoCrewMember.KerbalType.Crew);
                     pcm.ChangeName(kerbalName);
                     HighLogic.CurrentGame.CrewRoster.AddCrewMember(pcm);
                     //Also send it off to the server
                     vesselWorker.SendKerbalIfDifferent(pcm);
                 }
             }
         }
     }
 }
Esempio n. 3
0
 public void GenerateKerbal()
 {
     _pcm        = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(kerbalType);
     _pcm.gender = gender;
     _pcm.ChangeName(name);
     _pcm.trait = experienceTrait;
     KerbalRoster.SetExperienceTrait(_pcm, experienceTrait);
 }
Esempio n. 4
0
        public static void RerollKerbal(ref ProtoCrewMember kerbal, bool generateNewStats, bool useBellCurveMethod, bool dontInsultMe, float badassPercent, float femalePercent, Culture[] cultures, bool keepRoles)
        {
            LogUtils.Log("Rerolling kerbal ", kerbal.name);
            UnityEngine.Random.InitState(System.DateTime.Now.Millisecond * kerbal.name.GetHashCode());

            if (kerbal.type == ProtoCrewMember.KerbalType.Crew || kerbal.type == ProtoCrewMember.KerbalType.Applicant)
            {
                // generate some new stats
                if (generateNewStats)
                {
                    kerbal.stupidity = rollStupidity(useBellCurveMethod, dontInsultMe);
                    kerbal.courage   = rollCourage(useBellCurveMethod);
                    kerbal.isBadass  = (UnityEngine.Random.Range(0.0f, 1.0f) < badassPercent);


                    float rand = UnityEngine.Random.Range(0.0f, 1.0f);
                    if (keepRoles)
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, kerbal.trait);
                    }
                    else
                    {
                        if (rand < 0.33f)
                        {
                            KerbalRoster.SetExperienceTrait(kerbal, "Pilot");
                        }
                        else if (rand < 0.66f)
                        {
                            KerbalRoster.SetExperienceTrait(kerbal, "Engineer");
                        }
                        else
                        {
                            KerbalRoster.SetExperienceTrait(kerbal, "Scientist");
                        }
                    }

                    if (UnityEngine.Random.Range(0.0f, 1.0f) <= femalePercent)
                    {
                        kerbal.gender = ProtoCrewMember.Gender.Female;
                    }
                    else
                    {
                        kerbal.gender = ProtoCrewMember.Gender.Male;
                    }
                }
            }

            string name = getName(kerbal, cultures);

            LogUtils.Log("Renaming to ", name);
            if (name.Length > 0)
            {
                kerbal.ChangeName(name);
            }
        }
 public void CreateKerbalIfMissing(string kerbalName, Guid vesselID)
 {
     if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
     {
         ProtoCrewMember pcm = CrewGenerator.RandomCrewMemberPrototype(ProtoCrewMember.KerbalType.Crew);
         pcm.ChangeName(kerbalName);
         pcm.rosterStatus = ProtoCrewMember.RosterStatus.Assigned;
         HighLogic.CurrentGame.CrewRoster.AddCrewMember(pcm);
         DarkLog.Debug("Created kerbal " + pcm.name + " for vessel " + vesselID + ", Kerbal was missing");
     }
 }
        void generateCrew(string kerbalTrait, ProtoCrewMember.Gender gender)
        {
            ProtoCrewMember crew = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Crew);

            while (crew.trait != kerbalTrait)
            {
                crew = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Crew);
            }
            crew.ChangeName(crewName);
            crew.type            = ProtoCrewMember.KerbalType.Crew;
            crew.gender          = gender;
            crew.experienceLevel = 5;
            FlightLog flight = new FlightLog();

            flight.AddEntry("Land,Eeloo");
            flight.AddEntry("Land,Dres");
            flight.AddEntry("Land,Pol");
            flight.AddEntry("Land,Gilly");
            flight.AddEntry("Land,Tylo");
            flight.AddEntry("Land,Bop");
            flight.AddEntry("Land,Vall");
            flight.AddEntry("Land,Laythe");
            crew.careerLog.AddFlight();
            for (int i = flight.Entries.Count - 1; i >= 0; --i)
            {
                FlightLog.Entry entries = flight.Entries[i];
                crew.careerLog.AddEntry(entries);
            }
            for (int i = FlightGlobals.Vessels.Count - 1; i >= 0; --i)
            {
                Vessel vessel = FlightGlobals.Vessels[i];
                if (vessel.vesselName == "Kerbin Station")
                {
                    for (int j = vessel.Parts.Count - 1; j >= 0; --j)
                    {
                        Part part = vessel.Parts[j];
                        if (part.protoModuleCrew.Count < part.CrewCapacity)
                        {
                            part.AddCrewmember(crew);
                            part.Actions.part.SpawnIVA();
                            CameraManager.Instance.SetCameraMap();
                            CameraManager.Instance.SetCameraFlight();
                            break;
                        }
                    }
                    break;
                }
            }
        }
 static void SetCustomKerbal(ProtoCrewMember kerbal, string name, ProtoCrewMember.Gender gender, string trait, bool veteran, bool isBadass, float courage, float stupidity)
 {
     kerbal.ChangeName(name);
     kerbal.gender = gender;
     kerbal.type   = veteran ? ProtoCrewMember.KerbalType.Crew : ProtoCrewMember.KerbalType.Applicant;
     KerbalRoster.SetExperienceTrait(kerbal, trait);
     kerbal.veteran   = veteran;
     kerbal.isBadass  = isBadass;
     kerbal.courage   = courage;
     kerbal.stupidity = stupidity;
     if (HighLogic.CurrentGame.Mode != Game.Modes.CAREER)
     {
         kerbal.experienceLevel = 5;
         kerbal.experience      = 99999;
     }
 }
Esempio n. 8
0
        private void GoToIBV(ProtoCrewMember k)
        {
            this.showGui = false;
            GameObject intHatch = new GameObject("intHatch");

            intHatch.transform.position = base.part.partTransform.TransformPoint(new Vector3(0f, 0f, -1.5f));
            //ProtoCrewMember intEva = new ProtoCrewMember(HighLogic.CurrentGame.Mode, k);
            ProtoCrewMember intEva  = new ProtoCrewMember(k);
            ProtoCrewMember expr_55 = intEva;

            expr_55.ChangeName(expr_55.name + "int");
            if (FlightEVA.fetch.spawnEVA(intEva, base.vessel.rootPart, intHatch.transform))
            {
                FlightCamera.fetch.SetDistanceImmediate(2f);
            }
        }
Esempio n. 9
0
        private void RerollKerbal(ProtoCrewMember kerbal)
        {
            UnityEngine.Random.InitState(System.DateTime.Now.Millisecond * kerbal.name.GetHashCode());

            if (generateNewStats)
            {
                if (kerbal.type == ProtoCrewMember.KerbalType.Crew || kerbal.type == ProtoCrewMember.KerbalType.Applicant)
                {
                    // generate some new stats
                    kerbal.stupidity = rollStupidity();
                    kerbal.courage   = rollCourage();
                    kerbal.isBadass  = (UnityEngine.Random.Range(0.0f, 1.0f) < badassPercent);

                    float rand = UnityEngine.Random.Range(0.0f, 1.0f);
                    if (rand < 0.33f)
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, "Pilot");
                    }
                    else if (rand < 0.66f)
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, "Engineer");
                    }
                    else
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, "Scientist");
                    }

                    if (UnityEngine.Random.Range(0.0f, 1.0f) < femalePercent)
                    {
                        kerbal.gender = ProtoCrewMember.Gender.Female;
                    }
                    else
                    {
                        kerbal.gender = ProtoCrewMember.Gender.Male;
                    }
                }
            }

            string name = this.getName(kerbal);

            if (name.Length > 0)
            {
                kerbal.ChangeName(name);
            }
        }
Esempio n. 10
0
        private void CreateMissingTourists(ConfigNode contractSystemNode)
        {
            ConfigNode contractsNode = contractSystemNode.GetNode("CONTRACTS");

            foreach (ConfigNode contractNode in contractsNode.GetNodes("CONTRACT"))
            {
                if (contractNode.GetValue("type") == "TourismContract" && contractNode.GetValue("state") == "Active")
                {
                    foreach (ConfigNode paramNode in contractNode.GetNodes("PARAM"))
                    {
                        foreach (string kerbalName in paramNode.GetValues("kerbalName"))
                        {
                            DarkLog.Debug("Spawning missing tourist (" + kerbalName + ") for active tourism contract");
                            ProtoCrewMember pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);
                            pcm.ChangeName(kerbalName);
                        }
                    }
                }
            }
        }
 public void CreateKerbalIfMissing(string kerbalName, Guid vesselID)
 {
     if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
     {
         if (AddCrewMemberToRoster == null)
         {
             MethodInfo addMemberToCrewRosterMethod = typeof(KerbalRoster).GetMethod("AddCrewMember", BindingFlags.Public | BindingFlags.Instance);
             AddCrewMemberToRoster = (AddCrewMemberToRosterDelegate)Delegate.CreateDelegate(typeof(AddCrewMemberToRosterDelegate), HighLogic.CurrentGame.CrewRoster, addMemberToCrewRosterMethod);
             if (AddCrewMemberToRoster == null)
             {
                 throw new Exception("Failed to load AddCrewMember delegate!");
             }
         }
         ProtoCrewMember pcm = CrewGenerator.RandomCrewMemberPrototype(ProtoCrewMember.KerbalType.Crew);
         pcm.ChangeName(kerbalName);
         pcm.rosterStatus = ProtoCrewMember.RosterStatus.Assigned;
         AddCrewMemberToRoster(pcm);
         DarkLog.Debug("Created kerbal " + pcm.name + " for vessel " + vesselID + ", Kerbal was missing");
     }
 }
        protected ProtoCrewMember createTourist(string kerbalName = null)
        {
            KerbalRoster    roster     = HighLogic.CurrentGame.CrewRoster;
            string          message    = string.Empty;
            ProtoCrewMember newRecruit = roster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);

            if (!string.IsNullOrEmpty(kerbalName))
            {
                newRecruit.ChangeName(kerbalName);
            }
            Log("Created new tourist: " + newRecruit.name);

            newRecruit.rosterStatus = ProtoCrewMember.RosterStatus.Available;

            //Game events
            newRecruit.UpdateExperience();
            roster.Update(Planetarium.GetUniversalTime());
            GameEvents.onKerbalAdded.Fire(newRecruit);

            return(newRecruit);
        }
Esempio n. 13
0
        private void onKerbalAdd(ProtoCrewMember crew)
        {
            if (crew.type != ProtoCrewMember.KerbalType.Applicant)
            {
                return;
            }
            if (crew.name.GetHashCode() % 3 != 0)
            {
                return;
            }

            foreach (var name in HeadSwitchConfiguration.Instance.headNames)
            {
                if (!game.CrewRoster.Exists(name))
                {
                    crew.ChangeName(name);
                    SwitchHead(crew);
                    break;
                }
            }
        }
Esempio n. 14
0
 //Defends against bug #172
 private void CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(ConfigNode progressTrackingNode)
 {
     foreach (ConfigNode possibleNode in progressTrackingNode.nodes)
     {
         //Recursion (noun): See Recursion.
         CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(possibleNode);
     }
     //The kerbals are kept in a ConfigNode named 'crew', with 'crews' as a comma space delimited array of names.
     if (progressTrackingNode.name == "crew")
     {
         string kerbalNames = progressTrackingNode.GetValue("crews");
         if (!String.IsNullOrEmpty(kerbalNames))
         {
             string[] kerbalNamesSplit = kerbalNames.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
             foreach (string kerbalName in kerbalNamesSplit)
             {
                 if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
                 {
                     if (AddCrewMemberToRoster == null)
                     {
                         MethodInfo addMemberToCrewRosterMethod = typeof(KerbalRoster).GetMethod("AddCrewMember", BindingFlags.Public | BindingFlags.Instance);
                         AddCrewMemberToRoster = (AddCrewMemberToRosterDelegate)Delegate.CreateDelegate(typeof(AddCrewMemberToRosterDelegate), HighLogic.CurrentGame.CrewRoster, addMemberToCrewRosterMethod);
                     }
                     if (AddCrewMemberToRoster == null)
                     {
                         throw new Exception("Failed to initialize AddCrewMemberToRoster for #172 ProgressTracking fix.");
                     }
                     DarkLog.Debug("Generating missing kerbal from ProgressTracking: " + kerbalName);
                     ProtoCrewMember pcm = CrewGenerator.RandomCrewMemberPrototype(ProtoCrewMember.KerbalType.Crew);
                     pcm.ChangeName(kerbalName);
                     AddCrewMemberToRoster(pcm);
                     //Also send it off to the server
                     VesselWorker.fetch.SendKerbalIfDifferent(pcm);
                 }
             }
         }
     }
 }
Esempio n. 15
0
        //Gets a new kerbal and sets his/her stats based on whether there is already a Kerbal of that name or not, or if the person wants o override that check
        private void SpawnKerbal(int count, bool overrideState)
        {
            if (exists && overrideState == false)
            {
                warningState = true;
            }
            else
            {
                newKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal();
                newKerbal.ChangeName(stringToEdit);
                newKerbal.courage   = sliderValue;
                newKerbal.stupidity = sliderValue2;
                newKerbal.isBadass  = buttonState;
                newKerbal.veteran   = veteran;

                KerbalRoster.SetExperienceTrait(newKerbal, Trait);

                //Find out and set the gender
                if (male == false)
                {
                    newKerbal.gender = ProtoCrewMember.Gender.Female;
                }
                if (male)
                {
                    newKerbal.gender = ProtoCrewMember.Gender.Male;
                }

                if (closeOnComplete)
                {
                    appLauncherButton.SetFalse(true);
                    ScreenMessages.PostScreenMessage("Kustom Kerbal Spawned, closing window...", 1, ScreenMessageStyle.UPPER_CENTER);
                }
                else
                {
                    ScreenMessages.PostScreenMessage("Kustom Kerbal Spawned.", 1, ScreenMessageStyle.UPPER_CENTER);
                }
            }
        }
Esempio n. 16
0
        private void kHire()
        {
            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                double myFunds = Funding.Instance.Funds;
                Funding.Instance.AddFunds(-costMath(), TransactionReasons.CrewRecruited);
                Hire.Log.Info("KSI :: Total Funds removed " + costMath());
            }

            for (int i = 0; i < KBulki; i++)
            {
                ProtoCrewMember newKerb = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Crew);

                newKerb.ChangeName(KNames[KGender, i]);

                switch (KGender) // Sets gender
                {
                case 0: newKerb.gender = ProtoCrewMember.Gender.Male; break;

                case 1: newKerb.gender = ProtoCrewMember.Gender.Female; break;

                case 2: newKerb.gender = KNames2Gender[i]; break;

                default: break;
                }

                string career = traits.KCareerStrings[KCareer];
                // Sets the kerbal's career based on the KCareer switch.
                KerbalRoster.SetExperienceTrait(newKerb, career);

                // Hire.Log.Info("KSI :: KIA MIA Stat is: " + KDead);
                // Hire.Log.Info("KSI :: " + newKerb.experienceTrait.TypeName + " " + newKerb.name + " has been created in: " + loopcount.ToString() + " loops.");
                newKerb.rosterStatus    = ProtoCrewMember.RosterStatus.Available;
                newKerb.experience      = 0;
                newKerb.experienceLevel = 0;
                newKerb.courage         = KCourage / 100;
                newKerb.stupidity       = KStupidity / 100;
                if (KFearless)
                {
                    newKerb.isBadass = true;
                }

                if (KVeteran)
                {
                    newKerb.veteran = true;
                }

                // Hire.Log.Info("PSH :: Status set to Available, courage and stupidity set, fearless trait set.");

                if (KLevel == 1)
                {
                    newKerb.flightLog.AddEntry("Training1," + FlightGlobals.GetHomeBodyName());
                    newKerb.ArchiveFlightLog();
                    newKerb.experience      = 2;
                    newKerb.experienceLevel = 1;
                    // Hire.Log.Info("KSI :: Level set to 1.");
                }
                if (KLevel == 2)
                {
                    newKerb.flightLog.AddEntry("Training2," + FlightGlobals.GetHomeBodyName());
                    newKerb.ArchiveFlightLog();
                    newKerb.experience      = 8;
                    newKerb.experienceLevel = 2;
                    // Hire.Log.Info("KSI :: Level set to 2.");
                }
                if (ACLevel == 5 || kerExp == false)
                {
                    newKerb.experience      = 9999;
                    newKerb.experienceLevel = 5;
                    Hire.Log.Info("KSI :: Level set to 5 - Non-Career Mode default.");
                }
                GameEvents.onKerbalAdded.Fire(newKerb);       // old gameevent most likely to be used by other mods
                GameEvents.onKerbalAddComplete.Fire(newKerb); // new gameevent that seems relevant
            }
            // Refreshes the AC so that new kerbal shows on the available roster.
            Hire.Log.Info("PSH :: Hiring Function Completed.");


            GameEvents.onGUIAstronautComplexDespawn.Fire();
            GameEvents.onGUIAstronautComplexSpawn.Fire();
        }
Esempio n. 17
0
        public void OnKerbalAdded(ProtoCrewMember kerbal)
        {         //this is the part irishman changed
            List <string> originalNames = new List <string> {
                "Jebediah Kerman",
                "Bill Kerman",
                "Bob Kerman",
                "Valentina Kerman"
            };

            if (preserveOriginals)
            {
                foreach (string originalKerbalName in originalNames)
                {
                    if (HighLogic.CurrentGame.CrewRoster[originalKerbalName] != null)
                    {
                        ProtoCrewMember origKerbal = HighLogic.CurrentGame.CrewRoster[originalKerbalName];
                        if (origKerbal.name == "Jebediah Kerman")
                        {
                            origKerbal.ChangeName("Jebediah Gaelan");
                        }
                        if (origKerbal.name == "Bill Kerman")
                        {
                            origKerbal.ChangeName("Bill Gaelan");
                        }
                        if (origKerbal.name == "Bob Kerman")
                        {
                            origKerbal.ChangeName("Bob Gaelan");
                        }
                        if (origKerbal.name == "Valentina Kerman")
                        {
                            origKerbal.ChangeName("Valentina Gaelan");
                        }
                    }
                }
            }
            else             /* see if any of the originals are still around */
            {
                foreach (string originalKerbalName in originalNames)
                {
                    if (HighLogic.CurrentGame.CrewRoster[originalKerbalName] != null)
                    {
                        ProtoCrewMember origKerbal = HighLogic.CurrentGame.CrewRoster[originalKerbalName];
                        if (origKerbal.name == "Jebediah Kerman")
                        {
                            origKerbal.ChangeName("Galileo Gaelan");
                        }
                        if (origKerbal.name == "Bill Kerman")
                        {
                            origKerbal.ChangeName("Jade Gaelan");
                        }
                        if (origKerbal.name == "Bob Kerman")
                        {
                            origKerbal.ChangeName("Bobert Gaelan");
                        }
                        if (origKerbal.name == "Valentina Kerman")
                        {
                            origKerbal.ChangeName("Poody Gaelan");
                        }
                    }
                }
            }
            RerollKerbal(kerbal);
        }
Esempio n. 18
0
        public void ImportVessel(string name)
        {
            if (System.IO.File.Exists(name))
            {
                Log($"Importing vessel: {name}");
                ConfigNode storedNode = ConfigNode.Load(name);

                ConfigNode vesselNode = storedNode.GetNode("VESSEL");

                vesselNode.SetValue("pid", Guid.NewGuid().ToString());

                if (WarnOfInvalidParts(vesselNode, true))
                {
                    return;
                }

                List <ProtoCrewMember> crewAdded = new List <ProtoCrewMember>();

                if (!_includeCrew)
                {
                    //clear out all crew on vessel
                    StripCrew(vesselNode);
                }
                else
                {
                    //create crewmembers if they don't exist, set all of them to assigned
                    try
                    {
                        foreach (ConfigNode partNode in vesselNode.GetNodes("PART"))
                        {
                            if (partNode.HasValue("crew"))
                            {
                                List <string> toRemove = new List <string>();
                                foreach (ConfigNode.Value crewValue in partNode.values)//(string crewmember in partNode.GetValues("crew"))
                                {
                                    if (crewValue.name != "crew")
                                    {
                                        continue;
                                    }

                                    string crewmember = crewValue.value;
                                    //find the confignode saved with the vessel
                                    ConfigNode crewNode = storedNode.GetNodes("CREW")?.FirstOrDefault(c => c.GetValue("name") == crewmember);
                                    if (crewNode == null || crewNode.GetValue("type") != "Crew") //if no data or is tourist then remove from ship
                                    {
                                        //can't find the required data, so remove that kerbal from the ship
                                        Log($"Vessel occupant is not crew: {crewmember}");
                                        toRemove.Add(crewmember);
                                        continue;
                                    }


                                    ProtoCrewMember newCrew = new ProtoCrewMember(HighLogic.CurrentGame.Mode, crewNode, ProtoCrewMember.KerbalType.Crew);
                                    if (HighLogic.CurrentGame.CrewRoster.Exists(crewmember)) //there's already a kerbal with that name (sadness :( )
                                    {
                                        //alright, rename this kerbal to a new name
                                        string newName = RenameKerbal(crewmember);
                                        newCrew.ChangeName(newName);
                                        crewValue.value = newName;
                                    }
                                    Log($"Creating crewmember {newCrew.name}");
                                    //add the crew member to the crew roster
                                    //the function to do this is hidden for some reason. yay!
                                    HighLogic.CurrentGame.CrewRoster.AddCrewMember(newCrew); //no longer hidden! MORE YAY!
                                    crewAdded.Add(newCrew);
                                }
                                foreach (string crewmember in toRemove) //remove all crews that shouldn't be here anymore
                                {
                                    //find the value with this kerbal and remove it
                                    foreach (ConfigNode.Value val in partNode.values)
                                    {
                                        if (val.name == "crew" && val.value == crewmember)
                                        {
                                            Log($"Removing non-valid crew member {val.value}");
                                            partNode.values.Remove(val);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log("Encountered exception while transferring crew. The exception follows. Stripping crew data.");
                        Debug.LogException(ex);

                        StripCrew(vesselNode);

                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "errorPopup", "Error Occurred",
                                                     "Unable to import crew. An exception occurred and has been logged.",
                                                     "Ok", false, HighLogic.UISkin);

                        return;
                    }
                }

                ProtoVessel addedVessel = HighLogic.CurrentGame.AddVessel(vesselNode);
                foreach (ProtoCrewMember crew in crewAdded)
                {
                    Log($"Assigning {crew.name}");
                    addedVessel.AddCrew(crew);
                }
                //In 1.2.2+ saving fails when there are two copies of a ship with crew onboard both. Might be part ID related.
                //All I know is that if I terminate the original flight, I can import crew. Otherwise it NREs when it tries to save the flight state.
            }
        }
Esempio n. 19
0
        private void OnContractAccepted(Contract contract)
        {
            DarkLog.Debug("Contract accepted, state: " + contract.ContractState);
            ConfigNode contractNode = new ConfigNode();

            contract.Save(contractNode);

            if (contractNode.GetValue("type") == "RecoverAsset")
            {
                string kerbalName   = contractNode.GetValue("kerbalName").Trim();
                int    kerbalGender = int.Parse(contractNode.GetValue("gender"));
                uint   partID       = uint.Parse(contractNode.GetValue("partID"));

                if (!string.IsNullOrEmpty(kerbalName))
                {
                    ProtoCrewMember rescueKerbal = null;
                    if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
                    {
                        DarkLog.Debug("Generating missing kerbal " + kerbalName + " for rescue contract");

                        rescueKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
                        rescueKerbal.ChangeName(kerbalName);
                        rescueKerbal.gender       = (ProtoCrewMember.Gender)kerbalGender;
                        rescueKerbal.rosterStatus = ProtoCrewMember.RosterStatus.Assigned;
                    }
                    else
                    {
                        rescueKerbal = HighLogic.CurrentGame.CrewRoster[kerbalName];
                        DarkLog.Debug("Kerbal " + kerbalName + " already exists, skipping respawn");
                    }
                    if (rescueKerbal != null)
                    {
                        vesselWorker.SendKerbalIfDifferent(rescueKerbal);
                    }
                }

                if (partID != 0)
                {
                    Vessel contractVessel = FinePrint.Utilities.VesselUtilities.FindVesselWithPartIDs(new List <uint> {
                        partID
                    });
                    if (contractVessel != null)
                    {
                        vesselWorker.SendVesselUpdateIfNeeded(contractVessel);
                    }
                }
            }

            else if (contractNode.GetValue("type") == "TourismContract")
            {
                string tourists = contractNode.GetValue("tourists");
                if (tourists != null)
                {
                    string[] touristsNames = tourists.Split(new char[] { '|' });
                    foreach (string touristName in touristsNames)
                    {
                        ProtoCrewMember pcm = null;
                        if (!HighLogic.CurrentGame.CrewRoster.Exists(touristName))
                        {
                            DarkLog.Debug("Spawning missing tourist " + touristName + " for tourism contract");
                            pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);
                            pcm.rosterStatus = ProtoCrewMember.RosterStatus.Available;
                            pcm.ChangeName(touristName);
                        }
                        else
                        {
                            DarkLog.Debug("Skipped respawn of existing tourist " + touristName);
                            pcm = HighLogic.CurrentGame.CrewRoster[touristName];
                        }
                        if (pcm != null)
                        {
                            vesselWorker.SendKerbalIfDifferent(pcm);
                        }
                    }
                }
            }
        }
        void DrawGUISlaves(int windowID)
        {
            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Hello! When trafficking slaves, make sure the police don't find out!", HighLogic.Skin.label);
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Male  " + "      Price: " + slavePrice.ToString(), HighLogic.Skin.label);
            if (GUILayout.Button("Buy Slave", HighLogic.Skin.button))
            {
                if (Funding.Instance.Funds < 1000)
                {
                    ScreenMessages.PostScreenMessage("Not enough eunds", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                }
                else
                {
                    Funding.Instance.AddFunds(-slavePrice, TransactionReasons.CrewRecruited);
                    ProtoCrewMember slave = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);
                    slave.ChangeName(CrewGenerator.GetRandomName(ProtoCrewMember.Gender.Male) + " (slave)");
                    slave.gender    = ProtoCrewMember.Gender.Male;
                    slave.courage   = 1;
                    slave.stupidity = 1;
                    slave.isBadass  = true;
                    foreach (Part CrewPart in vessel.Parts)
                    {
                        if (CrewPart.protoModuleCrew.Count < CrewPart.CrewCapacity)
                        {
                            CrewPart.AddCrewmemberAt(slave, CrewPart.protoModuleCrew.Count);
                            CrewPart.SpawnIVA();
                            if (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Flight)
                            {
                                CameraManager.Instance.SetCameraMap();
                                CameraManager.Instance.SetCameraFlight();
                            }

                            break;
                        }
                    }

                    ScreenMessages.PostScreenMessage("New Slave Added (male)", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                }
            }
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label("Female" + "      Price: " + slavePrice.ToString(), HighLogic.Skin.label);
            if (GUILayout.Button("Buy Slave", HighLogic.Skin.button))
            {
                if (Funding.Instance.Funds < 900)
                {
                    ScreenMessages.PostScreenMessage("Not enough funds", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                }
                else
                {
                    Funding.Instance.AddFunds(-slavePrice, TransactionReasons.CrewRecruited);
                    ProtoCrewMember slave = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);
                    slave.type = ProtoCrewMember.KerbalType.Tourist;
                    slave.ChangeName(CrewGenerator.GetRandomName(ProtoCrewMember.Gender.Female) + " (slave)");
                    slave.gender    = ProtoCrewMember.Gender.Female;
                    slave.courage   = 1;
                    slave.stupidity = 1;
                    slave.isBadass  = true;
                    foreach (Part CrewPart in vessel.Parts)
                    {
                        if (CrewPart.protoModuleCrew.Count < CrewPart.CrewCapacity)
                        {
                            CrewPart.AddCrewmemberAt(slave, CrewPart.protoModuleCrew.Count);
                            CrewPart.SpawnIVA();
                            if (CameraManager.Instance.currentCameraMode != CameraManager.CameraMode.Flight)
                            {
                                CameraManager.Instance.SetCameraFlight();
                            }
                            CameraManager.Instance.SetCameraMap();
                            CameraManager.Instance.SetCameraFlight();

                            break;
                        }
                    }
                    ScreenMessages.PostScreenMessage("New Slave Added (female)", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                }
            }
            GUILayout.EndHorizontal();
            GUILayout.Label("Sell Slaves:", HighLogic.Skin.label);

            scrollPos = GUILayout.BeginScrollView(scrollPos, HighLogic.Skin.scrollView);
            foreach (Part vPart in vessel.Parts)
            {
                foreach (ProtoCrewMember slaves in vPart.protoModuleCrew)
                {
                    if (slaves.type == ProtoCrewMember.KerbalType.Tourist)
                    {
                        GUILayout.BeginHorizontal();
                        GUILayout.Label("Name: " + slaves.name, HighLogic.Skin.label);
                        GUILayout.Label("Gender: " + slaves.gender.ToString());
                        GUILayout.Label("Price: " + slavePrice.ToString());
                        if (GUILayout.Button("Sell", HighLogic.Skin.button))
                        {
                            ScreenMessages.PostScreenMessage("Slave selled", 5.0f, ScreenMessageStyle.UPPER_CENTER);
                            Funding.Instance.AddFunds(slavePrice, TransactionReasons.CrewRecruited);
                            vPart.protoModuleCrew.Remove(slaves);
                            vPart.DespawnIVA();
                            if (CameraManager.Instance.currentCameraMode != CameraManager.CameraMode.Flight)
                            {
                                CameraManager.Instance.SetCameraFlight();
                            }
                            CameraManager.Instance.SetCameraMap();
                            CameraManager.Instance.SetCameraFlight();
                            vPart.SpawnIVA();
                            if (CameraManager.Instance.currentCameraMode != CameraManager.CameraMode.Flight)
                            {
                                CameraManager.Instance.SetCameraFlight();
                            }
                            CameraManager.Instance.SetCameraMap();
                            CameraManager.Instance.SetCameraFlight();
                            break;
                        }
                        GUILayout.EndHorizontal();
                    }
                }
            }

            GUILayout.EndScrollView();
            if (GUILayout.Button("Close", HighLogic.Skin.button))
            {
                slaveWindow         = false;
                MainMenu.menuWindow = true;
                foreach (Part parts in vessel.Parts)
                {
                    parts.SpawnIVA();
                    if (CameraManager.Instance.currentCameraMode != CameraManager.CameraMode.Flight)
                    {
                        CameraManager.Instance.SetCameraFlight();
                    }
                    CameraManager.Instance.SetCameraMap();
                    CameraManager.Instance.SetCameraFlight();
                }
            }
            GUILayout.EndVertical();
        }
Esempio n. 21
0
        public void ImportVessel(string name)
        {
            if (System.IO.File.Exists(name))
            {
                ConfigNode storedNode = ConfigNode.Load(name);

                ConfigNode vesselNode = storedNode.GetNode("VESSEL");

                vesselNode.SetValue("pid", Guid.NewGuid().ToString());

                List <string> invalidParts = InvalidParts(vesselNode);
                if (invalidParts.Count > 0) //contains invalid parts and can't be loaded
                {
                    string msg = "The selected vessel cannot be imported because it contains the following invalid parts (perhaps you removed a mod?):\n";
                    foreach (string invalid in invalidParts)
                    {
                        msg += "    " + invalid + "\n";
                    }
                    PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Missing Parts", msg, "Ok", false, HighLogic.UISkin);
                    return;
                }



                if (!includeCrew)
                {
                    //clear out all crew on vessel
                    StripCrew(vesselNode);
                }
                else
                {
                    //create crewmembers if they don't exist, set all of them to assigned
                    try
                    {
                        foreach (ConfigNode partNode in vesselNode.GetNodes("PART"))
                        {
                            if (partNode.HasValue("crew"))
                            {
                                List <string> toRemove = new List <string>();
                                foreach (ConfigNode.Value crewValue in partNode.values)//(string crewmember in partNode.GetValues("crew"))
                                {
                                    if (crewValue.name != "crew")
                                    {
                                        continue;
                                    }
                                    string crewmember = crewValue.value;
                                    //find the confignode saved with the vessel
                                    ConfigNode crewNode = storedNode.GetNodes("CREW")?.FirstOrDefault(c => c.GetValue("name") == crewmember);
                                    if (crewNode == null || crewNode.GetValue("type") != "Crew") //if no data or is tourist then remove from ship
                                    {
                                        //can't find the required data, so remove that kerbal from the ship
                                        toRemove.Add(crewmember);
                                        continue;
                                    }


                                    ProtoCrewMember newCrew = new ProtoCrewMember(HighLogic.CurrentGame.Mode, crewNode, ProtoCrewMember.KerbalType.Crew);
                                    if (HighLogic.CurrentGame.CrewRoster.Crew.FirstOrDefault(c => c.name == crewmember) != null) //there's already a kerbal with that name (sadness :( )
                                    {
                                        //alright, rename this kerbal to a new name
                                        string newName = RenameKerbal(crewmember);
                                        newCrew.ChangeName(newName);
                                        crewValue.value = newName;
                                    }
                                    //add the crew member to the crew roster
                                    //the function to do this is hidden for some reason. yay!
                                    HighLogic.CurrentGame.CrewRoster.AddCrewMember(newCrew); //no longer hidden! MORE YAY!
                                }
                                foreach (string crewmember in toRemove)                      //remove all crews that shouldn't be here anymore
                                {
                                    //find the value with this kerbal and remove it
                                    foreach (ConfigNode.Value val in partNode.values)
                                    {
                                        if (val.name == "crew" && val.value == crewmember)
                                        {
                                            partNode.values.Remove(val);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.Log("[ShipSaveSplicer] Encountered exception while transferring crew. The exception follows. Stripping crew data.");
                        Debug.LogException(ex);

                        StripCrew(vesselNode);

                        PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), "Error Occurred",
                                                     "Unable to import crew. An exception occurred and has been logged.",
                                                     "Ok", false, HighLogic.UISkin);

                        return;
                    }
                }

                ProtoVessel addedVessel = HighLogic.CurrentGame.AddVessel(vesselNode);
                //we might have to assign the kerbals to the vessel here

                //related issue, in 1.2.2 (at least) we fail validation of assignments when there are two ships with the same part ids (guessing).
                //All I know is that if I terminate the original flight, I can import crew. Otherwise it NREs when I save.
            }
        }
Esempio n. 22
0
        private void GenerateStrandedKerbal(ConfigNode contractNode)
        {
            if (contractNode.GetValue("state") == "Active")
            {
                DarkLog.Debug("Generating stranded kerbal/compound contract");
                int recoveryType     = int.Parse(contractNode.GetValue("recoveryType"));
                int bodyID           = int.Parse(contractNode.GetValue("targetBody"));
                int recoveryLocation = int.Parse(contractNode.GetValue("recoveryLocation"));
                int contractSeed     = int.Parse(contractNode.GetValue("seed"));

                bool recoveringKerbal = recoveryType == 1 || recoveryType == 3;
                bool recoveringPart   = recoveryType == 2 || recoveryType == 3;

                System.Random generator = new System.Random(contractSeed);

                // RECOVERY TYPES:
                // 0: None
                // 1: Kerbal
                // 2: Part
                // 3: Compound

                // Generate vessel part
                string        partName         = contractNode.GetValue("partName");
                string[]      contractValues   = contractNode.GetValue("values").Split(',');
                double        contractDeadline = double.Parse(contractValues[1]);
                uint          newPartID        = uint.Parse(contractNode.GetValue("partID"));
                CelestialBody contractBody     = FlightGlobals.Bodies[bodyID];

                List <string> vesselDescriptionList;
                if (recoveringKerbal)
                {
                    vesselDescriptionList = new List <string>
                    {
                        "Shipwreck",
                        "Wreckage",
                        "Pod",
                        "Capsule",
                        "Derelict",
                        "Heap",
                        "Hulk",
                        "Craft",
                        "Debris",
                        "Scrap"
                    };
                }
                else
                {
                    vesselDescriptionList = new List <string>
                    {
                        "Prototype",
                        "Device",
                        "Part",
                        "Module",
                        "Unit",
                        "Component"
                    };
                }
                string vesselDescription = vesselDescriptionList[generator.Next(0, vesselDescriptionList.Count)];

                Orbit strandedOrbit;
                // Low orbit
                if (recoveryLocation != 1)
                {
                    // High orbit
                    if (recoveryLocation != 2)
                    {
                        strandedOrbit = new Orbit(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, contractBody);
                    }
                    else
                    {
                        strandedOrbit = FinePrint.Utilities.OrbitUtilities.GenerateOrbit(contractSeed, contractBody, FinePrint.Utilities.OrbitType.RANDOM,
                                                                                         FinePrint.ContractDefs.Recovery.HighOrbitDifficulty, FinePrint.ContractDefs.Recovery.HighOrbitDifficulty, 0.0);
                    }
                }
                else
                {
                    double minAltitude = FinePrint.Utilities.CelestialUtilities.GetMinimumOrbitalDistance(contractBody, 1f) - contractBody.Radius;
                    strandedOrbit = Orbit.CreateRandomOrbitAround(contractBody, contractBody.Radius + minAltitude * 1.1000000238418579, contractBody.Radius + minAltitude * 1.25);
                    strandedOrbit.meanAnomalyAtEpoch = generator.NextDouble() * 2.0 * Math.PI;
                }

                ConfigNode configNode = null;

                if (recoveringKerbal)
                {
                    DarkLog.Debug("We want to recover a kerbal, so let's do it");
                    string kerbalName   = contractNode.GetValue("kerbalName");
                    int    kerbalGender = int.Parse(contractNode.GetValue("gender"));

                    string vesselName = FinePrint.Utilities.StringUtilities.PossessiveString(FinePrint.Utilities.StringUtilities.ShortKerbalName(kerbalName)) +
                                        " " + vesselDescription;

                    // Recovery Locations:
                    // 0: None,
                    // 1: Low Orbit,
                    // 2: High Orbit,
                    // 3: Surface

                    ProtoCrewMember pcm = null;
                    if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
                    {
                        DarkLog.Debug("Spawning missing kerbal, name: " + kerbalName);
                        pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
                        pcm.ChangeName(kerbalName);
                        pcm.gender       = (ProtoCrewMember.Gender)kerbalGender;
                        pcm.rosterStatus = ProtoCrewMember.RosterStatus.Assigned;
                        pcm.seat         = null;
                        pcm.seatIdx      = -1;
                        //Add kerbal to crew roster.
                    }
                    else
                    {
                        pcm = HighLogic.CurrentGame.CrewRoster[kerbalName];
                    }

                    // Spawn lone kerbal
                    if (partName == "kerbalEVA")
                    {
                        configNode = ProtoVessel.CreateVesselNode(kerbalName, VesselType.EVA, strandedOrbit, 0, new ConfigNode[]
                        {
                            CreateProcessedPartNode(partName, newPartID, new ProtoCrewMember[]
                            {
                                pcm
                            })
                        }, new ConfigNode[]
                        {
                            ProtoVessel.CreateDiscoveryNode(DiscoveryLevels.Unowned, UntrackedObjectClass.A, contractDeadline * 2, contractDeadline * 2)
                        });
                        configNode.AddValue("prst", true);
                        ProtoVessel pv = HighLogic.CurrentGame.AddVessel(configNode);
                        VesselWorker.fetch.LoadVessel(configNode, pv.vesselID, false);
                        NetworkWorker.fetch.SendVesselProtoMessage(pv, false, false);
                    }
                    // Spawn kerbal in capsule/pod
                    else
                    {
                        configNode = ProtoVessel.CreateVesselNode(vesselName, (recoveryLocation != 3) ? VesselType.Ship : VesselType.Lander, strandedOrbit, 0, new ConfigNode[]
                        {
                            CreateProcessedPartNode(partName, newPartID, new ProtoCrewMember[]
                            {
                                pcm
                            })
                        }, new ConfigNode[]
                        {
                            new ConfigNode("ACTIONGROUPS"),
                            ProtoVessel.CreateDiscoveryNode(DiscoveryLevels.Unowned, UntrackedObjectClass.A, contractDeadline * 2, contractDeadline * 2)
                        });
                        configNode.AddValue("prst", true);
                        ProtoVessel pv = HighLogic.CurrentGame.AddVessel(configNode);
                        VesselWorker.fetch.LoadVessel(configNode, pv.vesselID, false);
                        NetworkWorker.fetch.SendVesselProtoMessage(pv, false, false);
                    }
                }
            }
        }
Esempio n. 23
0
        private void onKerbalAdded(ProtoCrewMember kerbal)
        {
            counter = 0;
            if (kerbal.isHero)
            {
                return;
            }
            bool   nameFound = false;
            bool   russian   = (r.NextDouble() < 0.5 && validRussianData);
            string surname   = "";

            if (!russian)
            {
                surname = americanSurnames.ElementAt(r.Next(0, americanSurnames.Count()));
            }
            else
            {
                if (kerbal.gender == ProtoCrewMember.Gender.Male)
                {
                    surname = russianMaleSurnames.ElementAt(r.Next(0, russianMaleSurnames.Count()));
                }
                else
                {
                    surname = russianFemaleSurnames.ElementAt(r.Next(0, russianFemaleSurnames.Count()));
                }
            }
            string forename = "";

            while (!nameFound)
            {
                nameFound = true;
                if (kerbal.gender == ProtoCrewMember.Gender.Male)
                {
                    if (!russian)
                    {
                        forename = americanMales.ElementAt(r.Next(0, americanMales.Count()));
                    }
                    else
                    {
                        forename = russianMales.ElementAt(r.Next(0, russianMales.Count()));
                    }
                }
                else
                {
                    if (!russian)
                    {
                        forename = americanFemales.ElementAt(r.Next(0, americanFemales.Count()));
                    }
                    else
                    {
                        forename = russianFemales.ElementAt(r.Next(0, russianFemales.Count()));
                    }
                }
                name = forename + " " + surname;
                IEnumerable <ProtoCrewMember> crew = HighLogic.CurrentGame.CrewRoster.Kerbals();
                for (int i = 0; i < crew.Count(); i++)
                {
                    ProtoCrewMember p = crew.ElementAt(i);
                    if (p.name == name)
                    {
                        nameFound = false;
                        counter++;
                        break;
                    }
                }
                if (counter > 50)
                {
                    nameFound = true;
                }
            }
            kerbal.ChangeName(name);
        }
 public void GenerateKerbal()
 {
     _pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(kerbalType);
     _pcm.gender = gender;
     _pcm.ChangeName(name);
     _pcm.trait = experienceTrait;
     KerbalRoster.SetExperienceTrait(_pcm, experienceTrait);
 }
Esempio n. 25
0
 private string SetName(string nameToSet)
 {
     Debug.Log("[EarnYourStripes]: Changing " + kerbalToEdit.name + " to " + nameToSet);
     kerbalToEdit.ChangeName(nameToSet);
     return(nameToSet);
 }
        /// <summary>
        /// Called when a draft succeeds.
        /// </summary>
        /// <param name="kerbalName">The name of the drafted viewer.</param>
        void DraftSuccess(Dictionary <string, string> info)
        {
            // Resets failures. The addon should only destroy after 5 consecutive failures.
            failures = 0;

            // Get the next contract in the queue.
            Contract toMod = contractsToModify.Dequeue();

            // Create a ConfigNode to save the contract into.
            ConfigNode replacement = new ConfigNode("CONTRACT");

            toMod.Save(replacement);

            // Get the old Kerbal name for later use.
            string oldName = replacement.GetValue("kerbalName");

            // Replace the old name with the new.
            replacement.SetValue("kerbalName", info["name"]);

            // For each PARAM node in the CONTRACT node,
            foreach (ConfigNode node in replacement.nodes)
            {
                // Get the name of the contract parameter.
                string paramName = node.GetValue("name");

                // Perform certain replacement functions for each parameter.
                switch (paramName)
                {
                case "AcquireCrew":
                {
                    node.SetValue("title", "Save " + info["name"]);
                    break;
                }

                case "AcquirePart":
                {
                    string firstName = info["name"].Substring(0, info["name"].IndexOf(' '));
                    node.SetValue("title", "Obtain " + firstName + "'s Scrap");
                    break;
                }

                case "RecoverKerbal":
                {
                    node.SetValue("title", "Recover " + info["name"] + " on Kerbin");
                    break;
                }

                case "RecoverPart":
                {
                    string firstName = info["name"].Substring(0, info["name"].IndexOf(' '));
                    node.SetValue("title", "Recover " + firstName + "'s Scrap on Kerbin");
                    break;
                }
                }
            }

            // Get a count of parameters currently held by the contract.
            int parameters = toMod.ParameterCount;

            // Iterate using this count, removing the one parameter each time, effectively clearing the list.
            for (int i = 0; i < parameters; i++)
            {
                // Remove the first parameter.
                toMod.RemoveParameter(0);
            }

            // Add the custom parameter indicating DTV has modified this contract.
            toMod.AddParameter(new ModifiedByDTV());

            // Reload the contract.
            Contract.Load(toMod, replacement);

            // Get the old Kerbal and rename it.
            ProtoCrewMember toRename = HighLogic.CurrentGame.CrewRoster[oldName];

            toRename.ChangeName(info["name"]);

            // Logging.
            Logger.DebugLog("Draft Success (" + contractsToModify.Count.ToString() + " contracts waiting): " + info["name"]);

            // Refresh the contract list by firing the onContractListChanged event.
            GameEvents.Contract.onContractsListChanged.Fire();

            // If the queue is not empty,
            if (contractsToModify.Count > 0)
            {
                // Begin another draft.
                StartCoroutine(ScenarioDraftManager.DraftKerbal(DraftSuccess, DraftFailure, false, false, "Any"));
            }
            // Else, the queue is empty.
            else
            {
                // Indicate a stop in waiting status.
                working = false;
            }
        }
Esempio n. 27
0
        private void kHire()
        {
            System.Random rand = new System.Random();

            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                double myFunds = Funding.Instance.Funds;
                Funding.Instance.AddFunds(-costMath(), TransactionReasons.CrewRecruited);
                Hire.Log.Info("KSI :: Total Funds removed " + costMath());
            }

            for (int i = 0; i < KBulki; i++)
            {
                ProtoCrewMember newKerb = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Crew);

                newKerb.ChangeName(KNames[KGender, i]);

                switch (KGender) // Sets gender
                {
                case 0: newKerb.gender = ProtoCrewMember.Gender.Male; break;

                case 1: newKerb.gender = ProtoCrewMember.Gender.Female; break;

                case 2: newKerb.gender = KNames2Gender[i]; break;

                default: break;
                }

                string career = traits.traitTitles[KCareer].name;
                // Sets the kerbal's career based on the KCareer switch.
                KerbalRoster.SetExperienceTrait(newKerb, career);

                // Hire.Log.Info("KSI :: KIA MIA Stat is: " + KDead);
                // Hire.Log.Info("KSI :: " + newKerb.experienceTrait.Config.Name + " " + newKerb.name + " has been created in: " + loopcount.ToString() + " loops.");
                newKerb.rosterStatus    = ProtoCrewMember.RosterStatus.Available;
                newKerb.experience      = 0;
                newKerb.experienceLevel = 0;
                if (KBulki > 0) // Bulk hires get random stats
                {
                    // The equation gives 60% of results within +/-10% of GUI setting
                    newKerb.courage   = (float)Math.Min(1, Math.Max(0, (Math.Pow(2 * rand.NextDouble() - 1, 3) / 2) + KCourage / 100));
                    newKerb.stupidity = (float)Math.Min(1, Math.Max(0, (Math.Pow(2 * rand.NextDouble() - 1, 3) / 2) + KStupidity / 100));
                    // 5% chance of Badass
                    newKerb.isBadass = rand.NextDouble() > .95;
                    // No chance of vets in bulk hires.
                    newKerb.veteran = false;
                }
                else // use GUI values
                {
                    newKerb.courage   = KCourage / 100;
                    newKerb.stupidity = KStupidity / 100;
                    if (KFearless)
                    {
                        newKerb.isBadass = true;
                    }

                    if (KVeteran)
                    {
                        newKerb.veteran = true;
                    }
                }

                // Hire.Log.Info("PSH :: Status set to Available, courage and stupidity set, fearless trait set.");

                if (kerExp == false)
                {
                    newKerb.experience      = 9999;
                    newKerb.experienceLevel = 5;
                    Hire.Log.Info("KSI :: Level set to 5 - Kerbal Experince disabled.");
                }
                else
                {
                    switch (KLevel)
                    {
                    case 1:
                        newKerb.flightLog.AddEntry("Training1," + FlightGlobals.GetHomeBodyName());
                        newKerb.ArchiveFlightLog();
                        newKerb.experience      = 2;
                        newKerb.experienceLevel = 1;
                        // Hire.Log.Info("KSI :: Level set to 1.");
                        break;

                    case 2:
                        newKerb.flightLog.AddEntry("Training2," + FlightGlobals.GetHomeBodyName());
                        newKerb.ArchiveFlightLog();
                        newKerb.experience      = 8;
                        newKerb.experienceLevel = 2;
                        // Hire.Log.Info("KSI :: Level set to 2.");
                        break;

                    case 3:
                        newKerb.flightLog.AddEntry("Training3," + FlightGlobals.GetHomeBodyName());
                        newKerb.ArchiveFlightLog();
                        newKerb.experience      = 16;
                        newKerb.experienceLevel = 3;
                        // Hire.Log.Info("KSI :: Level set to 3.");
                        break;

                    case 4:
                        newKerb.flightLog.AddEntry("Training4," + FlightGlobals.GetHomeBodyName());
                        newKerb.ArchiveFlightLog();
                        newKerb.experience      = 32;
                        newKerb.experienceLevel = 4;
                        // Hire.Log.Info("KSI :: Level set to 4.");
                        break;

                    case 5:
                        newKerb.flightLog.AddEntry("Training5," + FlightGlobals.GetHomeBodyName());
                        newKerb.ArchiveFlightLog();
                        newKerb.experience      = 64;
                        newKerb.experienceLevel = 5;
                        break;
                    }
                }
                GameEvents.onKerbalAdded.Fire(newKerb);       // old gameevent most likely to be used by other mods
                GameEvents.onKerbalAddComplete.Fire(newKerb); // new gameevent that seems relevant
            }
            // Refreshes the AC so that new kerbal shows on the available roster.
            Hire.Log.Info("PSH :: Hiring Function Completed.");


            GameEvents.onGUIAstronautComplexDespawn.Fire();
            GameEvents.onGUIAstronautComplexSpawn.Fire();
        }
        void OnKerbalAdded(ProtoCrewMember kerbal)
        {
            // Don't change custom kerbals
            if (!kerbal.name.EndsWith("Kerman"))
            {
                return;
            }

            // Make sure all custom kerbals exist
            for (int i = 0; i < KerbalCrewFixer.customKerbals.Length; i++)
            {
                int custom = (i + (KerbalRenamerSettings.preserveOriginals ? 6 : 0)) % 10;

                if (HighLogic.CurrentGame.CrewRoster[KerbalCrewFixer.customKerbals[custom]] == null)
                {
                    KerbalCrewFixer.SetCustomKerbal(kerbal, KerbalCrewFixer.customKerbals[custom]);
                    return;
                }
            }

            // This Part will generate a new Kerbal followint the defined KerbalRenamerSettings
            Random.InitState(DateTime.Now.Millisecond * kerbal.name.GetHashCode());

            if (KerbalRenamerSettings.generateNewStats)
            {
                if (kerbal.type == ProtoCrewMember.KerbalType.Applicant)
                {
                    // generate some new stats
                    kerbal.stupidity = rollStupidity();
                    kerbal.courage   = rollCourage();
                    kerbal.isBadass  = (Random.Range(0.0f, 1.0f) < KerbalRenamerSettings.badassPercent);

                    float rand = Random.Range(0.0f, 1.0f);
                    if (rand < 0.33f)
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, "Pilot");
                    }
                    else if (rand < 0.66f)
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, "Engineer");
                    }
                    else
                    {
                        KerbalRoster.SetExperienceTrait(kerbal, "Scientist");
                    }

                    if (Random.Range(0.0f, 1.0f) < KerbalRenamerSettings.femalePercent)
                    {
                        kerbal.gender = ProtoCrewMember.Gender.Female;
                    }
                    else
                    {
                        kerbal.gender = ProtoCrewMember.Gender.Male;
                    }
                }
            }

            string name  = "";
            int    index = 0;

            while (name.Length == 0 || HighLogic.CurrentGame.CrewRoster[name] != null)
            {
                name = getName(kerbal);

                index++; if (index > 50)
                {
                    return;
                }
            }

            kerbal.ChangeName(name);
        }
Esempio n. 29
0
        public void editor(int windowID)
        {
            editorScrollPosition = GUILayout.BeginScrollView(editorScrollPosition);
            List <ProtoCrewMember> kerbs = new List <ProtoCrewMember>(HighLogic.CurrentGame.CrewRoster.Crew);

            for (int i = kerbs.Count - 1; i >= 0; --i)
            {
                ProtoCrewMember kerb = kerbs[i];

                if (GUILayout.Button(kerb.name))
                {
                    kerbalToEdit  = kerb;
                    editCourage   = kerb.courage;
                    editStupidity = kerb.stupidity;
                    editBadS      = kerb.isBadass;
                    editName      = kerb.name;
                    if (kerb.gender == ProtoCrewMember.Gender.Female)
                    {
                        editGender = "Female";
                        editMale   = false;
                    }
                    else
                    {
                        editGender = "Male";
                        editMale   = true;
                    }
                    editTrait   = kerb.trait;
                    editVeteran = kerb.veteran;
                    if (editTrait == "Pilot")
                    {
                        editTraitInt = 0;
                    }
                    else if (editTrait == "Engineer")
                    {
                        editTraitInt = 1;
                    }
                    else
                    {
                        editTraitInt = 2;
                    }
                }
            }
            GUILayout.EndScrollView();

            //Field to type in kerbal's name.
            GUILayout.BeginHorizontal();
            GUILayout.Label("Name:");
            editName = GUILayout.TextField(editName, 50);
            GUILayout.EndHorizontal();

            //Toggle female/male
            GUILayout.BeginHorizontal();
            if (GUILayout.Button(editGender))
            {
                editMale = !editMale;
            }
            if (GUILayout.Button(editTrait))
            {
                if (editTraitInt < 2)
                {
                    editTraitInt += 1;
                }
                else
                {
                    editTraitInt = 0;
                }
            }

            GUILayout.EndHorizontal();

            //Sets kerbal's courage.
            GUILayout.BeginHorizontal();
            GUILayout.Label("Courage:");
            editCourage = GUILayout.HorizontalSlider(editCourage, 0.0f, 1.0f);
            GUILayout.EndHorizontal();

            //Sets kerbal's stupidity.
            GUILayout.BeginHorizontal();
            GUILayout.Label("Stupidity:");
            editStupidity = GUILayout.HorizontalSlider(editStupidity, 0.0f, 1.0f);
            GUILayout.EndHorizontal();

            //Toggles BadS state.
            GUILayout.BeginHorizontal();
            editBadS = GUILayout.Toggle(editBadS, "BadS: " + editBadS);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            editVeteran = GUILayout.Toggle(editVeteran, "Veteran: " + editVeteran);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            editFloat = GUILayout.Toggle(editFloat, "Float window");
            GUILayout.EndHorizontal();

            if (editExists)
            {
                GUILayout.BeginHorizontal();
                editOverride = GUILayout.Toggle(editOverride, "Override existing Kerbal check");
                GUILayout.EndHorizontal();
            }

            if (GUILayout.Button("Edit Kerbal"))
            {
                if (kerbalToEdit == null)
                {
                    ScreenMessages.PostScreenMessage("You must select a Kerbal first!", 1);
                }
                else
                {
                    if (editExists)
                    {
                        if (editOverride)
                        {
                            kerbalToEdit.ChangeName(editName);
                            if (editGender == "Female")
                            {
                                kerbalToEdit.gender = ProtoCrewMember.Gender.Female;
                            }
                            else
                            {
                                kerbalToEdit.gender = ProtoCrewMember.Gender.Male;
                            }

                            KerbalRoster.SetExperienceTrait(kerbalToEdit, editTrait);

                            kerbalToEdit.courage   = editCourage;
                            kerbalToEdit.stupidity = editStupidity;

                            kerbalToEdit.isBadass = editBadS;
                            kerbalToEdit.veteran  = editVeteran;

                            ScreenMessages.PostScreenMessage(kerbalToEdit.name + " has been edited!", 1, ScreenMessageStyle.UPPER_CENTER);
                        }
                        else
                        {
                            ScreenMessages.PostScreenMessage("A Kerbal with the name " + kerbalToEdit.name + " already exists.  If you would like to continue, enable override existing Kerbal ckeck.", 1, ScreenMessageStyle.UPPER_CENTER);
                        }
                    }
                    else
                    {
                        kerbalToEdit.ChangeName(editName);
                        if (editGender == "Female")
                        {
                            kerbalToEdit.gender = ProtoCrewMember.Gender.Female;
                        }
                        else
                        {
                            kerbalToEdit.gender = ProtoCrewMember.Gender.Male;
                        }

                        KerbalRoster.SetExperienceTrait(kerbalToEdit, editTrait);

                        kerbalToEdit.courage   = editCourage;
                        kerbalToEdit.stupidity = editStupidity;

                        kerbalToEdit.isBadass = editBadS;

                        ScreenMessages.PostScreenMessage(kerbalToEdit.name + " has been edited!", 1, ScreenMessageStyle.UPPER_CENTER);
                    }
                }
            }

            if (GUILayout.Button("Close"))
            {
                editorEnabled = false;
            }

            if (editFloat)
            {
                GUI.DragWindow();
            }
        }
        //Gets a new kerbal and sets his/her stats based on whether there is already a Kerbal of that name or not, or if the person wants o override that check
        private void SpawnKerbal(int count, bool overrideState)
        {
            if (exists && overrideState == false) {

                warningState = true;

            } else {

                newKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal ();
                newKerbal.ChangeName(stringToEdit);
                newKerbal.courage = sliderValue;
                newKerbal.stupidity = sliderValue2;
                newKerbal.isBadass = buttonState;
                newKerbal.veteran = veteran;

                KerbalRoster.SetExperienceTrait (newKerbal, Trait);

                //Find out and set the gender
                if (male == false) {

                    newKerbal.gender = ProtoCrewMember.Gender.Female;

                }
                if (male) {

                    newKerbal.gender = ProtoCrewMember.Gender.Male;

                }

                if (closeOnComplete) {

                    appLauncherButton.SetFalse (true);
                    ScreenMessages.PostScreenMessage ("Kustom Kerbal Spawned, closing window...", 1, ScreenMessageStyle.UPPER_CENTER);

                } else {

                    ScreenMessages.PostScreenMessage ("Kustom Kerbal Spawned.", 1, ScreenMessageStyle.UPPER_CENTER);

                }

            }
        }
        /// <summary>
        /// Called when a draft succeeds.
        /// </summary>
        /// <param name="kerbalName">The name of the drafted viewer.</param>
        void DraftSuccess(Dictionary <string, string> info)
        {
            // Enqueue the name first thing, since it needs to be in the queue whether it has enough with it or not.
            draftNames.Enqueue(info["name"]);

            // Resets failures. The addon should only destroy after 5 consecutive failures.
            failures = 0;

            // Peek at the next contract in the queue instead of dequeueing because there might not yet be enough names to cover the contract.
            Contract toMod = contractsToModify.Peek();

            // Create a ConfigNode to save the contract into.
            ConfigNode replacement = new ConfigNode("CONTRACT");

            toMod.Save(replacement);

            // Obtain a list of the old tourists in the contract.
            string[] oldTourists = replacement.GetValue("tourists").Split('|');

            // If the count of names in the queue plus this name equals the number of tourists,
            if (draftNames.Count == oldTourists.Length)
            {
                // Dequeue the contract we peeked because there are enough names for it.
                contractsToModify.Dequeue();

                // Create an array from the queue and clear it.
                string[] newTourists = draftNames.ToArray();
                draftNames.Clear();

                // Replace the contract "tourists" string.
                replacement.SetValue("tourists", string.Join("|", newTourists));

                // Get a list of PARAM nodes in the contract.
                ConfigNode[] paramNodes = replacement.GetNodes("PARAM");

                // Iterate through them,
                for (int i = 0; i < paramNodes.Length; i++)
                {
                    // And replace their kerbalName values.
                    paramNodes[i].SetValue("kerbalName", newTourists[i]);

                    // Iterate through any sub-PARAMS,
                    foreach (ConfigNode subParam in paramNodes[i].GetNodes("PARAM"))
                    {
                        // And replace their kerbalName values as well.
                        subParam.SetValue("kerbalName", newTourists[i]);
                    }

                    // Remove the parameter from the actual contract to prevent duplicates.
                    toMod.RemoveParameter(0);

                    // Get an old Kerbal and rename it.
                    ProtoCrewMember toRename = HighLogic.CurrentGame.CrewRoster[oldTourists[i]];
                    toRename.ChangeName(newTourists[i]);
                }

                // Add the custom parameter indicating DTV has modified this contract.
                toMod.AddParameter((ContractParameter) new ModifiedByDTV());

                // Reload the contract.
                Contract.Load(toMod, replacement);

                // Logging.
                Logger.DebugLog("Draft Success (" + contractsToModify.Count.ToString() + " contracts waiting): " + string.Join("|", newTourists));

                // Refresh the contract list by firing the onContractListChanged event.
                GameEvents.Contract.onContractsListChanged.Fire();

                // If the queue is not empty,
                if (contractsToModify.Count > 0)
                {
                    // Begin another draft.
                    StartCoroutine(ScenarioDraftManager.DraftKerbal(DraftSuccess, DraftFailure, false, false, "Any"));
                }
                // Else, the queue is empty.
                else
                {
                    // Indicate a stop in waiting status.
                    working = false;
                }
            }
            // Else, run another draft.
            else
            {
                StartCoroutine(ScenarioDraftManager.DraftKerbal(DraftSuccess, DraftFailure, false, false, "Any"));
            }
        }
Esempio n. 32
0
        protected bool CreateVessels()
        {
            if (vesselsCreated)
            {
                return(false);
            }

            String gameDataDir = KSPUtil.ApplicationRootPath;

            gameDataDir = gameDataDir.Replace("\\", "/");
            if (!gameDataDir.EndsWith("/"))
            {
                gameDataDir += "/";
            }
            gameDataDir += "GameData";

            // Spawn the vessel in the game world
            foreach (VesselData vesselData in vessels)
            {
                LoggingUtil.LogVerbose(this, "Spawning a vessel named '{0}'", vesselData.name);

                // Set additional info for landed vessels
                bool landed = false;
                if (!vesselData.orbiting)
                {
                    landed = true;
                    if (vesselData.altitude == null)
                    {
                        vesselData.altitude = LocationUtil.TerrainHeight(vesselData.latitude, vesselData.longitude, vesselData.body);
                    }

                    Vector3d pos = vesselData.body.GetWorldSurfacePosition(vesselData.latitude, vesselData.longitude, vesselData.altitude.Value);

                    vesselData.orbit = new Orbit(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, vesselData.body);
                    vesselData.orbit.UpdateFromStateVectors(pos, vesselData.body.getRFrmVel(pos), vesselData.body, Planetarium.GetUniversalTime());
                }
                else
                {
                    vesselData.orbit.referenceBody = vesselData.body;
                }

                ConfigNode[]         partNodes;
                UntrackedObjectClass sizeClass;
                ShipConstruct        shipConstruct = null;
                if (!string.IsNullOrEmpty(vesselData.craftURL))
                {
                    // Save the current ShipConstruction ship, otherwise the player will see the spawned ship next time they enter the VAB!
                    ConfigNode currentShip = ShipConstruction.ShipConfig;

                    shipConstruct = ShipConstruction.LoadShip(gameDataDir + "/" + vesselData.craftURL);
                    if (shipConstruct == null)
                    {
                        LoggingUtil.LogError(this, "ShipConstruct was null when tried to load '{0}' (usually this means the file could not be found).", vesselData.craftURL);
                        continue;
                    }

                    // Restore ShipConstruction ship
                    ShipConstruction.ShipConfig = currentShip;

                    // Set the name
                    if (string.IsNullOrEmpty(vesselData.name))
                    {
                        vesselData.name = shipConstruct.shipName;
                    }

                    // Set some parameters that need to be at the part level
                    uint missionID = (uint)Guid.NewGuid().GetHashCode();
                    uint launchID  = HighLogic.CurrentGame.launchID++;
                    foreach (Part p in shipConstruct.parts)
                    {
                        p.flightID  = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                        p.missionID = missionID;
                        p.launchID  = launchID;
                        p.flagURL   = vesselData.flagURL ?? HighLogic.CurrentGame.flagURL;

                        // Had some issues with this being set to -1 for some ships - can't figure out
                        // why.  End result is the vessel exploding, so let's just set it to a positive
                        // value.
                        p.temperature = 1.0;

                        p.UpdateOrgPosAndRot(shipConstruct.parts[0]);
                    }

                    // Estimate an object class, numbers are based on the code that generate objects.
                    float size = shipConstruct.shipSize.magnitude / 2.0f;
                    if (size < 4.05f)
                    {
                        sizeClass = UntrackedObjectClass.A;
                    }
                    else if (size < 6.75f)
                    {
                        sizeClass = UntrackedObjectClass.B;
                    }
                    else if (size < 11.25f)
                    {
                        sizeClass = UntrackedObjectClass.C;
                    }
                    else if (size < 18.25f)
                    {
                        sizeClass = UntrackedObjectClass.D;
                    }
                    else if (size < 31.25f || (Versioning.version_major <= 1 && Versioning.version_minor <= 10))
                    {
                        sizeClass = UntrackedObjectClass.E;
                    }
                    // Only for KSP 1.10+
                    else if (size < 52.125f)
                    {
                        sizeClass = UntrackedObjectClass.F;
                    }
                    else if (size < 86.875f)
                    {
                        sizeClass = UntrackedObjectClass.G;
                    }
                    else if (size < 144.75f)
                    {
                        sizeClass = UntrackedObjectClass.H;
                    }
                    else
                    {
                        sizeClass = UntrackedObjectClass.I;
                    }

                    foreach (CrewData cd in vesselData.crew)
                    {
                        bool success = false;

                        // Find a seat for the crew
                        Part part = shipConstruct.parts.Find(p => p.protoModuleCrew.Count < p.CrewCapacity);

                        // Add the crew member
                        if (part != null)
                        {
                            // Create the ProtoCrewMember
                            ProtoCrewMember crewMember = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
                            if (cd.gender != null)
                            {
                                crewMember.gender = cd.gender.Value;
                            }
                            if (cd.name != null)
                            {
                                crewMember.ChangeName(cd.name);
                            }

                            // Add them to the part
                            success = part.AddCrewmemberAt(crewMember, part.protoModuleCrew.Count);
                        }

                        if (!success)
                        {
                            LoggingUtil.LogWarning(this, "Unable to add crew to vessel named '{0}'.  Perhaps there's no room?", vesselData.name);
                            break;
                        }
                    }

                    // Create a dummy ProtoVessel, we will use this to dump the parts to a config node.
                    // We can't use the config nodes from the .craft file, because they are in a
                    // slightly different format than those required for a ProtoVessel.
                    ConfigNode  empty       = new ConfigNode();
                    ProtoVessel dummyProto  = new ProtoVessel(empty, null);
                    Vessel      dummyVessel = new GameObject().AddComponent <Vessel>();
                    dummyVessel.parts    = shipConstruct.parts;
                    dummyProto.vesselRef = dummyVessel;

                    // Create the ProtoPartSnapshot objects and then initialize them
                    foreach (Part p in shipConstruct.parts)
                    {
                        p.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                        p.vessel   = dummyVessel;
                        dummyProto.protoPartSnapshots.Add(new ProtoPartSnapshot(p, dummyProto));
                    }
                    foreach (ProtoPartSnapshot p in dummyProto.protoPartSnapshots)
                    {
                        p.storePartRefs();
                    }

                    // Create the ship's parts
                    partNodes = dummyProto.protoPartSnapshots.Select <ProtoPartSnapshot, ConfigNode>(GetNodeForPart).ToArray();

                    // Clean up
                    foreach (Part p in shipConstruct.parts)
                    {
                        GameObject.Destroy(p.gameObject);
                    }
                    GameObject.Destroy(dummyVessel.gameObject);
                }
                else
                {
                    // Create crew member array
                    ProtoCrewMember[] crewArray = new ProtoCrewMember[vesselData.crew.Count];
                    int i = 0;
                    foreach (CrewData cd in vesselData.crew)
                    {
                        // Create the ProtoCrewMember
                        ProtoCrewMember crewMember = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
                        if (cd.name != null)
                        {
                            crewMember.ChangeName(cd.name);
                        }

                        crewArray[i++] = crewMember;
                    }

                    // Create part nodes
                    uint flightId = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState);
                    partNodes    = new ConfigNode[1];
                    partNodes[0] = ProtoVessel.CreatePartNode(vesselData.craftPart.name, flightId, crewArray);

                    // Default the size class
                    sizeClass = UntrackedObjectClass.A;

                    // Set the name
                    if (string.IsNullOrEmpty(vesselData.name))
                    {
                        vesselData.name = vesselData.craftPart.name;
                    }
                }

                // Create additional nodes
                ConfigNode[]    additionalNodes = new ConfigNode[1];
                DiscoveryLevels discoveryLevel  = vesselData.owned ? DiscoveryLevels.Owned : DiscoveryLevels.Unowned;
                additionalNodes[0] = ProtoVessel.CreateDiscoveryNode(discoveryLevel, sizeClass, contract.TimeDeadline, contract.TimeDeadline);

                // Create the config node representation of the ProtoVessel
                ConfigNode protoVesselNode = ProtoVessel.CreateVesselNode(vesselData.name, vesselData.vesselType, vesselData.orbit, 0, partNodes, additionalNodes);

                // Additional seetings for a landed vessel
                if (!vesselData.orbiting)
                {
                    Vector3d norm = vesselData.body.GetRelSurfaceNVector(vesselData.latitude, vesselData.longitude);

                    double terrainHeight = 0.0;
                    if (vesselData.body.pqsController != null)
                    {
                        terrainHeight = vesselData.body.pqsController.GetSurfaceHeight(norm) - vesselData.body.pqsController.radius;
                    }
                    bool splashed = landed && terrainHeight < 0.001;

                    // Create the config node representation of the ProtoVessel
                    // Note - flying is experimental, and so far doesn't work
                    protoVesselNode.SetValue("sit", (splashed ? Vessel.Situations.SPLASHED : landed ?
                                                     Vessel.Situations.LANDED : Vessel.Situations.FLYING).ToString());
                    protoVesselNode.SetValue("landed", (landed && !splashed).ToString());
                    protoVesselNode.SetValue("splashed", splashed.ToString());
                    protoVesselNode.SetValue("lat", vesselData.latitude.ToString());
                    protoVesselNode.SetValue("lon", vesselData.longitude.ToString());
                    protoVesselNode.SetValue("alt", vesselData.altitude.ToString());
                    protoVesselNode.SetValue("landedAt", vesselData.body.name);

                    // Figure out the additional height to subtract
                    float lowest = float.MaxValue;
                    if (shipConstruct != null)
                    {
                        foreach (Part p in shipConstruct.parts)
                        {
                            foreach (Collider collider in p.GetComponentsInChildren <Collider>())
                            {
                                if (collider.gameObject.layer != 21 && collider.enabled)
                                {
                                    lowest = Mathf.Min(lowest, collider.bounds.min.y);
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (Collider collider in vesselData.craftPart.partPrefab.GetComponentsInChildren <Collider>())
                        {
                            if (collider.gameObject.layer != 21 && collider.enabled)
                            {
                                lowest = Mathf.Min(lowest, collider.bounds.min.y);
                            }
                        }
                    }

                    if (lowest == float.MaxValue)
                    {
                        lowest = 0;
                    }

                    // Figure out the surface height and rotation
                    Quaternion normal   = Quaternion.LookRotation(new Vector3((float)norm.x, (float)norm.y, (float)norm.z));
                    Quaternion rotation = Quaternion.identity;
                    float      heading  = vesselData.heading;
                    if (shipConstruct == null)
                    {
                        rotation = rotation * Quaternion.FromToRotation(Vector3.up, Vector3.back);
                    }
                    else if (shipConstruct.shipFacility == EditorFacility.SPH)
                    {
                        rotation = rotation * Quaternion.FromToRotation(Vector3.forward, -Vector3.forward);
                        heading += 180.0f;
                    }
                    else
                    {
                        rotation = rotation * Quaternion.FromToRotation(Vector3.up, Vector3.forward);
                    }

                    rotation = rotation * Quaternion.AngleAxis(vesselData.pitch, Vector3.right);
                    rotation = rotation * Quaternion.AngleAxis(vesselData.roll, Vector3.down);
                    rotation = rotation * Quaternion.AngleAxis(heading, Vector3.forward);

                    // Set the height and rotation
                    if (landed || splashed)
                    {
                        float hgt = (shipConstruct != null ? shipConstruct.parts[0] : vesselData.craftPart.partPrefab).localRoot.attPos0.y - lowest;
                        hgt += vesselData.height;
                        protoVesselNode.SetValue("hgt", hgt.ToString());
                    }
                    protoVesselNode.SetValue("rot", KSPUtil.WriteQuaternion(rotation * normal));

                    // Set the normal vector relative to the surface
                    Vector3 nrm = (rotation * Vector3.forward);
                    protoVesselNode.SetValue("nrm", nrm.x + "," + nrm.y + "," + nrm.z);

                    protoVesselNode.SetValue("prst", false.ToString());
                }

                // Add vessel to the game
                ProtoVessel protoVessel = new ProtoVessel(protoVesselNode, HighLogic.CurrentGame);
                protoVessel.Load(HighLogic.CurrentGame.flightState);

                // Store the id for later use
                vesselData.id = protoVessel.vesselRef.id;

                // Associate it so that it can be used in contract parameters
                ContractVesselTracker.Instance.AssociateVessel(vesselData.name, protoVessel.vesselRef);
            }

            vesselsCreated = true;
            return(true);
        }