IEnumerator SaveCraftVariant(Vessel toSave) { _count += 1; int partCount = 0; string shipDescription = toSave.vesselName + " Variant " + _count; Debug.Log("[OrX Save Craft Variant] Saving " + toSave.vesselName + " ......................."); ShipConstruct ConstructToSave = new ShipConstruct(toSave.vesselName + " Variant " + _count, shipDescription, toSave.parts[0]); ConfigNode craftConstruct = new ConfigNode("craft"); craftConstruct = ConstructToSave.SaveShip(); yield return(new WaitForFixedUpdate()); //craftConstruct.RemoveValue("persistentId"); craftConstruct.RemoveValue("steamPublishedFileId"); craftConstruct.RemoveValue("rot"); craftConstruct.RemoveValue("missionFlag"); craftConstruct.RemoveValue("vesselType"); craftConstruct.RemoveValue("OverrideDefault"); craftConstruct.RemoveValue("OverrideActionControl"); craftConstruct.RemoveValue("OverrideAxisControl"); craftConstruct.RemoveValue("OverrideGroupNames"); string _craftFileToSave = UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/Ships/SPH/" + toSave.vesselName + "-Variant-" + _count + ".craft"; craftConstruct.Save(_craftFileToSave); OrXLog.instance.DebugLog("[OrX Save Craft Variant] Saved " + toSave.vesselName + " to the hangar ......................."); OrXHoloKron.instance.OnScrnMsgUC("<color=#cfc100ff><b>" + toSave.vesselName + " Variant " + _count + " Saved</b></color>"); }
public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL) { ship = s; shipNode = s.SaveShip(); shipName = s.shipName; //Get total ship cost float dry, fuel; s.GetShipCosts(out dry, out fuel); cost = dry + fuel; TotalMass = 0; foreach (Part p in s.Parts) { TotalMass += p.mass; TotalMass += p.GetResourceMass(); } launchSite = ls; buildPoints = bP; progress = 0; flag = flagURL; if (launchSite == "LaunchPad") { type = ListType.VAB; } else { type = ListType.SPH; } InventoryParts = new Dictionary <string, int>(); id = Guid.NewGuid(); cannotEarnScience = false; }
public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL) { ship = s; shipNode = s.SaveShip(); shipName = s.shipName; //Get total ship cost float dry, fuel; s.GetShipCosts(out dry, out fuel); cost = dry + fuel; TotalMass = 0; foreach (Part p in s.Parts) { TotalMass += p.mass; TotalMass += p.GetResourceMass(); } launchSite = ls; buildPoints = bP; progress = 0; flag = flagURL; if (launchSite == "LaunchPad") type = ListType.VAB; else type = ListType.SPH; InventoryParts = new Dictionary<string, int>(); id = Guid.NewGuid(); cannotEarnScience = false; }
public static string TemporarySaveVessel(Vessel VesselToSave) { string ShipName = VesselToSave.vesselName; ShipConstruct ConstructToSave = new ShipConstruct(ShipName, "", VesselToSave.parts[0]); Quaternion OriginalRotation = VesselToSave.vesselTransform.rotation; Vector3 OriginalPosition = VesselToSave.vesselTransform.position; VesselToSave.SetRotation(new Quaternion(0, 0, 0, 1)); Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave); VesselToSave.SetPosition(new Vector3(0, ShipSize.y + 2, 0)); ConfigNode CN = new ConfigNode("ShipConstruct"); CN = ConstructToSave.SaveShip(); VesselToSave.SetRotation(OriginalRotation); VesselToSave.SetPosition(OriginalPosition); string filename = UrlDir.ApplicationRootPath + "GameData/FlightEdit/temp.craft"; CN.Save(filename); return(filename); }
public static void RecalculateEditorBuildTime(ShipConstruct ship) { KCTDebug.Log("Recalculating build time"); List <ConfigNode> partNodes = ship.SaveShip().GetNodes("PART").ToList(); KCT_GUI.PartsInUse.Clear(); if (KCT_GUI.useInventory) { foreach (ConfigNode part in partNodes) { string name = PartNameFromNode(part) + GetTweakScaleSize(part); if (!KCT_GUI.PartsInUse.ContainsKey(name)) { KCT_GUI.PartsInUse.Add(name, 1); } else { ++KCT_GUI.PartsInUse[name]; } } } if (!KCT_GameStates.EditorShipEditingMode) { KCT_GameStates.EditorBuildTime = KCT_Utilities.GetBuildTime(partNodes, true, KCT_GUI.useInventory); } else { List <string> partsForInventory = new List <string>(); if (KCT_GUI.useInventory) { List <string> newParts = new List <string>(PartDictToList(KCT_GUI.PartsInUse)); List <string> theInventory = new List <string>(PartDictToList(KCT_GameStates.PartInventory)); foreach (string s in PartDictToList(KCT_GameStates.EditedVesselParts)) { if (newParts.Contains(s)) { newParts.Remove(s); } } foreach (string s in newParts) { if (theInventory.Contains(s)) { theInventory.Remove(s); partsForInventory.Add(s); } } } foreach (string s in KCT_GameStates.editedVessel.InventoryParts) { partsForInventory.Add(s); } KCT_GameStates.EditorBuildTime = KCT_Utilities.GetBuildTime(partNodes, true, partsForInventory); } }
public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation, Part flagFromPart) { UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (!obj) { KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name); return null; } Part newPart = (Part)obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = avPart.name; newPart.partInfo = avPart; //newPart.highlightRecurse = true; newPart.SetMirror(Vector3.one); ShipConstruct newShip = new ShipConstruct(); newShip.Add(newPart); newShip.SaveShip(); newShip.shipName = avPart.title; //newShip.ty = 1; VesselCrewManifest vessCrewManifest = new VesselCrewManifest(); Vessel currentVessel = FlightGlobals.ActiveVessel; Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(false); v.Landed = true; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = flagFromPart.missionID; v.rootPart.flagURL = flagFromPart.flagURL; //v.rootPart.collider.isTrigger = true; //v.landedAt = "somewhere"; Staging.beginFlight(); newShip.parts[0].vessel.ResumeStaging(); Staging.GenerateStagingSequence(newShip.parts[0].localRoot); Staging.RecalculateVesselStaging(newShip.parts[0].vessel); FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(position); v.SetRotation(rotation); // Solar panels from containers don't work otherwise for (int i = 0; i < newPart.Modules.Count; i++) { ConfigNode node = new ConfigNode(); node.AddValue("name", newPart.Modules[i].moduleName); newPart.LoadModule(node, ref i); } return newPart; }
public PackedConstruct(ShipConstruct construct, string flag) { this.flag = flag; this.construct = construct; vessel_node = construct.SaveShip(); vessel_node.name = "VESSEL"; resources = new VesselResources(vessel_node); name = Localizer.Format(construct.shipName); id = Guid.NewGuid(); }
public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL) { ship = s; shipNode = s.SaveShip(); shipName = s.shipName; //Get total ship cost float fuel; cost = s.GetShipCosts(out emptyCost, out fuel); TotalMass = s.GetShipMass(out emptyMass, out fuel); HashSet <int> stages = new HashSet <int>(); numStageParts = 0; stagePartCost = 0d; foreach (Part p in s.Parts) { if (p.stagingOn) { stages.Add(p.inverseStage); ++numStageParts; stagePartCost += p.GetModuleCosts(p.partInfo.cost, ModifierStagingSituation.CURRENT) + p.partInfo.cost; } } numStages = stages.Count; launchSite = ls; buildPoints = bP; progress = 0; flag = flagURL; if (s.shipFacility == EditorFacility.VAB) { type = ListType.VAB; } else if (s.shipFacility == EditorFacility.SPH) { type = ListType.SPH; } else { type = ListType.None; } id = Guid.NewGuid(); cannotEarnScience = false; //get the crew from the editorlogic DesiredManifest = new List <string>(); if (CrewAssignmentDialog.Instance?.GetManifest()?.CrewCount > 0) { foreach (ProtoCrewMember crew in CrewAssignmentDialog.Instance.GetManifest().GetAllCrew(true) ?? new List <ProtoCrewMember>()) { DesiredManifest.Add(crew?.name ?? string.Empty); } } }
public void Save() { if (!Directory.Exists(UrlDir.ApplicationRootPath + "GameData/OrXHoloCache/" + HoloCacheName)) { Directory.CreateDirectory(UrlDir.ApplicationRootPath + "GameData/OrXHoloCache/" + HoloCacheName); } ShipName = VesselToSave.vesselName; if (holo) { Debug.Log("[OrX Ship Save] HoloCache Identified ......................."); shipDescription = "HoloCache"; } else { Debug.Log("[OrX Ship Save] Vessel Identified ......................."); shipDescription = ""; } ShipConstruct ConstructToSave = new ShipConstruct(ShipName, shipDescription, VesselToSave.parts[0]); Debug.Log("[OrX Ship Save] Saving: " + ShipName + " ............"); ScreenMsg("<color=#cfc100ff><b>Saving: " + ShipName + "</b></color>"); Quaternion OriginalRotation = VesselToSave.vesselTransform.rotation; Vector3 OriginalPosition = VesselToSave.vesselTransform.position; VesselToSave.SetRotation(new Quaternion(0, 0, 0, 1)); Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave); VesselToSave.SetPosition(new Vector3(0, ShipSize.y + 2, 0)); ConfigNode CN = new ConfigNode("ShipConstruct"); CN = ConstructToSave.SaveShip(); CleanEditorNodes(CN); VesselToSave.SetRotation(OriginalRotation); VesselToSave.SetPosition(OriginalPosition); Debug.Log("Facility: " + ConstructToSave.shipFacility); Debug.Log("[OrX Ship Save] Saving: " + UrlDir.ApplicationRootPath + "GameData/OrXHoloCache/" + HoloCacheName + "/" + ShipName + ".craft"); CN.Save(UrlDir.ApplicationRootPath + "GameData/OrXHoloCache/" + HoloCacheName + "/" + ShipName + ".craft"); ScreenMsg("<color=#cfc100ff><b>" + ShipName + " Saved to GameData/OrXHoloCache/" + HoloCacheName + "</b></color>"); if (sthTargets) { sthTargets = false; } saveShip = false; holo = true; }
IEnumerator SaveDelayRoutine() { yield return(new WaitForSeconds(2)); if (HighLogic.LoadedSceneIsFlight && !FlightGlobals.ActiveVessel.HoldPhysics) { Debug.Log("[OrX Ship Save] Active Vessel Identified ......................."); VesselToSave = FlightGlobals.ActiveVessel; ShipName = FlightGlobals.ActiveVessel.vesselName; shipDescription = "_Rescued"; ShipConstruct ConstructToSave = new ShipConstruct(ShipName, shipDescription, VesselToSave.parts[0]); Debug.Log("[OrX Ship Save] Saving: " + ShipName + " ............"); ScreenMsg("<color=#cfc100ff><b>Saving: " + ShipName + "</b></color>"); Quaternion OriginalRotation = VesselToSave.vesselTransform.rotation; Vector3 OriginalPosition = VesselToSave.vesselTransform.position; VesselToSave.SetRotation(new Quaternion(0, 0, 0, 1)); Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave); VesselToSave.SetPosition(new Vector3(0, ShipSize.y + 2, 0)); ConfigNode CN = new ConfigNode("ShipConstruct"); CN = ConstructToSave.SaveShip(); CleanEditorNodes(CN); VesselToSave.SetRotation(OriginalRotation); VesselToSave.SetPosition(OriginalPosition); Debug.Log("Facility: " + ConstructToSave.shipFacility); if (ConstructToSave.shipFacility == EditorFacility.SPH) { Debug.Log("Ship Saved: " + UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/Ships/SPH/" + ShipName + "_Rescued.craft"); CN.Save(UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/Ships/SPH/" + ShipName + "_Rescued.craft"); } else { Debug.Log("Ship Saved: " + UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/Ships/VAB/" + ShipName + "_Rescued.craft"); CN.Save(UrlDir.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/Ships/VAB/" + ShipName + "_Rescued.craft"); } } else { //Save(); } }
//creation public static Vessel Create(Creature creature, Vector3 positionOffset) { try { AvailablePart partInfo = PartLoader.LoadedPartsList.First(ap => ap.name == creature.part); Part referencePart = FlightGlobals.ActiveVessel.rootPart; Part part = (Part)UnityEngine.Object.Instantiate(partInfo.partPrefab); part.gameObject.SetActive(true); part.gameObject.name = partInfo.name; part.partInfo = partInfo; part.SetMirror(Vector3.one); ShipConstruct sc = new ShipConstruct(); sc.Add(part); sc.SaveShip(); sc.shipName = creature.name; Vessel vessel = sc.parts[0].localRoot.gameObject.AddComponent <Vessel>(); vessel.id = Guid.NewGuid(); vessel.vesselName = sc.shipName; vessel.vesselType = VesselType.Unknown; //vessel.DiscoveryInfo.Load(ProtoVessel.CreateDiscoveryNode(DiscoveryLevels.Unowned, UntrackedObjectClass.A, 10000, 10000)); vessel.ctrlState = new FlightCtrlState(); vessel.ctrlState.NeutralizeAll(); vessel.Initialize(false); vessel.Landed = false; vessel.SetPosition(referencePart.transform.position + positionOffset); vessel.SetRotation(Quaternion.identity); //manually remove orbit renderer UnityEngine.Object.Destroy(vessel.orbitDriver.Renderer); CreaturePart cp = (CreaturePart)vessel.rootPart; cp.creature = creature; cp.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); cp.missionID = referencePart.missionID; cp.flagURL = referencePart.flagURL; FlightLogger.eventLog.Add(Utils.FormatTime(referencePart.vessel.missionTime) + "A " + creature.name + " was seen."); return(vessel); } catch (Exception e) { Utils.LogError("Error encountered while spawning part"); if (e != null) { Debug.LogException(e); } } return(null); }
public VesselKit( PartModule host, ShipConstruct ship, bool assembled = true, bool simulate = false ) : this() { Host = host; Name = Localizer.Format(ship.shipName); ship.Parts.ForEach(p => p.UpdateMass()); if (!simulate) { strip_resources(ship, assembled); Blueprint = ship.SaveShip(); } var create_resources = count_kit_resources(ship, assembled); ShipMetric = new Metric((IShipconstruct)ship, true, true); DockingNodes = FindDockingNodes(ship, ShipMetric); var final_assembly_work = 0f; ship.Parts.ForEach(p => { var kit = new PartKit(p, assembled); final_assembly_work += p.mass * GLB.FinalizationWorkPerMass * 3600; Jobs.Add(kit); }); create_resources.ForEach(r => { var assembled_resource = r.Value.type == KitResourceInfo.ResourceType.CONSTRUCTED; Jobs.Add(new PartKit(r.Value.name, r.Value.mass, r.Value.cost, assembled_resource ? 0 : 1, 0, assembled_resource)); }); Jobs.Add(new PartKit("Final Assembly", 0, 0, 0, final_assembly_work, true)); if (assembled) { SetStageComplete(DIYKit.ASSEMBLY, true); } HasLaunchClamps = ship.HasLaunchClamp(); CurrentIndex = 0; }
public VesselKit(PartModule host, ShipConstruct ship, bool assembled = true, bool simulate = false) : this() { Host = host; Name = Localizer.Format(ship.shipName); if (!simulate) { strip_resources(ship, assembled); Blueprint = ship.SaveShip(); } count_kit_resources(ship); ShipMetric = new Metric(ship, true, true); DockingNodes = FindDockingNodes(ship, ShipMetric); Jobs.AddRange(ship.Parts.ConvertAll(p => new PartKit(p, assembled))); SetStageComplete(DIYKit.ASSEMBLY, assembled); HasLaunchClamps = ship.HasLaunchClamp(); CurrentIndex = 0; }
public VesselKit(PartModule host, ShipConstruct ship, bool assembled = true, bool simulate = false) : this() { Host = host; Name = Localizer.Format(ship.shipName); if (!simulate) { strip_resources(ship, assembled); Blueprint = ship.SaveShip(); } var create_resources = count_kit_resources(ship, assembled); ShipMetric = new Metric(ship, true, true); DockingNodes = FindDockingNodes(ship, ShipMetric); Jobs.AddRange(ship.Parts.ConvertAll(p => new PartKit(p, assembled))); create_resources.ForEach(r => Jobs.Add(new PartKit(r.Value.name, r.Value.mass, r.Value.cost, r.Value.type == KitResourceInfo.ResourceType.CONSTRUCTED))); SetStageComplete(DIYKit.ASSEMBLY, assembled); HasLaunchClamps = ship.HasLaunchClamp(); CurrentIndex = 0; }
public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL) { ship = s; shipNode = s.SaveShip(); shipName = s.shipName; //Get total ship cost float dry, fuel; s.GetShipCosts(out dry, out fuel); cost = dry + fuel; launchSite = ls; buildPoints = bP; progress = 0; flag = flagURL; if (launchSite == "LaunchPad") type = ListType.VAB; else type = ListType.SPH; InventoryParts = new List<string>(); id = Guid.NewGuid(); cannotEarnScience = false; }
public KCT_BuildListVessel(ShipConstruct s, String ls, double bP, String flagURL) { ship = s; shipNode = s.SaveShip(); shipName = s.shipName; //Get total ship cost float fuel; cost = s.GetShipCosts(out emptyCost, out fuel); TotalMass = s.GetShipMass(out emptyMass, out fuel); launchSite = ls; buildPoints = bP; progress = 0; flag = flagURL; if (s.shipFacility == EditorFacility.VAB) type = ListType.VAB; else if (s.shipFacility == EditorFacility.SPH) type = ListType.SPH; else type = ListType.None; InventoryParts = new Dictionary<string, int>(); id = Guid.NewGuid(); cannotEarnScience = false; }
private void OnEditorUndo(ShipConstruct data) { ConfigNode n = data.SaveShip(); }
private ConfigNode FromInFlightVessel(Vessel VesselToSave) { //This code is taken from InflightShipSave by Claw, using the CC-BY-NC-SA license. //This code thus is licensed under the same license, despite the GPLv3 license covering original KCT code //See https://github.com/ClawKSP/InflightShipSave string ShipName = VesselToSave.vesselName; // Debug.LogWarning("Saving: " + ShipName); ShipConstruct ConstructToSave = new ShipConstruct(ShipName, "", VesselToSave.parts[0]); Quaternion OriginalRotation = VesselToSave.vesselTransform.rotation; Vector3 OriginalPosition = VesselToSave.vesselTransform.position; VesselToSave.SetRotation(new Quaternion(0, 0, 0, 1)); Vector3 ShipSize = ShipConstruction.CalculateCraftSize(ConstructToSave); VesselToSave.SetPosition(new Vector3(0, ShipSize.y + 2, 0)); ConfigNode CN = new ConfigNode("ShipConstruct"); CN = ConstructToSave.SaveShip(); SanitizeShipNode(CN); VesselToSave.SetRotation(OriginalRotation); VesselToSave.SetPosition(OriginalPosition); //End of Claw's code. Thanks Claw! return CN; }
/// <remarks> /// This code is based on KAS by KospY and the following license applies: /// http://kerbal.curseforge.com/ksp-mods/223900-kerbal-attachment-system-kas/license (link valid 03.09.2014) /// Usage of this code by me (marce) has been generously granted by KospY on 02.09.2014 per PM. /// </remarks> public static Part SpawnPartInFlight(string partName, Part referencePart, Vector3 referencePartOriginSpawnOffset, Quaternion spawnRotation, bool spawnLanded = true) { if (!HighLogic.LoadedSceneIsFlight) { Debug.Log(LOG_PREFIX + " can only spawn in flight"); return(null); } var currentVessel = FlightGlobals.ActiveVessel; var avPart = PartLoader.getPartInfoByName(partName); if (avPart == null) { Debug.Log(LOG_PREFIX + " failed to find part " + partName); return(null); } var obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (obj == null) { Debug.Log(LOG_PREFIX + " failed to instantiate part " + partName); return(null); } try { var newPart = (Part)obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = avPart.name; newPart.partInfo = avPart; //newPart.highlightRecurse = true; newPart.SetMirror(Vector3.one); var newShip = new ShipConstruct { newPart }; newShip.SaveShip(); newShip.shipName = avPart.title; var type = Convert.ChangeType(VesselType.Debris, VesselType.Debris.GetTypeCode()); //if (type != null) //{ // newShip.shipType = (int) type; //} //else //{ // newShip.shipType = 1; //} var v = newShip.parts[0].localRoot.gameObject.AddComponent <Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(); v.Landed = spawnLanded; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = referencePart.missionID; v.rootPart.flagURL = referencePart.flagURL; FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(referencePart.transform.position + referencePartOriginSpawnOffset); v.SetRotation(spawnRotation); for (var i = 0; i < newPart.Modules.Count; i++) { var node = new ConfigNode(); node.AddValue("name", newPart.Modules[i].moduleName); var j = i; newPart.LoadModule(node, ref j); } return(newPart); } catch (NullReferenceException) { Debug.Log(LOG_PREFIX + " part unknown"); return(null); } }
public void OnVesselRecoveryRequested(Vessel v) { //Get total ship cost KerbalGUIManager.print("[rusty] OnVesselRecoveryRequested"); KerbalGUIManager.print("[rusty] parts.Count: " + v.parts.Count); KerbalGUIManager.print("[rusty] Parts.Count: " + v.Parts.Count); KerbalGUIManager.print("[rusty] GetActiveParts().Count: " + v.GetActiveParts().Count); if (v.rootPart != null) { KerbalGUIManager.print("[rusty] Root part is alive"); } else { KerbalGUIManager.print("[rusty] Root part is NULL"); } ShipConstruct ship = new ShipConstruct(v.vesselName, "", v.rootPart); ship.shipFacility = EditorFacility.VAB; saveVesselLater = ship.SaveShip(); }
public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation, Part flagFromPart) { UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (!obj) { KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name); return null; } Part newPart = (Part)obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = "KASCreatedPart"; newPart.partInfo = avPart; newPart.highlightRecurse = true; ShipConstruct newShip = new ShipConstruct(); newShip.Add(newPart); newShip.SaveShip(); newShip.shipName = avPart.title; newShip.shipType = 1; VesselCrewManifest vessCrewManifest = new VesselCrewManifest(); Vessel currentVessel = FlightGlobals.ActiveVessel; Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(false); v.Landed = true; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = (uint)Guid.NewGuid().GetHashCode(); v.rootPart.flagURL = flagFromPart.flagURL; //v.rootPart.collider.isTrigger = true; v.rootPart.FindModelTransform("model").localScale *= v.rootPart.rescaleFactor; //v.landedAt = "somewhere"; Staging.beginFlight(); newShip.parts[0].vessel.ResumeStaging(); Staging.GenerateStagingSequence(newShip.parts[0].localRoot); Staging.RecalculateVesselStaging(newShip.parts[0].vessel); FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(position); v.SetRotation(rotation); return newPart; }
/// <remarks> /// This code is based on KAS by KospY and the following license applies: /// http://kerbal.curseforge.com/ksp-mods/223900-kerbal-attachment-system-kas/license (link valid 03.09.2014) /// Usage of this code by me (marce) has been generously granted by KospY on 02.09.2014 per PM. /// </remarks> public static Part SpawnPartInFlight(string partName, Part referencePart, Vector3 referencePartOriginSpawnOffset, Quaternion spawnRotation, bool spawnLanded = true) { if (!HighLogic.LoadedSceneIsFlight) { Debug.Log(LogPrefix + " can only spawn in flight"); return null; } var currentVessel = FlightGlobals.ActiveVessel; var avPart = PartLoader.getPartInfoByName(partName); var obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (obj == null) { Debug.Log(LogPrefix + " failed to instantiate part " + partName); return null; } try { var newPart = (Part) obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = avPart.name; newPart.partInfo = avPart; newPart.highlightRecurse = true; newPart.SetMirror(Vector3.one); var newShip = new ShipConstruct {newPart}; newShip.SaveShip(); newShip.shipName = avPart.title; var type = Convert.ChangeType(VesselType.Debris, VesselType.Debris.GetTypeCode()); if (type != null) { newShip.shipType = (int) type; } else { newShip.shipType = 1; } var v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(); v.Landed = spawnLanded; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = referencePart.missionID; v.rootPart.flagURL = referencePart.flagURL; FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(referencePart.transform.position + referencePartOriginSpawnOffset); v.SetRotation(spawnRotation); for (var i = 0; i < newPart.Modules.Count; i++) { var node = new ConfigNode(); node.AddValue("name", newPart.Modules[i].moduleName); var j = i; newPart.LoadModule(node, ref j); } return newPart; } catch (NullReferenceException) { Debug.Log(LogPrefix + " part unknown"); return null; } }
protected void onEditorShipModified(ShipConstruct ship) { Part[] shipParts = ship.parts.ToArray(); ModuleQualityControl qualityControl; debugLog("onEditorShipModified called"); //If build time is disabled then just set the integration bonus to maximum. if (BARISSettingsLaunch.VesselsNeedIntegration == false) { int integrationBonus = BARISScenario.Instance.GetIntegrationCap(isVAB); debugLog("Vehicle integration is disabled, setting parts to max integration bonus: " + integrationBonus); foreach (Part part in shipParts) { qualityControl = part.FindModuleImplementing <ModuleQualityControl>(); if (qualityControl != null) { qualityControl.integrationBonus = integrationBonus; } } return; } //If you launch a vessel that was loaded from an editor bay, then go back to the editor, that vessel will be loaded again. //For BARIS purposes though, we need to treat it as a vessel that hasn't been integrated yet. To do that, we clear the integration bonus. if (editorBayItem == null) { debugLog("no editorBayItem found, clearing integration bonus."); if (!clearedIntegrationBonus) { clearedIntegrationBonus = true; foreach (Part part in shipParts) { qualityControl = part.FindModuleImplementing <ModuleQualityControl>(); if (qualityControl != null) { qualityControl.integrationBonus = 0; } } } return; } //onEditorShipModified gets called whenever a part is added or removed from the vessel being built. //It will be called when the vessel is loaded as well. We want to watch for vessel modifications when //the player loads a vessel from an editor bay; if the vessel changes before it is launched, then //any vessel integration progress is void. Fortunately the player can just re-load from the editor bay. //We also add the integration bonus at this time. int integrationPerPart = editorBayItem.totalIntegrationAdded / editorBayItem.breakablePartCount; bool partCountMismatch = EditorLogic.fetch.ship.parts.Count != editorBayItem.totalVesselParts; //When loading a vessel from an editor bay, be sure to bypass the part count mismatch. if (bypassPartMismatch) { bypassPartMismatch = false; partCountMismatch = false; } //Set integration bonus & Flight Experience //If the vessel has been tampered with then integration has failed. foreach (Part part in shipParts) { qualityControl = part.FindModuleImplementing <ModuleQualityControl>(); if (qualityControl != null) { if (partCountMismatch) { qualityControl.integrationBonus = 0; } else { qualityControl.integrationBonus = integrationPerPart; } //Set flight experience qualityControl.flightExperienceBonus = BARISScenario.Instance.GetFlightBonus(qualityControl.part); //Recalculate the quality. qualityControl.currentQuality = qualityControl.GetMaxQuality(); debugLog(qualityControl.part.partInfo.title + " new quality: " + qualityControl.currentQuality); } } //If the vessel has been tamepred with then inform the player debugLog("partCountMismatch: " + partCountMismatch); debugLog("errorMessageShown: " + errorMessageShown); if (partCountMismatch && !errorMessageShown) { //Inform player errorMessageShown = true; messageView.WindowTitle = Localizer.Format(BARISScenario.VesselModifiedTitle); messageView.message = "<Color=yellow><b>" + Localizer.Format(BARISScenario.VesselModifiedMsg) + "</b></color>"; messageView.SetVisible(true); BARISScenario.Instance.PlayProblemSound(); } //Vessel is good, update the save file. else { ConfigNode shipNode = ship.SaveShip(); shipNode.Save(editorBayItem.vesselFilePath); } }
public override void drawWindow(int windowID) { GUIStyle mySty = new GUIStyle(GUI.skin.window); mySty.normal.textColor = mySty.focused.textColor = Color.white; mySty.hover.textColor = mySty.active.textColor = Color.yellow; mySty.onNormal.textColor = mySty.onFocused.textColor = mySty.onHover.textColor = mySty.onActive.textColor = Color.green; mySty.padding = new RectOffset(8, 8, 8, 8); GUILayout.BeginVertical(); GUILayout.Label("Select an assembly"); if (GUILayout.Button("StorePart") && EditorLogic.SelectedPart != null) { EditorLogic editor = EditorLogic.fetch; ShipConstruct ship = new ShipConstruct(); Utils.addPartToShipRecursive(ship, EditorLogic.SelectedPart); ship.SaveShip().Save("D:/rusty.cfg"); ShipConstruction.CaptureThumbnail(ship, "rusty_thumbs", "rusty"); // store thumb KSP_rusty.Inventory.Add(ship.SaveShip()); // root or not? if (EditorLogic.SelectedPart == EditorLogic.RootPart) { KerbalGUIManager.print("[rusty] GUIInventory:StorePart: is root"); EditorLogic.DeletePart(EditorLogic.SelectedPart); } else { KerbalGUIManager.print("[rusty] GUIInventory:StorePart: is not root"); EditorLogic.DeletePart(EditorLogic.SelectedPart); } } /* if (GUILayout.Button("Store")) { try { EditorLogic editor = EditorLogic.fetch; ShipConstruct ship = new ShipConstruct(editor.ship.shipName, editor.ship.shipFacility, editor.getSortedShipList()); KerbalGUIManager.print("[rusty] GUIInventory: storing"); try { inv = new ShipConstruct(); if (inv.LoadShip(ship.SaveShip())) { KerbalGUIManager.print("[rusty] GUIInventory: load OK"); } else { KerbalGUIManager.print("[rusty] GUIInventory: load failed"); } } catch (Exception e) { KerbalGUIManager.print("Exception GUIInventory:drawWindow():Store;saveShip: " + e.Message + "\n" + e.StackTrace); } KerbalGUIManager.print("[rusty] GUIInventory: deleting old"); } catch (Exception e) { KerbalGUIManager.print("Exception GUIInventory:drawWindow():Store: " + e.Message + "\n" + e.StackTrace); } } */ if (GUILayout.Button("Load rusty.cfg")) { ConfigNode rusty2 = ConfigNode.Load("D:/rusty.cfg"); EditorLogic editor = null; ShipConstruct ship = null; editor = EditorLogic.fetch; //editor.SpawnPart(PartLoader.getPartInfoByName("mk1pod")); //editor.SpawnConstruct(inv); // fix type rusty2.SetValue("type", "VAB", true); rusty2.Save("D:/rusty2.cfg"); ship = new ShipConstruct(); ship.LoadShip(rusty2); } if (KSP_rusty.Inventory != null) { foreach (ConfigNode inventoryItem in KSP_rusty.Inventory) { string title = ""; int nrOfParts = 0; try { // get number of parts ConfigNode[] partNodes = inventoryItem.GetNodes("PART"); if (partNodes != null) { nrOfParts = partNodes.GetUpperBound(0) + 1; } // get vessel name title = inventoryItem.GetValue("ship"); if (title != null && title.Length > 0) { title = "Load " + title + " (" + nrOfParts + ")"; } else { title = "Load (" + nrOfParts + " parts)"; } } catch (Exception e) { KerbalGUIManager.print("Exception GUIInventory:drawWindow():Button title " + e.Message + "\n" + e.StackTrace); } if (GUILayout.Button(title)) { KerbalGUIManager.print("[rusty] Adding part from inventory"); EditorLogic editor = null; ShipConstruct ship = null; try { editor = EditorLogic.fetch; ship = new ShipConstruct(); ship = rustyInventory.buildConstruct(inventoryItem); ship.SaveShip().Save("D:/rusty.cfg"); editor.SpawnConstruct(ship); /* //editor.SpawnPart(PartLoader.getPartInfoByName("mk1pod")); //editor.SpawnConstruct(inv); // fix type inventoryItem.SetValue("type", "VAB", true); inventoryItem.Save("D:/rusty.cfg"); ship = new ShipConstruct(); ship.LoadShip(inventoryItem); // TODO: editor.OnPodSpawn(PartLoader.getPartInfoByName("mk1pod")); */ KSP_rusty.Inventory.Remove(inventoryItem); break; } catch (Exception e) { if (editor == null) KerbalGUIManager.print("[rusty] editor is null"); if (ship == null) KerbalGUIManager.print("[rusty] ship is null"); KerbalGUIManager.print("[rusty] Exception GUIInventory:drawWindow():Load " + e.Message + "\n" + e.StackTrace); } } } } GUILayout.EndVertical(); }
private void SaveEncrypted() { OrXLog.instance.DebugLog("[OrX Module - Save Encrypted] === SAVING OrX ==="); Vessel toSave = FlightGlobals.ActiveVessel; string shipDescription = "Infected"; ShipConstruct ConstructToSave = new ShipConstruct(toSave.vesselName, shipDescription, toSave.parts[0]); ConfigNode craftConstruct = new ConfigNode("craft"); craftConstruct = ConstructToSave.SaveShip(); craftConstruct.RemoveValue("persistentId"); craftConstruct.RemoveValue("steamPublishedFileId"); craftConstruct.RemoveValue("rot"); craftConstruct.RemoveValue("missionFlag"); craftConstruct.RemoveValue("vesselType"); craftConstruct.RemoveValue("OverrideDefault"); craftConstruct.RemoveValue("OverrideActionControl"); craftConstruct.RemoveValue("OverrideAxisControl"); craftConstruct.RemoveValue("OverrideGroupNames"); foreach (ConfigNode cn in craftConstruct.nodes) { if (cn.name == "PART") { cn.RemoveValue("persistentId"); } } OrXLog.instance.DebugLog("[OrX Module - Save Encrypted] Saving: " + toSave.vesselName); OrXHoloKron.instance.OnScrnMsgUC("<color=#cfc100ff><b>Saving: " + toSave.vesselName + "</b></color>"); craftConstruct.Save(UrlDir.ApplicationRootPath + "GameData/OrX/Plugin/PluginData/VesselData/OrX/" + toSave.vesselName + ".craft"); // ADD ENCRYPTION foreach (ConfigNode.Value cv in craftConstruct.values) { if (cv.name == "ship") { cv.value = toSave.vesselName; } string cvEncryptedName = OrXLog.instance.Crypt(cv.name); string cvEncryptedValue = OrXLog.instance.Crypt(cv.value); cv.name = cvEncryptedName; cv.value = cvEncryptedValue; } foreach (ConfigNode cn in craftConstruct.nodes) { foreach (ConfigNode.Value cv in cn.values) { string cvEncryptedName = OrXLog.instance.Crypt(cv.name); string cvEncryptedValue = OrXLog.instance.Crypt(cv.value); cv.name = cvEncryptedName; cv.value = cvEncryptedValue; } foreach (ConfigNode cn2 in cn.nodes) { foreach (ConfigNode.Value cv2 in cn2.values) { if (!cv2.value.Contains("(") && !cv2.value.Contains(")")) { string cvEncryptedName = OrXLog.instance.Crypt(cv2.name); string cvEncryptedValue = OrXLog.instance.Crypt(cv2.value); cv2.name = cvEncryptedName; cv2.value = cvEncryptedValue; } } } } craftConstruct.Save(UrlDir.ApplicationRootPath + "GameData/OrX/Plugin/PluginData/VesselData/OrX/" + toSave.vesselName + ".crypt"); //toSave.rootPart.AddModule("ModuleOrXJason", true); }
public static Part CreatePart(AvailablePart avPart, Vector3 position, Quaternion rotation, Part flagFromPart) { UnityEngine.Object obj = UnityEngine.Object.Instantiate(avPart.partPrefab); if (!obj) { KAS_Shared.DebugError("CreatePart(Crate) Failed to instantiate " + avPart.partPrefab.name); return null; } Part newPart = (Part)obj; newPart.gameObject.SetActive(true); newPart.gameObject.name = avPart.name; newPart.partInfo = avPart; newPart.highlightRecurse = true; newPart.SetMirror(Vector3.one); ShipConstruct newShip = new ShipConstruct(); newShip.Add(newPart); newShip.SaveShip(); newShip.shipName = avPart.title; newShip.shipType = 1; VesselCrewManifest vessCrewManifest = new VesselCrewManifest(); Vessel currentVessel = FlightGlobals.ActiveVessel; Vessel v = newShip.parts[0].localRoot.gameObject.AddComponent<Vessel>(); v.id = Guid.NewGuid(); v.vesselName = newShip.shipName; v.Initialize(false); v.Landed = true; v.rootPart.flightID = ShipConstruction.GetUniqueFlightID(HighLogic.CurrentGame.flightState); v.rootPart.missionID = flagFromPart.missionID; v.rootPart.flagURL = flagFromPart.flagURL; //v.rootPart.collider.isTrigger = true; //v.landedAt = "somewhere"; Staging.beginFlight(); newShip.parts[0].vessel.ResumeStaging(); Staging.GenerateStagingSequence(newShip.parts[0].localRoot); Staging.RecalculateVesselStaging(newShip.parts[0].vessel); FlightGlobals.SetActiveVessel(currentVessel); v.SetPosition(position); v.SetRotation(rotation); // Solar panels from containers don't work otherwise for (int i = 0; i < newPart.Modules.Count; i++) { ConfigNode node = new ConfigNode(); node.AddValue("name", newPart.Modules[i].moduleName); newPart.LoadModule(node, ref i); } return newPart; }