public override void OnSave(ConfigNode node) { base.OnSave(node); try { if (HighLogic.fetch && HighLogic.LoadedSceneIsFlight) { if (FlightComputer == null) { FlightComputer = new FlightComputer.FlightComputer(this); } FlightComputer.Save(node); } } catch (Exception e) { RTLog.Notify("An exception occurred in ModuleSPU.OnSave(): ", RTLogLevel.LVL4, e); print(e); } }
public static double GetSignalDelayToSatellite(Guid a, Guid b) { var satelliteA = RTCore.Instance.Satellites[a]; var satelliteB = RTCore.Instance.Satellites[b]; if (satelliteA == null || satelliteB == null) { return(Double.PositiveInfinity); } Func <ISatellite, IEnumerable <NetworkLink <ISatellite> > > neighbors = RTCore.Instance.Network.FindNeighbors; Func <ISatellite, NetworkLink <ISatellite>, double> cost = RangeModelExtensions.DistanceTo; Func <ISatellite, ISatellite, double> heuristic = RangeModelExtensions.DistanceTo; var path = NetworkPathfinder.Solve(satelliteA, satelliteB, neighbors, cost, heuristic); var delayBetween = path.Delay; RTLog.Verbose("Connection from {0} to {1} Delay: {2}", RTLogLevel.API, a, b, delayBetween); return(delayBetween); }
public static AssetBinder NewSubBinder(AssetBinder binder) { if (binder == null || binder.mRunner == null) { return(null); } if (binder.DeepAsSubTree >= binder.Runner.MaxSubTreeDeep) { var error = string.Format("在创建子行为树是超过了支持的最大深度值:{0}", binder.Runner.MaxSubTreeDeep); #if UNITY_EDITOR UnityEditor.EditorUtility.DisplayDialog("Error", error, "OK"); #endif RTLog.LogError(LogCat.AI, error); return(null); } var subbind = new AssetBinder(binder); subbind.mParent = binder; binder.mSubAssets.Add(subbind); return(subbind); }
/// <summary> /// Draws the content of the Presets section /// </summary> private void drawPresetsContent() { GUILayout.Label(Localizer.Format("#RT_OptionWindow_Presets_HelpText"), this.mGuiRunningText);//"You can revert your current settings to the starting settings, constructed from installed mods' MM patches. Also, you can reload your current settings with a third-party mod's own RemoteTech settings (the fallback in the event of no MM patch).\n\nHere you can see what presets are available:" GUILayout.Space(15); List <String> presetList = this.mSettings.PreSets; if (this.mSettings.PreSets.Count <= 0) { GUILayout.Label(Localizer.Format("#RT_OptionWindow_Presets_NotFound"), this.mGuiRunningText);//"No presets are found" } for (int i = presetList.Count - 1; i >= 0; --i) { GUILayout.BeginHorizontal("box", GUILayout.MaxHeight(15)); { string folderName = presetList[i]; //remove the node name int index = folderName.LastIndexOf("/RemoteTechSettings"); folderName = folderName.Substring(0, index) + folderName.Substring(index).Replace("/RemoteTechSettings", "").Trim(); //change default name to better name for MM-patched settings index = folderName.LastIndexOf("/Default_Settings"); if (index >= 0) { folderName = folderName.Substring(0, index) + " " + folderName.Substring(index).Replace("/Default_Settings", "starting settings"); } GUILayout.Space(15); GUILayout.Label(folderName, this.mGuiListText, GUILayout.ExpandWidth(true)); if (GUILayout.Button(Localizer.Format("#RT_OptionWindow_Presets_Reload"), this.mGuiListButton, GUILayout.Width(70), GUILayout.Height(20)))//"Reload" { RTSettings.ReloadSettings(this.mSettings, presetList[i]); ScreenMessages.PostScreenMessage(Localizer.Format("#RT_OptionWindow_Presets_msg1", folderName), 10);//string.Format("Your RemoteTech settings are set to {0}", ) RTLog.Notify("Overwrote current settings with this cfg {0}", RTLogLevel.LVL3, presetList[i]); } } GUILayout.EndHorizontal(); } }
/// <summary> /// Load and creates a command after saving a command. Returns null if no object /// has been loaded. /// </summary> /// <param name="n">Node with the command infos</param> /// <param name="fc">Current flightcomputer</param> public static ICommand LoadCommand(ConfigNode n, FlightComputer fc) { ICommand command = null; // switch the different commands switch (n.name) { case "AttitudeCommand": { command = new AttitudeCommand(); break; } case "ActionGroupCommand": { command = new ActionGroupCommand(); break; } case "BurnCommand": { command = new BurnCommand(); break; } case "ManeuverCommand": { command = new ManeuverCommand(); break; } case "CancelCommand": { command = new CancelCommand(); break; } case "TargetCommand": { command = new TargetCommand(); break; } case "EventCommand": { command = new EventCommand(); break; } case "DriveCommand": { command = new DriveCommand(); break; } case "ExternalAPICommand": { command = new ExternalAPICommand(); break; } } if (command != null) { ConfigNode.LoadObjectFromConfig(command, n); // additional loadings var result = command.Load(n, fc); RTLog.Verbose("Loading command {0}={1}", RTLogLevel.LVL1, n.name, result); // delete command if we can't load the command correctlys if (result == false) { command = null; } } return(command); }
//exposed method called by other mods, passing a ConfigNode to RemoteTech public static bool QueueCommandToFlightComputer(ConfigNode externalData) { //check we were actually passed a config node if (externalData == null) { return(false); } // check our min values if (!externalData.HasValue("GUIDString") && !externalData.HasValue("Executor") && !externalData.HasValue("ReflectionType")) { return(false); } try { Guid externalVesselId = new Guid(externalData.GetValue("GUIDString")); // you can only push a new external command if the vessel guid is the current active vessel if (FlightGlobals.ActiveVessel.id != externalVesselId) { RTLog.Verbose("Passed Guid is not the active Vessels guid", RTLogLevel.API); return(false); } // maybe we should look if this vessel hasLocal controll or not. If so, we can execute the command // immediately // get the flightcomputer FlightComputer.FlightComputer computer = RTCore.Instance.Satellites[externalVesselId].FlightComputer; var extCmd = FlightComputer.Commands.ExternalAPICommand.FromExternal(externalData); computer.Enqueue(extCmd); return(true); } catch (Exception ex) { RTLog.Verbose(ex.Message, RTLogLevel.API); } return(false); }
/// <summary> /// Determines whether or not the antenna is shielded from aerodynamic forces /// </summary> /// <returns><c>true</c>, if the antenna is shielded, <c>false</c> otherwise.</returns> /// /// <precondition><c>this.part</c> is not null</precondition> /// /// <exceptionsafe>Does not throw exceptions</exceptionsafe> private bool GetShieldedState() { PartModule FARPartModule = GetFARModule(); if (FARPartModule != null) { try { FieldInfo fi = FARPartModule.GetType().GetField("isShielded"); return((bool)(fi.GetValue(FARPartModule))); } catch (Exception e) { RTLog.Notify("GetShieldedState: {0}", e); // otherwise go further and try to get the stock shielded value } } // For KSP 1.0 return(this.part.ShieldedFromAirstream); }
public void LoadAsTable() { if (!string.IsNullOrEmpty(mData)) { if (mMerge) { TableSet <T> .MergeTo(TableSet <T> .LoadAsNew(mFile, mData), mTable); } else { TableSet <T> .LoadTo(mFile, mData, mTable); } #if UNITY_EDITOR RTLog.LogFormat(LogCat.Table, "{0} Table<{1}> @ {2}", mMerge ? "Merge" : "Load", typeof(T).Name, AssetPath); #endif } else { TableSet <T> .LoadComplete(mTable, mMerge); } }
/// <summary> /// Find the maneuver node by the saved node id (index id of the meneuver list) /// </summary> /// <param name="n">Node with the command infos</param> /// <param name="fc">Current flightcomputer</param> /// <returns>true - loaded successfull</returns> public override bool Load(ConfigNode n, FlightComputer fc) { if (base.Load(n, fc)) { if (n.HasValue("NodeIndex")) { this.NodeIndex = int.Parse(n.GetValue("NodeIndex")); RTLog.Notify("Trying to get Maneuver {0}", this.NodeIndex); if (this.NodeIndex >= 0) { // Set the ManeuverNode into this command this.Node = fc.Vessel.patchedConicSolver.maneuverNodes[this.NodeIndex]; RTLog.Notify("Found Maneuver {0} with {1} dV", this.NodeIndex, this.Node.DeltaV); return(true); } } } return(false); }
protected virtual void FindDomains() { var type = GetType(); var methods = type.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); for (int i = 0; i < methods.Length; i++) { var mtd = methods[i]; if (mtd.ReturnType != typeof(ISitcomResult)) { continue; } var args = mtd.GetParameters(); if (args == null || args.Length != 4) { continue; } if (args[0].ParameterType != typeof(SitcomContext) || args[1].ParameterType != typeof(T) || args[2].ParameterType != typeof(string) || args[3].ParameterType != typeof(object[])) { RTLog.LogErrorFormat(LogCat.Game, " [SitcomDomain]\"{0}/{1}\" don't match args", type.Name, mtd.Name); continue; } var attr = mtd.GetCustomAttributes(typeof(SitcomDomainAttribute), true); if (attr == null || attr.Length == 0) { continue; } var call = (SitcomCall <T>)System.Delegate.CreateDelegate(typeof(SitcomCall <T>), this, mtd); for (int j = 0; j < attr.Length; j++) { var domain = attr[j] as SitcomDomainAttribute; if (domain == null) { continue; } AddDomain(domain.Name, domain.Args, call, domain.IsDefault); } } }
public override bool Pop(FlightComputer f) { f.Vessel.ActionGroups.ToggleGroup(ActionGroup); if (ActionGroup == KSPActionGroup.Stage && !(f.Vessel == FlightGlobals.ActiveVessel && FlightInputHandler.fetch.stageLock)) { try { KSP.UI.Screens.StageManager.ActivateNextStage(); } catch (Exception ex) { RTLog.Notify("Exception during ActivateNextStage(): " + ex.Message, RTLogLevel.LVL4); } KSP.UI.Screens.ResourceDisplay.Instance.Refresh(); } if (ActionGroup == KSPActionGroup.RCS && f.Vessel == FlightGlobals.ActiveVessel) { FlightInputHandler.fetch.rcslock = !FlightInputHandler.RCSLock; } return(false); }
public override void OnLoad(ConfigNode node) { base.OnLoad(node); if (node.HasValue("RTAntennaTarget")) { try { Target = new Guid(node.GetValue("RTAntennaTarget")); } catch (FormatException) { Target = Guid.Empty; } } // Have RTDishRadians as a fallback to avoid corrupting save games if (node.HasValue("RTDishRadians")) { double temp_double; RTDishCosAngle = Double.TryParse(node.GetValue("RTDishRadians"), out temp_double) ? temp_double : 1.0; } if (node.HasValue("DishAngle")) { RTDishCosAngle = Math.Cos(DishAngle / 2 * Math.PI / 180); } if (node.HasValue("DeployFxModules")) { mDeployFxModuleIndices = KSPUtil.ParseArray <Int32>(node.GetValue("DeployFxModules"), new ParserMethod <Int32>(Int32.Parse)); } if (node.HasValue("ProgressFxModules")) { mProgressFxModuleIndices = KSPUtil.ParseArray <Int32>(node.GetValue("ProgressFxModules"), new ParserMethod <Int32>(Int32.Parse)); } if (node.HasNode("TRANSMITTER")) { RTLog.Notify("ModuleRTAntenna: Found TRANSMITTER block."); mTransmitterConfig = node.GetNode("TRANSMITTER"); mTransmitterConfig.AddValue("name", "ModuleRTDataTransmitter"); } }
public static bool QueryTask(int id, ETaskType type = ETaskType.task) { if (sInitilized && id != 0) { lock (sInstance.mLock) { Queue <ITask> queue; if (type == ETaskType.task) { queue = sInstance.mTasks; } else if (type == ETaskType.lateTask) { queue = sInstance.mLateTasks; } else { queue = null; } if (queue != null) { foreach (var t in queue) { if (t.Identify == id) { return(true); } } } } } #if UNITY_EDITOR else if (!sInitilized && Application.isPlaying) { RTLog.LogError(LogCat.Game, "MainThread not initialized."); } #endif return(false); }
public static double GetShortestSignalDelay(Guid id) { if (RTCore.Instance == null) { return(double.PositiveInfinity); } var satellite = RTCore.Instance.Satellites.Where(sat => sat.Guid.Equals(id)).FirstOrDefault(); if (satellite == null) { return(double.PositiveInfinity); } if (!RTCore.Instance.Network[satellite].Any()) { return(double.PositiveInfinity); } var shortestDelay = RTCore.Instance.Network[satellite].Min().Delay; RTLog.Verbose("Flight: Shortest signal delay from {0} to {1}", RTLogLevel.API, id, shortestDelay); return(shortestDelay); }
public static void AddSanctionedPilot(Guid id, Action <FlightCtrlState> autopilot) { var satellite = RTCore.Instance.Satellites[id]; if (satellite == null) { return; } foreach (var spu in satellite.SignalProcessors) { if (spu.FlightComputer == null) { continue; } if (spu.FlightComputer.SanctionedPilots.Contains(autopilot)) { continue; } RTLog.Verbose("Flight: {0} Adding Sanctioned Pilot", RTLogLevel.API, id); spu.FlightComputer.SanctionedPilots.Add(autopilot); } }
public static double GetSignalDelayToKSC(Guid id) { if (RTCore.Instance == null) { return(double.PositiveInfinity); } var satellite = RTCore.Instance.Satellites.Where(sat => sat.Guid.Equals(id)).FirstOrDefault(); if (satellite == null) { return(double.PositiveInfinity); } if (!RTCore.Instance.Network[satellite].Any(r => RTCore.Instance.Network.GroundStations.ContainsKey(r.Goal.Guid))) { return(double.PositiveInfinity); } var signalDelaytoKerbin = RTCore.Instance.Network[satellite].Where(r => RTCore.Instance.Network.GroundStations.ContainsKey(r.Goal.Guid)).Min().Delay; RTLog.Verbose("Connection from {0} to Kerbin Delay: {1}", RTLogLevel.API, id, signalDelaytoKerbin); return(signalDelaytoKerbin); }
private void AddTransmitter() { if (mTransmitterConfig == null || !mTransmitterConfig.HasValue("name")) { return; } var transmitters = part.FindModulesImplementing <IScienceDataTransmitter>(); if (transmitters.Count > 0) { RTLog.Notify("ModuleRTAntenna: Find TRANSMITTER success."); mTransmitter = transmitters.First(); } else { var copy = new ConfigNode(); mTransmitterConfig.CopyTo(copy); part.AddModule(copy); AddTransmitter(); RTLog.Notify("ModuleRTAntenna: Add TRANSMITTER success."); } }
/// <summary> /// Draws the content of the Presets section /// </summary> private void drawPresetsContent() { GUILayout.Label("Other mods can deliver their own RemoteTech_Settings.cfg and override config values. Here you can see what presets we've loaded:", this.mGuiRunningText); GUILayout.Space(15); List <String> presetList = this.mSettings.PreSets; if (this.mSettings.PreSets.Count <= 0) { GUILayout.Label("- no presets found", this.mGuiRunningText); } for (int i = presetList.Count - 1; i >= 0; i--) { String FolderName = presetList[i].Replace("/RemoteTechSettings", ".cfg").Trim(); GUILayout.BeginHorizontal("box", GUILayout.MaxHeight(15)); { GUILayout.Space(15); GUILayout.Label("- " + FolderName, this.mGuiListText, GUILayout.ExpandWidth(true)); if (GUILayout.Button("Reload", this.mGuiListButton, GUILayout.Width(50), GUILayout.Height(20))) { RTLog.Notify("Reload cfg {0}", RTLogLevel.LVL3, presetList[i]); this.mSettings.PreSets.RemoveAt(i); RTSettings.ReloadSettings(); } } GUILayout.EndHorizontal(); } // Reload all button if (presetList.Count >= 2) { if (GUILayout.Button("Reload All", this.mGuiListButton)) { this.mSettings.PreSets.Clear(); RTSettings.ReloadSettings(); } } }
public override bool Pop(FlightComputer f) { if (BaseField != null) { try { var field = (BaseField as WrappedField); if (field == null) // we lost the Wrapped field instance, this is due to the fact that the command was loaded from a save { if (NewValue != null) { var newfield = new WrappedField(BaseField, WrappedField.KspFieldFromBaseField(BaseField)); if (newfield.NewValueFromString(NewValueString)) { newfield.Invoke(); } } } else { // invoke the field value change field.Invoke(); } if (UIPartActionController.Instance != null) { UIPartActionController.Instance.UpdateFlight(); } } catch (Exception invokeException) { RTLog.Notify("BaseField InvokeAction() by '{0}' with message: {1}", RTLogLevel.LVL1, this.BaseField.guiName, invokeException.Message); } } return(false); }
protected override void LoadAssetAsync <T>(string assetPath, AssetHandler <T> handler, ErrorHandler errorhandler = null) { var asset = LoadAsset <T>(assetPath); if (asset == null) { var error = string.Format("Can't load Asset: \"{0}\"", assetPath); #if UNITY_EDITOR if (typeof(T) != typeof(AssetBundle)) { RTLog.LogError(LogCat.Asset, error); } #endif if (errorhandler != null) { errorhandler(error); } } else if (handler != null) { handler(asset); } }
public static void RemoveSanctionedPilot(Guid id, Action <FlightCtrlState> autopilot) { if (RTCore.Instance == null) { return; } var satellite = RTCore.Instance.Satellites.Where(sat => sat.Guid.Equals(id)).FirstOrDefault(); if (satellite == null || satellite.SignalProcessor == null) { return; } foreach (var spu in satellite.SignalProcessors) { if (spu.FlightComputer == null || spu.FlightComputer.SanctionedPilots == null) { continue; } RTLog.Verbose("Flight: {0} Removing Sanctioned Pilot", RTLogLevel.API, id); spu.FlightComputer.SanctionedPilots.Remove(autopilot); } }
protected override void OnDestroy() { foreach (var asset in mAssets.Values) { if (!asset.useAb && asset.assetInstence != null) { Resources.UnloadAsset(asset.assetInstence); } asset.assetInstence = null; } mAssets.Clear(); foreach (var ab in mAbs) { if (ab.assetBundle != null) { ab.assetBundle.Unload(true); ab.SetAssetBundle(null); } } #if UNITY_EDITOR RTLog.Log(LogCat.Asset, "All Assets Unloaded."); #endif }
private void AddTransmitter() { if (mTransmitterConfig == null || !mTransmitterConfig.HasValue("name")) { return; } var transmitters = part.FindModulesImplementing <IScienceDataTransmitter>(); if (transmitters.Count > 0) { RTLog.Notify("ModuleRTAntenna: Find TRANSMITTER success."); mTransmitter = transmitters.First(); } else { var copy = new ConfigNode(); mTransmitterConfig.CopyTo(copy); part.AddModule(copy); AddTransmitter(); RTLog.Notify("ModuleRTAntenna: Add TRANSMITTER success."); // Trigger onVesselWasModified after adding a new transmitter GameEvents.onVesselWasModified.Fire(this.part.vessel); } if (mTransmitter != null) { //overwrite default parameters of ModuleRTDataTransmitter (mTransmitter as ModuleRTDataTransmitter).PacketSize = RTPacketSize; (mTransmitter as ModuleRTDataTransmitter).PacketInterval = RTPacketInterval; (mTransmitter as ModuleRTDataTransmitter).PacketResourceCost = RTPacketResourceCost; } GUI_SciencePacketInterval = String.Format("{0} sec", RTPacketInterval); GUI_SciencePacketSize = String.Format("{0} Mits", RTPacketSize); GUI_SciencePacketCost = String.Format("{0} charge", RTPacketResourceCost); }
public void Unload() { if (assetBundle != null) { foreach (var meta in util.mAssets.Values) { if (meta.abData == this) { #if UNITY_EDITOR if (meta.assetInstence != null) { RTLog.LogFormat(LogCat.Asset, "Unload asset: \"{0}\"", meta.assetPath); } #endif meta.assetInstence = null; } } assetBundle.Unload(true); assetBundle = null; #if UNITY_EDITOR RTLog.LogFormat(LogCat.Asset, "Unload ab: \"{0}\"", name); #endif } }
/// <summary> /// 加载场景 /// </summary> /// <param name="sceneName"></param> /// <param name="displayTime"></param> public void LoadScene(string sceneName, float displayTime = 0, System.Action complateCallback = null) { if (mLoadingScene == sceneName) { #if UNITY_EDITOR RTLog.LogWarning(LogCat.Game, string.Format("Scene:{0} is loading, don't need to load it agin.", sceneName)); #endif if (complateCallback != null) { mLoadEndCallback += complateCallback; } return; } mLoadingScene = sceneName; mLoader.Reset(); mLoadEndCallback = complateCallback; mLoading = true; OnLoadBegin(mLoadingScene); LoadSceneTask task = new LoadSceneTask(mLoadingScene, displayTime, m_WaitForTimeWeight); task.PresetTask = new WaitTask(() => !PanelManager.HasAnyPanelClosing); SceneTask = task; mLoader.AddTask(SceneTask); mLoader.Start(); }
private void AddTransmitter() { if (mTransmitterConfig == null || !mTransmitterConfig.HasValue("name")) { return; } var transmitters = part.FindModulesImplementing <IScienceDataTransmitter>(); if (transmitters.Count > 0) { RTLog.Notify("ModuleRTAntenna: Find TRANSMITTER success."); mTransmitter = transmitters.First(); } else { var copy = new ConfigNode(); mTransmitterConfig.CopyTo(copy); part.AddModule(copy); AddTransmitter(); RTLog.Notify("ModuleRTAntenna: Add TRANSMITTER success."); // Trigger onVesselWasModified after adding a new transmitter GameEvents.onVesselWasModified.Fire(this.part.vessel); } }
private List <IScalarModule> FindFxModules(int[] indices, bool showUI) { var modules = new List <IScalarModule>(); if (indices == null) { return(modules); } foreach (int i in indices) { var item = base.part.Modules[i] as IScalarModule; if (item != null) { item.SetUIWrite(showUI); item.SetUIRead(showUI); modules.Add(item); } else { RTLog.Notify("ModuleRTAntenna: Part Module {0} doesn't implement IScalarModule", part.Modules[i].name); } } return(modules); }
public void Abort() { RTLog.LogError(LogCat.Asset, "Invoke static method \"AssetsUtil.AbortLoadAssetAsync<T>()\" instead of Abort()."); }
private IEnumerator Transmit() { var msg = new ScreenMessage(String.Format("[{0}]: Starting Transmission...", part.partInfo.title), 4f, ScreenMessageStyle.UPPER_LEFT); var msg_status = new ScreenMessage(String.Empty, 4.0f, ScreenMessageStyle.UPPER_LEFT); ScreenMessages.PostScreenMessage(msg); mBusy = true; while (mQueue.Any()) { RnDCommsStream commStream = null; var science_data = mQueue[0]; var data_amount = science_data.dataAmount; mQueue.RemoveAt(0); var subject = ResearchAndDevelopment.GetSubjectByID(science_data.subjectID); int packets = Mathf.CeilToInt(science_data.dataAmount / PacketSize); if (ResearchAndDevelopment.Instance != null) { // pre calculate the time interval - fix for x64 systems // workaround for issue #136 float time1 = Time.time; yield return(new WaitForSeconds(PacketInterval)); // get the delta time float x64PacketInterval = (Time.time - time1); RTLog.Notify("Changing RnDCommsStream timeout from {0} to {1}", PacketInterval, x64PacketInterval); commStream = new RnDCommsStream(subject, science_data.dataAmount, x64PacketInterval, science_data.transmitValue, ResearchAndDevelopment.Instance); } //StartCoroutine(SetFXModules_Coroutine(modules_progress, 0.0f)); float power = 0; while (packets > 0) { power += part.RequestResource("ElectricCharge", PacketResourceCost - power); if (power >= PacketResourceCost * 0.95) { float frame = Math.Min(PacketSize, data_amount); power -= PacketResourceCost; GUI_Status = "Uploading Data..."; data_amount -= frame; packets--; float progress = (science_data.dataAmount - data_amount) / science_data.dataAmount; //StartCoroutine(SetFXModules_Coroutine(modules_progress, progress)); msg_status.message = String.Format("[{0}]: Uploading Data... {1}", part.partInfo.title, progress.ToString("P0")); RTLog.Notify("[Transmitter]: Uploading Data... ({0}) - {1} Mits/sec. Packets to go: {2} - Files to Go: {3}", science_data.title, (PacketSize / PacketInterval).ToString("0.00"), packets, mQueue.Count); ScreenMessages.PostScreenMessage(msg_status, true); if (commStream != null) { commStream.StreamData(frame); } } else { msg.message = String.Format("<b><color=orange>[{0}]: Warning! Not Enough {1}!</color></b>", part.partInfo.title, RequiredResource); ScreenMessages.PostScreenMessage(msg, true); GUI_Status = String.Format("{0}/{1} {2}", power, PacketResourceCost, RequiredResource); } yield return(new WaitForSeconds(PacketInterval)); } yield return(new WaitForSeconds(PacketInterval * 2)); } mBusy = false; msg.message = String.Format("[{0}]: Done!", part.partInfo.title); ScreenMessages.PostScreenMessage(msg, true); GUI_Status = "Idle"; yield break; }
/// <summary> /// Restores the flightcomputer from the persistant /// </summary> /// <param name="n">Node with the informations for the flightcomputer</param> public void load(ConfigNode n) { RTLog.Notify("Loading Flightcomputer from persistent!"); if (!n.HasNode("FlightComputer")) { return; } // Wait while we are packed and store the current configNode if (Vessel.packed) { RTLog.Notify("Save flightconfig after unpacking"); fcLoadedConfigs = n; return; } // Load the current vessel from signalprocessor if we've no on the flightcomputer if (Vessel == null) { Vessel = SignalProcessor.Vessel; mRoverComputer.SetVessel(Vessel); } // Read Flightcomputer informations ConfigNode FlightNode = n.GetNode("FlightComputer"); TotalDelay = double.Parse(FlightNode.GetValue("TotalDelay")); ConfigNode ActiveCommands = FlightNode.GetNode("ActiveCommands"); ConfigNode Commands = FlightNode.GetNode("Commands"); // Read active commands if (ActiveCommands.HasNode()) { if (mActiveCommands.Count > 0) { mActiveCommands.Clear(); } foreach (ConfigNode cmdNode in ActiveCommands.nodes) { ICommand cmd = AbstractCommand.LoadCommand(cmdNode, this); if (cmd != null) { mActiveCommands[cmd.Priority] = cmd; cmd.Pop(this); } } } // Read queued commands if (Commands.HasNode()) { int qCounter = 0; // clear the current list if (mCommandQueue.Count > 0) { mCommandQueue.Clear(); } RTLog.Notify("Loading queued commands from persistent ..."); foreach (ConfigNode cmdNode in Commands.nodes) { ICommand cmd = AbstractCommand.LoadCommand(cmdNode, this); if (cmd != null) { // if delay = 0 we're ready for the extraDelay if (cmd.Delay == 0) { if (cmd is ManeuverCommand) { // TODO: Need better text RTUtil.ScreenMessage("You missed the maneuver burn!"); continue; } // if extraDelay is set, we've to calculate the elapsed time // and set the new extradelay based on the current time if (cmd.ExtraDelay > 0) { cmd.ExtraDelay = cmd.TimeStamp + cmd.ExtraDelay - RTUtil.GameTime; // Are we ready to handle the command ? if (cmd.ExtraDelay <= 0) { if (cmd is BurnCommand) { // TODO: Need better text RTUtil.ScreenMessage("You missed the burn command!"); continue; } else { // change the extra delay to x/100 cmd.ExtraDelay = (qCounter) / 100; } } } } mCommandQueue.Add(cmd); } } } }