private ConfigNode(ConfigNode parent) { _parentNode = parent; _localConfig = new Dictionary<string, object>(2); if(_parentNode != null) _parentNode.ConfigChanged += ParentNode_ConfigChanged; }
public static IM.BaseTexture CreateBaseTexture(ConfigNode node) { IM.BaseTexture baseTexture = null; Method method = Method.AUTO; if (node.HasValue("method")) method = (Method)ConfigNode.ParseEnum(typeof(Method), node.GetValue("method")); switch (method) { case Method.CURRENT: baseTexture = new IM.CurrentBaseTexture(); break; case Method.MULTIPLE: baseTexture = new IM.MultipleBaseTexture(); break; default: case Method.AUTO: baseTexture = new IM.AutoBaseTexture(); break; } return baseTexture; }
public void Save(ConfigNode node) { ConfigNode pNode = new ConfigNode("WING_PROPERTY"); pNode.AddValue(nameof(ID), ID); pNode.AddValue(nameof(value), value); node.AddNode(pNode); }
internal ConfigObjectNode(dynamic n, KeyType key, ConfigNode parent) : base(key, parent) { _children = new Dictionary<string, ConfigNode>(); var expando = n as IDictionary<string, object>; foreach (var kvp in expando) { ConfigNode valueNode; var newKey = new StringKey(kvp.Key); if (kvp.Value is ExpandoObject) { valueNode = ConfigNodeFactory.CreateConfigObjectNode(kvp.Value, newKey, this); } else if (kvp.Value is IList<object>) { valueNode = ConfigNodeFactory.CreateConfigListNode(kvp.Value, newKey, this); } else { valueNode = ConfigNodeFactory.CreateConfigLeafNode(kvp.Value, newKey, this); } _children.Add(kvp.Key, valueNode); } }
public void saveText(ConfigNode node) { saveMonoOverlay(node); node.AddValue("text", _text); node.AddValue("fontName", _fontName); node.AddValue("fontSize", _fontSize); }
public override void OnLoad(ConfigNode node) { PluginConfiguration config = PluginConfiguration.CreateForType<AntennaPrototype>(); config.load(); windowPosition = config.GetValue<Rect>("Window Position"); }
public override void OnSave(ConfigNode node) { PluginConfiguration config = PluginConfiguration.CreateForType<AntennaPrototype>(); config.SetValue("Window Position", windowPosition); config.save(); }
/// <summary> /// Loads the RealChute_Settings config to memory /// </summary> public RealChuteSettings() { ConfigNode node = new ConfigNode(), settings = new ConfigNode("REALCHUTE_SETTINGS"); Debug.Log("[RealChute]: Loading settings file."); if (!System.IO.File.Exists(RCUtils.settingsURL)) { Debug.LogWarning("[RealChute]: RealChute_Settings.cfg is missing component. Creating new version."); settings.AddValue("autoArm", autoArm); settings.AddValue("jokeActivated", jokeActivated); node.AddNode(settings); node.Save(RCUtils.settingsURL); } else { node = ConfigNode.Load(RCUtils.settingsURL); node.TryGetNode("REALCHUTE_SETTINGS", ref settings); bool missing = false; if (!settings.TryGetValue("autoArm", ref _autoArm)) { missing = true; } if (!settings.TryGetValue("jokeActivated", ref _jokeActivated)) { missing = true; } if (missing) { Debug.LogWarning("[RealChute]: RealChute_Settings.cfg is missing component. Fixing settings file."); settings.ClearValues(); settings.AddValue("autoArm", autoArm); settings.AddValue("jokeActivated", jokeActivated); node.ClearData(); node.AddNode(settings); node.Save(RCUtils.settingsURL); } } }
public ResourceInfo(ConfigNode node) { node.TryGetValue("name", ref this.name); resource = PartResourceLibrary.Instance.GetDefinition(this.Name); node.TryGetValue("realName", ref this.realName); node.TryGetValue("colour", ref this.colour); }
/// <summary> /// Initializes a new instance of the <see cref="ConfigNode" /> class. /// </summary> /// <param name="key">The key.</param> /// <param name="parent">The parent.</param> protected ConfigNode(KeyType key, ConfigNode parent) { _isSelected = false; _isExpanded = true; _key = key; _parent = parent; }
public static Layout Load(string name, ConfigNode node) { try { var layout = new Layout(name); foreach (var child in node.GetNodes()) { IElement element = Element.Create(child.name); if (element != null) { element.Load(child); layout.AddElement(element); } else { Historian.Print("Failed to load layout element of type '{0}'.", child.name); } } return layout; } catch { Historian.Print("Failed to load layout '{0}'.", name); } return Empty; }
public Grid2DControler(int width, int height, int numberOfClasses, ConfigNode node) : base(width * height, numberOfClasses, node) { _width = width; _height = height; this.StructureBuilder = new DefaultGrid2DStructureBuilder(width, height, NumberOfClasses); }
public void Configure(ConfigNode node) { ConfigNode[] pages = node.GetNodes("PAGE_DEFINITION"); if (pages != null && pages.Length > 0) { definitions = new PageDefinition[pages.Length]; for (int i = 0; i < pages.Length; ++i) { string variableName = pages[i].GetValue("variableName"); string range = pages[i].GetValue("range"); string page = pages[i].GetValue("page"); if (string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(range) || string.IsNullOrEmpty(page)) { JUtil.LogErrorMessage(this, "Incorrect page definition for page {0}", i); definitions = null; if (string.IsNullOrEmpty(definitionIn)) { // Make sure we aren't crashing later. definitionIn = definitionOut; } return; } definitions[i] = new PageDefinition(variableName, range, page); } } }
public void Save(ConfigNode node) { if (node.HasNode("KOLONIZATION")) { SettingsNode = node.GetNode("KOLONIZATION"); } else { SettingsNode = node.AddNode("KOLONIZATION"); } foreach (KolonizationEntry r in _LogInfo) { var rNode = new ConfigNode("KOLONY_ENTRY"); rNode.AddValue("BodyIndex", r.BodyIndex); rNode.AddValue("VesselId", r.VesselId); rNode.AddValue("LastUpdate", r.LastUpdate); rNode.AddValue("KolonyDate", r.KolonyDate); rNode.AddValue("GeologyResearch", r.GeologyResearch); rNode.AddValue("BotanyResearch", r.BotanyResearch); rNode.AddValue("KolonizationResearch", r.KolonizationResearch); rNode.AddValue("Science", r.Science); rNode.AddValue("Rep", r.Rep); rNode.AddValue("Funds", r.Funds); SettingsNode.AddNode(rNode); } //Reset cache KolonizationManager.Instance.ResetCache(); }
public void HandleSettings() { if (!File.Exists<KineTechAnimationModuleLoader>(SETTINGS_FILE_NAME)) { ConfigNode node = new ConfigNode(); node.AddValue("DumpDocumentationOnStartup", false); node.Save(IOUtils.GetFilePathFor(typeof(KineTechAnimationModuleLoader), SETTINGS_FILE_NAME)); } if (File.Exists<KineTechAnimationModuleLoader>(SETTINGS_FILE_NAME)) { ConfigNode node = ConfigNode.Load( IOUtils.GetFilePathFor(typeof(KineTechAnimationModuleLoader), SETTINGS_FILE_NAME)); if(node == null) return; //Dump Documentation if(node.HasValue("DumpDocumentationOnStartup")) { bool working = false; if(bool.TryParse(node.GetValue("DumpDocumentationOnStartup"), out working)) { GameObject dumperObject = new GameObject("Kine-Tech Animation - ConfigDocumentationGenerator"); dumperObject.AddComponent<KConfigDocumentationGenerator>(); GameObject.DontDestroyOnLoad(dumperObject); } } } }
public override void OnLoad(ConfigNode node) { base.OnLoad(node); if (!string.IsNullOrEmpty(moduleID) && node.HasValue(nameof(moduleID))) { string newID = node.GetValue(nameof(moduleID)); if (!string.Equals(moduleID, newID)) { var correctModule = part.Modules.OfType<CFGUtilPartModule>().FirstOrDefault(m => m != this && m.GetType() == this.GetType() && m.moduleID == newID); if (correctModule.IsNotNull()) { LogWarning("OnLoad was called with the wrong ModuleID ('" + newID + "'), but found the correct module to load"); correctModule.Load(node); } else { LogError("OnLoad was called with the wrong ModuleID and the correct module could not be found"); } return; } } configFieldList.Load(node); }
public void Save(ConfigNode node) { ConfigNode newNode = new ConfigNode("Resource"); newNode.AddValue("name", resource.name); newNode.AddValue("ratio", ratio); node.AddNode(newNode); }
private double _weightBuffer = 0; //Buffer for MomentumTerm Optimization #endregion Fields #region Constructors /// <summary> /// Instanciate a new synapse. You'll hardly need to call this as the preferred way to create neurons is using the neuron, layer or even network classes. /// </summary> /// <param name="source">The source neuron feeding this synapse.</param> /// <param name="target">The target neuron fed by this synapse.</param> /// <param name="weight">The weight of the synapse.</param> public Synapse(ConfigNode node, Neuron source, Neuron target, double weight) { node.AttatchToHost(this); _sourceNeuron = source; _targetNeuron = target; _weight = weight; }
/// <summary> /// Instanciate a new synapse. You'll hardly need to call this as the preferred way to create neurons is using the neuron, layer or even network classes. /// </summary> /// <param name="source">The source neuron feeding this synapse.</param> /// <param name="target">The target neuron fed by this synapse.</param> public Synapse(ConfigNode node, Neuron source, Neuron target) { node.AttatchToHost(this); _sourceNeuron = source; _targetNeuron = target; _weight = _config.RandomInitialWeight(); }
/// <summary> /// Initiates all the texture and model nodes in this model config /// </summary> public TextureConfig(ConfigNode node) { node.TryGetValue("name", ref _name); _cases = node.GetNodes("CASE_TEXTURE").Select(n => new CaseConfig(n)).ToDictionary(c => c, c => c.name); _canopies = node.GetNodes("CANOPY_TEXTURE").Select(n => new CanopyConfig(n)).ToDictionary(c => c, c => c.name); _models = node.GetNodes("CANOPY_MODEL").Select(n => new ModelConfig(n)).ToDictionary(m => m, m => m.name); }
/// <summary> /// Loads the RealChute_Settings config to memory /// </summary> public RealChuteSettings() { ConfigNode node = new ConfigNode(), settings = new ConfigNode("REALCHUTE_SETTINGS"); Debug.Log("[RealChute]: Loading settings file."); if (!File.Exists(RCUtils.settingsURL)) { Debug.LogError("[RealChute]: RealChute_Settings.cfg is missing. Creating new."); settings.AddValue("autoArm", this._autoArm); settings.AddValue("jokeActivated", this._jokeActivated); settings.AddValue("guiResizeUpdates", this._guiResizeUpdates); settings.AddValue("mustBeEngineer", this._mustBeEngineer); settings.AddValue("engineerLevel", this._engineerLevel); node.AddNode(settings); node.Save(RCUtils.settingsURL); } else { node = ConfigNode.Load(RCUtils.settingsURL); bool mustSave = false; if (!node.TryGetNode("REALCHUTE_SETTINGS", ref settings)) { SaveSettings(); return; } if (!settings.TryGetValue("autoArm", ref this._autoArm)) { mustSave = true; return; } if (!settings.TryGetValue("jokeActivated", ref this._jokeActivated)) { mustSave = true; return; } if (!settings.TryGetValue("guiResizeUpdates", ref this._guiResizeUpdates)) { mustSave = true; return; } if (!settings.TryGetValue("mustBeEngineer", ref this._mustBeEngineer)) { mustSave = true; return; } if (!settings.TryGetValue("engineerLevel", ref this._engineerLevel)) { mustSave = true; return; } this._presets = settings.GetNodes("PRESET"); if (mustSave) { SaveSettings(); } } }
protected override void OnSave(ConfigNode node) { foreach (string field in matchFields) { node.AddValue("FIELD", field); } }
internal IEnumerator<YieldInstruction> LoadItems(ConfigNode settings, System.Random random) { foreach (string type in KRESUtils.types.Values) { if (KRESUtils.GetRelevantBodies(type).Any(b => b.bodyName == this.Name)) { foreach (ConfigNode data in settings.GetNode(type).GetNode(this.Name).GetNodes("KRES_DATA")) { string resourceName = string.Empty; data.TryGetValue("name", ref resourceName); if (!PartResourceLibrary.Instance.resourceDefinitions.Contains(resourceName)) { continue; } if (type == "ore") { string path = Path.Combine(KRESUtils.GetSavePath(), "KRESTextures/" + name + "/" + resourceName + ".png"); if (File.Exists(path)) { ResourceItem item = new ResourceItem(data, resourceName, this.Name, random); resourceItems.Add(item); } } else if (type == "gas" || type == "liquid") { ResourceItem item = new ResourceItem(data, resourceName, this.Name, type, random); resourceItems.Add(item); } yield return null; } } } }
public override void OnSave(ConfigNode node) { PluginConfiguration config = PluginConfiguration.CreateForType<PluginTutorial>(); config.SetValue("Window Position", _windowPosition); config.save(); }
protected void saveMonoOverlay(ConfigNode node) { saveOverlay(node); node.AddValue("red", _red); node.AddValue("green", _green); node.AddValue("blue", _blue); }
/// <summary> /// Creates a material definition from a config node /// </summary> /// <param name="node">Node to initiate the material from</param> public MaterialDefinition(ConfigNode node) { node.TryGetValue("name", ref _name); node.TryGetValue("description", ref _description); node.TryGetValue("areaDensity", ref _areaDensity); node.TryGetValue("dragCoefficient", ref _dragCoefficient); }
private GUIStyle _windowStyle, _labelStyle; // Setup Gui Style #endregion Fields #region Methods public override void OnLoad(ConfigNode node) { PluginConfiguration config = PluginConfiguration.CreateForType<PluginTutorial>(); config.load(); _windowPosition = config.GetValue<Rect>("Window Position"); }
protected override void OnLoad(ConfigNode node) { if (node.HasValue("FIELD")) { matchFields.AddRange(node.GetValues("FIELD")); } }
public override void OnLoad(ConfigNode node) { base.OnLoad(node); //deprecated config conversion// ModuleConfig = node.HasValue("base_mass")? node : null; //****************************// }
/// <summary> /// Initiates all the texture and model nodes in this model config /// </summary> public TextureConfig(ConfigNode node) { node.TryGetValue("name", ref _name); foreach(ConfigNode cfg in node.nodes) { if (cfg.name == "CASE_TEXTURE") { CaseConfig parachuteCase = new CaseConfig(cfg); _cases.Add(parachuteCase); continue; } if (cfg.name == "CANOPY_TEXTURE") { CanopyConfig canopy = new CanopyConfig(cfg); _canopies.Add(canopy); continue; } if (cfg.name == "CANOPY_MODEL") { ModelConfig model = new ModelConfig(cfg); _models.Add(model); continue; } } if (_cases.Count > 0) { _caseNames = _cases.Select(c => c.name).ToArray(); } if (_canopies.Count > 0) { _canopyNames = _canopies.Select(c => c.name).ToArray(); } if (_models.Count > 0) { _modelNames = _models.Select(m => m.name).ToArray(); } }
public virtual void OnLoad(ConfigNode configNode) { async = configNode.HasValue("async") && ConfigNodeUtil.ParseValue <bool>(configNode, "async"); }
private void UpdateTankType(bool initializeAmounts = true) { if (oldType == type || type == null) { return; } // Copy the tank list from the tank definitiion TankDefinition def; if (!MFSSettings.tankDefinitions.Contains(type)) { Debug.LogError("Unable to find tank definition for type \"" + type + "\" reverting."); type = oldType; return; } def = MFSSettings.tankDefinitions[type]; oldType = type; // Build the new tank list. tankList = new FuelTankList(); for (int i = 0; i < def.tankList.Count; i++) { FuelTank tank = def.tankList[i]; // Pull the override from the list of overrides ConfigNode overNode = overrideListNodes.FirstOrDefault(n => n.GetValue("name") == tank.name); tankList.Add(tank.CreateCopy(this, overNode, initializeAmounts)); } // Destroy any managed resources that are not in the new type. HashSet <string> managed = MFSSettings.managedResources[part.name]; // if this throws, we have some big fish to fry bool needsMesage = false; for (int i = part.Resources.Count - 1; i >= 0; --i) { PartResource partResource = part.Resources[i]; string resname = partResource.resourceName; if (!managed.Contains(resname) || tankList.Contains(resname)) { continue; } part.Resources.list.RemoveAt(i); DestroyImmediate(partResource); needsMesage = true; } if (needsMesage) { RaiseResourceListChanged(); } if (!basemassOverride) { ParseBaseMass(def.basemass); } if (!baseCostOverride) { ParseBaseCost(def.baseCost); } if (isDatabaseLoad) { // being called in the SpaceCenter scene is assumed to be a database reload //FIXME is this really needed? return; } UpdateEngineIgnitor(def); massDirty = true; }
// Load the list of TANK overrides from the part file private void LoadTankListOverrides(ConfigNode node) { overrideListNodes = node.GetNodes("TANK"); }
public override void OnLoad(ConfigNode node) { if (!compatible) { return; } if (MFSSettings.tankDefinitions == null) { MFSSettings.Initialize(); } // Load the volume. If totalVolume is specified, use that to calc the volume // otherwise scale up the provided volume. No KSPField support for doubles if (node.HasValue("totalVolume") && double.TryParse(node.GetValue("totalVolume"), out totalVolume)) { ChangeTotalVolume(totalVolume); } else if (node.HasValue("volume") && double.TryParse(node.GetValue("volume"), out volume)) { totalVolume = volume * 100 / utilization; } using (PartMessageService.Instance.Ignore(this, null, typeof(PartResourcesChanged))) { if (isDatabaseLoad) { overrideListNodes = node.GetNodes("TANK"); ParseBaseMass(node); ParseBaseCost(node); typesAvailable = node.GetValues("typeAvailable"); RecordManagedResources(); } else if (isEditorOrFlight) { // The amounts initialized flag is there so that the tank type loading doesn't // try to set up any resources. They'll get loaded directly from the save. UpdateTankType(false); // Destroy any resources still hanging around from the LOADING phase for (int i = part.Resources.Count - 1; i >= 0; --i) { PartResource partResource = part.Resources[i]; if (!tankList.Contains(partResource.resourceName)) { continue; } part.Resources.list.RemoveAt(i); DestroyImmediate(partResource); } RaiseResourceListChanged(); // Setup the mass part.mass = mass; MassChanged(mass); // compute massDelta based on prefab, if available. if ((object)(part.partInfo) != null) { if ((object)(part.partInfo.partPrefab) != null) { massDelta = part.mass - part.partInfo.partPrefab.mass; } } } } }
/// <inheritdoc/> public override void OnLoad(ConfigNode node) { base.OnLoad(node); UpdateContextMenu(); // For the flight mode. }
private void onLoad(ConfigNode node) { //Debug.Log("onLoad"); SnackSnapshot.Instance().SetRebuildSnapshot(); }
private static void CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(ConfigNode progressTrackingNode) { foreach (var possibleNode in progressTrackingNode.nodes) { CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(possibleNode as ConfigNode); } //The kerbals are kept in a ConfigNode named 'crew', with 'crews' as a comma space delimited array of names. if (progressTrackingNode.name == "crew") { var kerbalNames = progressTrackingNode.GetValue("crews"); if (!string.IsNullOrEmpty(kerbalNames)) { var kerbalNamesSplit = kerbalNames.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); foreach (var kerbalName in kerbalNamesSplit.Where(k => !HighLogic.CurrentGame.CrewRoster.Exists(k))) { LunaLog.Log($"[LMP]: Generating missing kerbal from ProgressTracking: {kerbalName}"); var pcm = CrewGenerator.RandomCrewMemberPrototype(); pcm.ChangeName(kerbalName); HighLogic.CurrentGame.CrewRoster.AddCrewMember(pcm); //Also send it off to the server SystemsContainer.Get <KerbalSystem>().MessageSender.SendKerbalIfDifferent(pcm); } } } }
public override void Load(ConfigNode node) { base.Load(node); update_total_work(); }
/// <summary> /// Save data /// </summary> /// <param name="gameNode"></param> public override void OnSave(ConfigNode gameNode) { base.OnSave(gameNode); SaveScenario(gameNode); }
protected void runConverters(ProtoVessel vessel) { ProtoPartModuleSnapshot[] modules = null; ProtoPartModuleSnapshot recycler = null; ProtoPartModuleSnapshot snackProcessor = null; string activated = string.Empty; double currentTime = Planetarium.GetUniversalTime(); double lastUpdateTime, elapsedTime; Dictionary <string, double> inputs = new Dictionary <string, double>(); Dictionary <string, double> outputs = new Dictionary <string, double>(); double recyclerCapacity = 0f; double baseDemand, demand = 0f; double percentAcquired = 0f; double totalDemand = 0f; double totalObtained = 0f; double baseOutput = 0f; double output = 0f; ConfigNode moduleValues = null; //For each recycler and snack processor, run them manually. foreach (ProtoPartSnapshot pps in vessel.protoPartSnapshots) { modules = pps.modules.ToArray(); recycler = null; snackProcessor = null; activated = string.Empty; recyclerCapacity = 0f; baseDemand = 0f; demand = 0f; percentAcquired = 1.0f; totalDemand = 0f; totalObtained = 0f; baseOutput = 0f; inputs.Clear(); outputs.Clear(); //See if the part has a recycler or snack processor that's active. for (int snapModIndex = 0; snapModIndex < modules.Length; snapModIndex++) { moduleValues = modules[snapModIndex].moduleValues; if (modules[snapModIndex].moduleName == "SoilRecycler") { //Activation status if (moduleValues.HasValue("IsActivated")) { activated = moduleValues.GetValue("IsActivated").ToLower(); if (activated == "true") { Log("Found an active soil recycler"); recycler = modules[snapModIndex]; } } } else if (modules[snapModIndex].moduleName == "SnackProcessor") { //Activation status if (moduleValues.HasValue("IsActivated")) { activated = moduleValues.GetValue("IsActivated").ToLower(); if (activated == "true") { Log("Found an active snack processor"); snackProcessor = modules[snapModIndex]; } } } if (recycler != null || snackProcessor != null) { break; } } if (recycler != null) { Log("Running soil recycler..."); lastUpdateTime = double.Parse(recycler.moduleValues.GetValue("lastUpdateTime")); elapsedTime = currentTime - lastUpdateTime; //Get the resource ratios getResourceRatios(pps, inputs, outputs, out recyclerCapacity); //Calculate base demand baseDemand = elapsedTime * recyclerCapacity * SnacksProperties.SnacksPerMeal * SnacksProperties.MealsPerDay; Debug.Log("elapsedTime: " + elapsedTime + " baseDemand: " + baseDemand + " recyclerCapacity: " + recyclerCapacity + " SnacksPerMeal: " + SnacksProperties.SnacksPerMeal); //Now request all the input resources foreach (string resourceName in inputs.Keys) { //Skip ElectricCharge. There's no way to know how much is produced while you're away... if (resourceName == "ElectricCharge") { continue; } //Calculate demand demand = inputs[resourceName] * baseDemand; totalDemand += demand; //Request the resource totalObtained += GetResource(vessel.protoPartSnapshots, resourceName, demand); Debug.Log("Requested " + demand + " units of " + resourceName + " and total received thus far: " + totalObtained); } //Calculate base output percentAcquired = totalObtained / totalDemand; if (percentAcquired > 0.999) { percentAcquired = 1.0f; } baseOutput = baseDemand * percentAcquired * SnacksProperties.RecyclerEfficiency; if (baseOutput < 0.00000000f) { baseOutput = 0f; } Debug.Log("baseOutput: " + baseOutput + " RecyclerEfficiency: " + SnacksProperties.RecyclerEfficiency); //Get the output ratios and process them. foreach (string resourceName in outputs.Keys) { output = outputs[resourceName] * baseOutput; if (output > 0f) { AddResource(vessel.protoPartSnapshots, resourceName, output); } Debug.Log("Added " + outputs[resourceName] * baseOutput + " units of " + resourceName); } //Update the last update time. recycler.moduleValues.SetValue("lastUpdateTime", Planetarium.GetUniversalTime()); } if (snackProcessor != null) { Log("Running snack processor..."); lastUpdateTime = double.Parse(snackProcessor.moduleValues.GetValue("lastUpdateTime")); elapsedTime = currentTime - lastUpdateTime; //Get the resource ratios recyclerCapacity = 0f; inputs.Clear(); outputs.Clear(); getResourceRatios(pps, inputs, outputs, out recyclerCapacity); //Calculate base demand float efficiency = SnacksProperties.ProductionEfficiency; baseDemand = elapsedTime * (SnacksProperties.ProductionEfficiency / 100); //Now request all the input resources percentAcquired = 1.0f; totalDemand = 0f; totalObtained = 0f; foreach (string resourceName in inputs.Keys) { //Skip ElectricCharge. There's no way to know how much is produced while you're away... if (resourceName == "ElectricCharge") { continue; } //Calculate demand demand = inputs[resourceName] * baseDemand; totalDemand += demand; //Request the resource totalObtained += GetResource(vessel.protoPartSnapshots, resourceName, demand); Log("Requested " + demand + " units of " + resourceName + " and received " + totalObtained + " units"); } //Calculate base output percentAcquired = totalObtained / totalDemand; if (percentAcquired > 0.999) { percentAcquired = 1.0f; } baseOutput = baseDemand * percentAcquired; if (baseOutput < 0.00000000f) { baseOutput = 0f; } //Get the output ratios and process them. foreach (string resourceName in outputs.Keys) { output = outputs[resourceName] * baseOutput; if (output > 0f) { AddResource(vessel.protoPartSnapshots, resourceName, output); Log("Added " + output + " units of " + resourceName); } } //Update the last update time. snackProcessor.moduleValues.SetValue("lastUpdateTime", Planetarium.GetUniversalTime()); } } }
/// <summary> /// Load scenario details for each vessel with BV controller /// </summary> public void LoadScenario() { if (scenarioNode != null) { var controllers = BonVoyage.Instance.BVControllers; int count = controllers.Count; for (int i = 0; i < count; i++) { BVController controller = controllers[i]; if (controller.vessel != null) { ConfigNode controllerNode = scenarioNode.GetNode("CONTROLLER", "vesselId", controller.vessel.id.ToString()); if (controllerNode != null) { ConfigNode subNode = controllerNode.GetNode("BATTERIES"); if (subNode != null) { controller.batteries.UseBatteries = Convert.ToBoolean(subNode.GetValue("useBatteries")); controller.batteries.MaxUsedEC = Convert.ToDouble(subNode.GetValue("maxUsedEC")); controller.batteries.ECPerSecondConsumed = Convert.ToDouble(subNode.GetValue("ecPerSecondConsumed")); controller.batteries.ECPerSecondGenerated = Convert.ToDouble(subNode.GetValue("ecPerSecondGenerated")); controller.batteries.CurrentEC = Convert.ToDouble(subNode.GetValue("currentEC")); } subNode = controllerNode.GetNode("FUEL_CELLS"); if (subNode != null) { controller.fuelCells.Use = Convert.ToBoolean(subNode.GetValue("useFuelCells")); controller.fuelCells.OutputValue = Convert.ToDouble(subNode.GetValue("outputEC")); var resources = subNode.GetNodes("RESOURCE"); controller.fuelCells.InputResources.Clear(); for (int r = 0; r < resources.Length; r++) { Resource ir = new Resource(); ir.Name = resources[r].GetValue("name"); ir.Ratio = Convert.ToDouble(resources[r].GetValue("ratio")); ir.MaximumAmountAvailable = Convert.ToDouble(resources[r].GetValue("maximumAmount")); ir.CurrentAmountUsed = Convert.ToDouble(resources[r].GetValue("currentAmount")); controller.fuelCells.InputResources.Add(ir); } } subNode = controllerNode.GetNode("PROPELLANTS"); if (subNode != null) { var propellants = subNode.GetNodes("FUEL"); controller.propellants.Clear(); for (int r = 0; r < propellants.Length; r++) { Fuel ir = new Fuel(); ir.Name = propellants[r].GetValue("name"); ir.FuelFlow = Convert.ToDouble(propellants[r].GetValue("fuelFlow")); ir.MaximumAmountAvailable = Convert.ToDouble(propellants[r].GetValue("maximumAmount")); ir.CurrentAmountUsed = Convert.ToDouble(propellants[r].GetValue("currentAmount")); controller.propellants.Add(ir); } } } } } } }
private void Start() { InstallationPathWarning.Warn("SCANsatRPM"); // Arrrgh. if (!string.IsNullOrEmpty(iconColorSelf)) { iconColorSelfValue = ConfigNode.ParseColor32(iconColorSelf); } if (!string.IsNullOrEmpty(iconColorTarget)) { iconColorTargetValue = ConfigNode.ParseColor32(iconColorTarget); } if (!string.IsNullOrEmpty(iconColorUnvisitedAnomaly)) { iconColorUnvisitedAnomalyValue = ConfigNode.ParseColor32(iconColorUnvisitedAnomaly); } if (!string.IsNullOrEmpty(iconColorVisitedAnomaly)) { iconColorVisitedAnomalyValue = ConfigNode.ParseColor32(iconColorVisitedAnomaly); } if (!string.IsNullOrEmpty(iconColorShadow)) { iconColorShadowValue = ConfigNode.ParseColor32(iconColorShadow); } if (!string.IsNullOrEmpty(iconColorAP)) { iconColorAPValue = ConfigNode.ParseColor32(iconColorAP); } if (!string.IsNullOrEmpty(iconColorPE)) { iconColorPEValue = ConfigNode.ParseColor32(iconColorPE); } if (!string.IsNullOrEmpty(iconColorANDN)) { iconColorANDNValue = ConfigNode.ParseColor32(iconColorANDN); } if (!string.IsNullOrEmpty(iconColorNode)) { iconColorNodeValue = ConfigNode.ParseColor32(iconColorNode); } if (!string.IsNullOrEmpty(trailColor)) { trailColorValue = ConfigNode.ParseColor32(trailColor); } // Referencing the parent project should work, shouldn't it. persistentVarName = "scansat" + internalProp.propID; persistence = new PersistenceAccessor(part); showLines = persistence.GetBool(persistentVarName + "lines") ?? true; trailMaterial = JUtil.DrawLineMaterial(); LeaveTrail(); if (!string.IsNullOrEmpty(scaleBar) && !string.IsNullOrEmpty(scaleLabels) && !string.IsNullOrEmpty(scaleLevels)) { scaleBarTexture = GameDatabase.Instance.GetTexture(scaleBar, false); scaleLabelTexture = GameDatabase.Instance.GetTexture(scaleLabels, false); var scales = new List <float>(); foreach (string scl in scaleLevels.Split(',')) { float scale; if (float.TryParse(scl.Trim(), out scale)) { scales.Add(scale / 1000); } } scaleLevelValues = scales.ToArray(); Array.Sort(scaleLevelValues); scaleLabelSpan = 1f / scaleLevelValues.Length; } // Now the fun bit: Locate all cfg files depicting map features anywhere. foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("JSISCANSATVECTORMARK")) { mapMarkup.Add(new MapMarkupLine(node)); } startupComplete = true; }
public override void OnLoad(ConfigNode node) { // get version of the savegame // note: if there isn't a version this is either a new game, or the first public release (that didn't have versioning) string version = node.HasValue("version") ? node.GetValue("version") : node.HasNode("kerbals") ? "0.9.9.0" : current_version; // this is an unsupported version, attempt a total clean up and pray // note: currently unused if (string.CompareOrdinal(version, "0.9.9.0") < 0) { Lib.Log("loading save from unsupported version " + version); kerbals.Clear(); vessels.Clear(); bodies.Clear(); notifications = new notification_data(); return; } kerbals.Clear(); if (node.HasNode("kerbals")) { ConfigNode kerbals_node = node.GetNode("kerbals"); foreach(ConfigNode kerbal_node in kerbals_node.GetNodes()) { kerbal_data kd = new kerbal_data(); kd.resque = Lib.ConfigValue(kerbal_node, "resque", 1u); kd.disabled = Lib.ConfigValue(kerbal_node, "disabled", 0u); kd.living_space = Lib.ConfigValue(kerbal_node, "living_space", 1.0); // since 0.9.9.4 kd.entertainment = Lib.ConfigValue(kerbal_node, "entertainment", 1.0); // since 0.9.9.4 kd.shielding = Lib.ConfigValue(kerbal_node, "shielding", 0.0); // since 0.9.9.4 kd.space_name = Lib.ConfigValue(kerbal_node, "space_name", ""); // since 0.9.9.4 kd.kmon = new Dictionary<string, kmon_data>(); if (kerbal_node.HasNode("kmon")) // since 0.9.9.5 { foreach(var cfg in kerbal_node.GetNode("kmon").GetNodes()) { kmon_data kmon = new kmon_data(); kmon.problem = Lib.ConfigValue(cfg, "problem", 0.0); kmon.message = Lib.ConfigValue(cfg, "message", 0u); kmon.time_since = Lib.ConfigValue(cfg, "time_since", 0.0); kd.kmon.Add(cfg.name, kmon); } } kerbals.Add(kerbal_node.name.Replace("___", " "), kd); } } vessels.Clear(); if (node.HasNode("vessels")) { ConfigNode vessels_node = node.GetNode("vessels"); foreach(ConfigNode vessel_node in vessels_node.GetNodes()) { vessel_data vd = new vessel_data(); vd.msg_signal = Lib.ConfigValue(vessel_node, "msg_signal", 0u); vd.msg_belt = Lib.ConfigValue(vessel_node, "msg_belt", 0u); vd.cfg_ec = Lib.ConfigValue(vessel_node, "cfg_ec", 1u); vd.cfg_supply = Lib.ConfigValue(vessel_node, "cfg_supply", 1u); vd.cfg_signal = Lib.ConfigValue(vessel_node, "cfg_signal", 1u); vd.cfg_malfunction = Lib.ConfigValue(vessel_node, "cfg_malfunction", 1u); vd.cfg_storm = Lib.ConfigValue(vessel_node, "cfg_storm", 1u); // since 0.9.9.5 vd.cfg_highlights = Lib.ConfigValue(vessel_node, "cfg_highlights", 1u); // since 0.9.9.5 vd.cfg_showlink = Lib.ConfigValue(vessel_node, "cfg_showlink", 0u); // since 0.9.9.8 vd.notes = Lib.ConfigValue(vessel_node, "notes", "").Replace("$NEWLINE", "\n"); // since 0.9.9.1 vd.group = Lib.ConfigValue(vessel_node, "group", "NONE"); // since 0.9.9.1 vd.vmon = new Dictionary<string, vmon_data>(); if (vessel_node.HasNode("vmon")) // since 0.9.9.5 { foreach(var cfg in vessel_node.GetNode("vmon").GetNodes()) { vmon_data vmon = new vmon_data(); vmon.message = Lib.ConfigValue(cfg, "message", 0u); vd.vmon.Add(cfg.name, vmon); } } vd.scansat_id = new List<uint>(); foreach(string s in vessel_node.GetValues("scansat_id")) // since 0.9.9.5 { vd.scansat_id.Add(Convert.ToUInt32(s)); } vessels.Add(new Guid(vessel_node.name), vd); } } bodies.Clear(); if (node.HasNode("bodies")) { ConfigNode bodies_node = node.GetNode("bodies"); foreach(ConfigNode body_node in bodies_node.GetNodes()) { body_data bd = new body_data(); bd.storm_time = Lib.ConfigValue(body_node, "storm_time", 0.0); bd.storm_age = Lib.ConfigValue(body_node, "storm_age", 0.0); bd.storm_state = Lib.ConfigValue(body_node, "storm_state", 0u); bd.msg_storm = Lib.ConfigValue(body_node, "msg_storm", 0u); bodies.Add(body_node.name.Replace("___", " "), bd); } } notifications = new notification_data(); if (node.HasNode("notifications")) { ConfigNode n_node = node.GetNode("notifications"); notifications.next_death_report = Lib.ConfigValue(n_node, "next_death_report", 0u); notifications.next_tutorial = Lib.ConfigValue(n_node, "next_tutorial", 0u); notifications.death_counter = Lib.ConfigValue(n_node, "death_counter", 0u); notifications.last_death_counter = Lib.ConfigValue(n_node, "last_death_counter", 0u); notifications.first_belt_crossing = Lib.ConfigValue(n_node, "first_belt_crossing", 0u); notifications.first_signal_loss = Lib.ConfigValue(n_node, "first_signal_loss", 0u); notifications.first_malfunction = Lib.ConfigValue(n_node, "first_malfunction", 0u); } // versions before 0.9.9.5 used a different structure to remember message sent // mute the message system for a few seconds to avoid the user being bombarded by messages if (string.CompareOrdinal(version, "0.9.9.5") < 0) { Message.MuteInternal(); base.StartCoroutine(CallbackUtil.DelayedCallback(10.0f, Message.UnmuteInternal)); } // versions before 0.9.9.5 didn't have profiles, and didn't use CRP food/oxygen values // scale all amounts of them in existing vessels, to not break savegames if (string.CompareOrdinal(version, "0.9.9.5") < 0) { foreach(Vessel v in FlightGlobals.Vessels.FindAll(k => !k.loaded)) { foreach(var part in v.protoVessel.protoPartSnapshots) { var food = part.resources.Find(k => k.resourceName == "Food"); if (food != null) { food.resourceValues.SetValue("amount", (Lib.ConfigValue(food.resourceValues, "amount", 0.0f) * 10.0f).ToString()); food.resourceValues.SetValue("maxAmount", (Lib.ConfigValue(food.resourceValues, "maxAmount", 0.0f) * 10.0f).ToString()); } var oxygen = part.resources.Find(k => k.resourceName == "Oxygen"); if (oxygen != null) { oxygen.resourceValues.SetValue("amount", (Lib.ConfigValue(oxygen.resourceValues, "amount", 0.0f) * 1000.0f).ToString()); oxygen.resourceValues.SetValue("maxAmount", (Lib.ConfigValue(oxygen.resourceValues, "maxAmount", 0.0f) * 1000.0f).ToString()); } } } } // if an old savegame was imported, log some debug info if (version != current_version) Lib.Log("savegame converted from version " + version); }
/// <summary> /// Load data /// </summary> /// <param name="gameNode"></param> public override void OnLoad(ConfigNode gameNode) { base.OnLoad(gameNode); scenarioNode = gameNode; }
/// <summary> /// Adds a part to the inventory using a ConfigNode of a Part /// </summary> /// <param name="partNode">The ConfigNode to add</param> public InventoryPart AddPart(ConfigNode partNode) { InventoryPart convertedPart = new InventoryPart(partNode); return(AddPart(convertedPart)); }
internal void ChangeFacility() { RemoveOldSettings(); Log.Normal("FacEditor: Change called"); KKFacilityType newType; try { newType = (KKFacilityType)Enum.Parse(typeof(KKFacilityType), facType, true); } catch { //Log.UserError("Unknown Facility Type: " + cfgNode.GetValue("FacilityType") + " in file: " + instance.configPath ); return; } selectedObject.facilityType = newType; selectedObject.FacilityType = facType; if (newType == KKFacilityType.None) { return; } else { selectedObject.hasFacilities = true; } // use a face cfgnode for initialization ConfigNode cfgNode = new ConfigNode(); switch (newType) { case KKFacilityType.GroundStation: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <GroundStation>().ParseConfig(cfgNode)); break; case KKFacilityType.TrackingStation: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <GroundStation>().ParseConfig(cfgNode)); selectedObject.facilityType = KKFacilityType.GroundStation; break; case KKFacilityType.FuelTanks: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <FuelTanks>().ParseConfig(cfgNode)); break; case KKFacilityType.Research: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <Research>().ParseConfig(cfgNode)); break; case KKFacilityType.Business: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <Business>().ParseConfig(cfgNode)); break; case KKFacilityType.Hangar: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <Hangar>().ParseConfig(cfgNode)); break; case KKFacilityType.Barracks: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <Barracks>().ParseConfig(cfgNode)); break; case KKFacilityType.LandingGuide: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <LandingGuide>().ParseConfig(cfgNode)); break; case KKFacilityType.TouchdownGuideL: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <TouchdownGuideL>().ParseConfig(cfgNode)); break; case KKFacilityType.TouchdownGuideR: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <TouchdownGuideR>().ParseConfig(cfgNode)); break; case KKFacilityType.RadarStation: selectedObject.myFacilities.Add(selectedObject.gameObject.AddComponent <RadarStation>().ParseConfig(cfgNode)); break; } Log.Normal("FacEditor: Change Finished"); }
public SupplyData(ConfigNode node) { message = Lib.ConfigValue(node, "message", 0u); }
public override void OnSave(ConfigNode node) { // save current version node.AddValue("version", current_version); ConfigNode kerbals_node = node.AddNode("kerbals"); foreach(var p in kerbals) { kerbal_data kd = p.Value; ConfigNode kerbal_node = kerbals_node.AddNode(p.Key.Replace(" ", "___")); kerbal_node.AddValue("resque", kd.resque); kerbal_node.AddValue("disabled", kd.disabled); kerbal_node.AddValue("living_space", kd.living_space); kerbal_node.AddValue("entertainment", kd.entertainment); kerbal_node.AddValue("shielding", kd.shielding); kerbal_node.AddValue("space_name", kd.space_name); var kmon_node = kerbal_node.AddNode("kmon"); foreach(var q in kd.kmon) { var kmon_subnode = kmon_node.AddNode(q.Key); kmon_subnode.AddValue("problem", q.Value.problem); kmon_subnode.AddValue("message", q.Value.message); kmon_subnode.AddValue("time_since", q.Value.time_since); } } ConfigNode vessels_node = node.AddNode("vessels"); foreach(var p in vessels) { vessel_data vd = p.Value; ConfigNode vessel_node = vessels_node.AddNode(p.Key.ToString()); vessel_node.AddValue("msg_signal", vd.msg_signal); vessel_node.AddValue("msg_belt", vd.msg_belt); vessel_node.AddValue("cfg_ec", vd.cfg_ec); vessel_node.AddValue("cfg_supply", vd.cfg_supply); vessel_node.AddValue("cfg_signal", vd.cfg_signal); vessel_node.AddValue("cfg_malfunction", vd.cfg_malfunction); vessel_node.AddValue("cfg_storm", vd.cfg_storm); vessel_node.AddValue("cfg_highlights", vd.cfg_highlights); vessel_node.AddValue("cfg_showlink", vd.cfg_showlink); vessel_node.AddValue("notes", vd.notes.Replace("\n", "$NEWLINE")); vessel_node.AddValue("group", vd.group); var vmon_node = vessel_node.AddNode("vmon"); foreach(var q in vd.vmon) { var vmon_subnode = vmon_node.AddNode(q.Key); vmon_subnode.AddValue("message", q.Value.message); } foreach(uint id in vd.scansat_id) { vessel_node.AddValue("scansat_id", id.ToString()); } } ConfigNode bodies_node = node.AddNode("bodies"); foreach(var p in bodies) { body_data bd = p.Value; ConfigNode body_node = bodies_node.AddNode(p.Key.Replace(" ", "___")); body_node.AddValue("storm_time", bd.storm_time); body_node.AddValue("storm_age", bd.storm_age); body_node.AddValue("storm_state", bd.storm_state); body_node.AddValue("msg_storm", bd.msg_storm); } ConfigNode notifications_node = node.AddNode("notifications"); notifications_node.AddValue("next_death_report", notifications.next_death_report.ToString()); notifications_node.AddValue("next_tutorial", notifications.next_tutorial.ToString()); notifications_node.AddValue("death_counter", notifications.death_counter.ToString()); notifications_node.AddValue("last_death_counter", notifications.last_death_counter.ToString()); notifications_node.AddValue("first_belt_crossing", notifications.first_belt_crossing.ToString()); notifications_node.AddValue("first_signal_loss", notifications.first_signal_loss.ToString()); notifications_node.AddValue("first_malfunction", notifications.first_malfunction.ToString()); }
internal MASPageEllipse(ConfigNode config, InternalProp prop, MASFlightComputer comp, MASMonitor monitor, Transform pageRoot, float depth) : base(config, prop, comp) { string startColorString = string.Empty; if (!config.TryGetValue("startColor", ref startColorString)) { throw new ArgumentException("Unable to find 'startColor' in ELLIPSE " + name); } string endColorString = string.Empty; if (!config.TryGetValue("endColor", ref endColorString)) { endColorString = string.Empty; } string startWidthString = string.Empty; if (!config.TryGetValue("startWidth", ref startWidthString)) { throw new ArgumentException("Unable to find 'startWidth' in ELLIPSE " + name); } string endWidthString = string.Empty; if (!config.TryGetValue("endWidth", ref endWidthString)) { endWidthString = string.Empty; } numVertices = 0; if (!config.TryGetValue("vertexCount", ref numVertices)) { throw new ArgumentException("Unable to find 'vertexCount' in ELLIPSE " + name); } else if (numVertices < 3) { throw new ArgumentException("'vertexCount' must be at least 3 in ELLIPSE " + name); } Vector2 position = Vector2.zero; if (!config.TryGetValue("position", ref position)) { throw new ArgumentException("Unable to find 'position' in ELLIPSE " + name); } string variableName = string.Empty; if (config.TryGetValue("variable", ref variableName)) { variableName = variableName.Trim(); } string rotationVariableName = string.Empty; config.TryGetValue("rotation", ref rotationVariableName); lineOrigin = new GameObject(); lineOrigin.name = Utility.ComposeObjectName(pageRoot.gameObject.name, this.GetType().Name, name, (int)(-depth / MASMonitor.depthDelta)); lineOrigin.layer = pageRoot.gameObject.layer; lineOrigin.transform.parent = pageRoot; lineOrigin.transform.position = pageRoot.position; lineOrigin.transform.Translate(monitor.screenSize.x * -0.5f + position.x, monitor.screenSize.y * 0.5f - position.y, depth); // add renderer stuff lineMaterial = new Material(MASLoader.shaders["MOARdV/Monitor"]); lineRenderer = lineOrigin.AddComponent <LineRenderer>(); lineRenderer.useWorldSpace = false; lineRenderer.material = lineMaterial; lineRenderer.startColor = startColor; lineRenderer.endColor = endColor; lineRenderer.startWidth = startWidth; lineRenderer.endWidth = endWidth; ++numVertices; lineRenderer.positionCount = numVertices; vertices = new Vector3[numVertices]; string textureName = string.Empty; if (config.TryGetValue("texture", ref textureName)) { Texture tex = GameDatabase.Instance.GetTexture(textureName, false); if (tex != null) { lineMaterial.mainTexture = tex; inverseTextureWidth = 1.0f / (float)tex.width; usesTexture = true; } } string startAngleName = string.Empty; if (config.TryGetValue("startAngle", ref startAngleName)) { variableRegistrar.RegisterVariableChangeCallback(startAngleName, (double newValue) => { startAngle = (float)newValue; RecalculateVertices(); }); } else { startAngle = 0.0f; } string endAngleName = string.Empty; if (config.TryGetValue("endAngle", ref endAngleName)) { if (string.IsNullOrEmpty(startAngleName)) { throw new ArgumentException("Missing 'startAngle', but found 'endAngle' in ELLIPSE " + name); } else { variableRegistrar.RegisterVariableChangeCallback(endAngleName, (double newValue) => { endAngle = (float)newValue; RecalculateVertices(); }); } } else if (!string.IsNullOrEmpty(startAngleName)) { throw new ArgumentException("Found 'startAngle', but missing 'endAngle' in ELLIPSE " + name); } else { endAngle = 360.0f; } string radiusXName = string.Empty; if (!config.TryGetValue("radiusX", ref radiusXName)) { throw new ArgumentException("Unable to find 'radiusX' in ELLIPSE " + name); } string radiusYName = string.Empty; if (!config.TryGetValue("radiusY", ref radiusYName)) { Action <double> newRadius = (double newValue) => { radiusX = (float)newValue; radiusY = radiusX; RecalculateVertices(); }; variableRegistrar.RegisterVariableChangeCallback(radiusXName, newRadius); } else { Action <double> newRadiusX = (double newValue) => { radiusX = (float)newValue; RecalculateVertices(); }; variableRegistrar.RegisterVariableChangeCallback(radiusXName, newRadiusX); Action <double> newRadiusY = (double newValue) => { radiusY = (float)newValue; RecalculateVertices(); }; variableRegistrar.RegisterVariableChangeCallback(radiusYName, newRadiusY); } RenderPage(false); if (!string.IsNullOrEmpty(variableName)) { // Disable the lines if we're in variable mode lineOrigin.SetActive(false); variableRegistrar.RegisterVariableChangeCallback(variableName, VariableCallback); } else { lineOrigin.SetActive(true); } if (!string.IsNullOrEmpty(rotationVariableName)) { variableRegistrar.RegisterVariableChangeCallback(rotationVariableName, RotationCallback); } if (string.IsNullOrEmpty(endColorString)) { Color32 namedColor; if (comp.TryGetNamedColor(startColorString, out namedColor)) { startColor = namedColor; lineRenderer.startColor = startColor; lineRenderer.endColor = startColor; } else { string[] startColors = Utility.SplitVariableList(startColorString); if (startColors.Length < 3 || startColors.Length > 4) { throw new ArgumentException("startColor does not contain 3 or 4 values in ELLIPSE " + name); } Action <double> startColorR = (double newValue) => { startColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; lineRenderer.endColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[0], startColorR); Action <double> startColorG = (double newValue) => { startColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; lineRenderer.endColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[1], startColorG); Action <double> startColorB = (double newValue) => { startColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; lineRenderer.endColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[2], startColorB); if (startColors.Length == 4) { Action <double> startColorA = (double newValue) => { startColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; lineRenderer.endColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[3], startColorA); } } } else { Color32 namedColor; if (comp.TryGetNamedColor(startColorString, out namedColor)) { startColor = namedColor; lineRenderer.startColor = startColor; lineRenderer.endColor = endColor; } else { string[] startColors = Utility.SplitVariableList(startColorString); if (startColors.Length < 3 || startColors.Length > 4) { throw new ArgumentException("startColor does not contain 3 or 4 values in ELLIPSE " + name); } Action <double> startColorR = (double newValue) => { startColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[0], startColorR); Action <double> startColorG = (double newValue) => { startColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[1], startColorG); Action <double> startColorB = (double newValue) => { startColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[2], startColorB); if (startColors.Length == 4) { Action <double> startColorA = (double newValue) => { startColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.startColor = startColor; }; variableRegistrar.RegisterVariableChangeCallback(startColors[3], startColorA); } } if (comp.TryGetNamedColor(endColorString, out namedColor)) { endColor = namedColor; lineRenderer.startColor = startColor; lineRenderer.endColor = endColor; } else { string[] endColors = Utility.SplitVariableList(endColorString); if (endColors.Length < 3 || endColors.Length > 4) { throw new ArgumentException("endColor does not contain 3 or 4 values in ELLIPSE " + name); } Action <double> endColorR = (double newValue) => { endColor.r = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.endColor = endColor; }; variableRegistrar.RegisterVariableChangeCallback(endColors[0], endColorR); Action <double> endColorG = (double newValue) => { endColor.g = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.endColor = endColor; }; variableRegistrar.RegisterVariableChangeCallback(endColors[1], endColorG); Action <double> endColorB = (double newValue) => { endColor.b = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.endColor = endColor; }; variableRegistrar.RegisterVariableChangeCallback(endColors[2], endColorB); if (endColors.Length == 4) { Action <double> endColorA = (double newValue) => { endColor.a = Mathf.Clamp01((float)newValue * (1.0f / 255.0f)); lineRenderer.endColor = endColor; }; variableRegistrar.RegisterVariableChangeCallback(endColors[3], endColorA); } } } if (string.IsNullOrEmpty(endWidthString)) { // Monowidth line Action <double> startWidthAction = (double newValue) => { startWidth = (float)newValue; lineRenderer.startWidth = startWidth; lineRenderer.endWidth = startWidth; }; variableRegistrar.RegisterVariableChangeCallback(startWidthString, startWidthAction); } else { Action <double> startWidthAction = (double newValue) => { startWidth = (float)newValue; lineRenderer.startWidth = startWidth; }; variableRegistrar.RegisterVariableChangeCallback(startWidthString, startWidthAction); Action <double> endWidthAction = (double newValue) => { endWidth = (float)newValue; lineRenderer.endWidth = endWidth; }; variableRegistrar.RegisterVariableChangeCallback(endWidthString, endWidthAction); } }
public void Save(ConfigNode node) { node.AddValue("message", message); }
protected void loadConfig() { prevIndex = selectedIndex; if (selectedIndex == 0) { description = kDefaultDescription; payToRemodel = true; requireSkillCheck = true; repairsRequireResources = true; partsCanBreak = true; } else { string configFile = System.IO.File.ReadAllText(playModeFiles[selectedIndex - 1]); nodePlayMode = ConfigNode.Parse(configFile); if (nodePlayMode.HasNode("PATHFINDER_PLAYMODE")) { nodePlayMode = nodePlayMode.GetNode("PATHFINDER_PLAYMODE"); } if (nodePlayMode.HasValue("description")) { description = nodePlayMode.GetValue("description"); } else { description = "Not available"; } if (nodePlayMode.HasValue("payToRemodel")) { payToRemodel = bool.Parse(nodePlayMode.GetValue("payToRemodel")); } else { payToRemodel = true; } if (nodePlayMode.HasValue("requireSkillCheck")) { requireSkillCheck = bool.Parse(nodePlayMode.GetValue("requireSkillCheck")); } else { requireSkillCheck = true; } if (nodePlayMode.HasValue("repairsRequireResources")) { repairsRequireResources = bool.Parse(nodePlayMode.GetValue("repairsRequireResources")); } else { repairsRequireResources = true; } if (nodePlayMode.HasValue("partsCanBreak")) { partsCanBreak = bool.Parse(nodePlayMode.GetValue("partsCanBreak")); } else { partsCanBreak = true; } } //List the default values description = description + "\r\n\r\n<b>Default Settings</b>\r\n\r\n"; description = description + "Require resources to reconfigure modules: " + payToRemodel.ToString() + "\r\n"; description = description + "Require skill check to reconfigure modules: " + requireSkillCheck.ToString() + "\r\n"; description = description + "Repairs require resources: " + repairsRequireResources.ToString() + "\r\n"; description = description + "Parts can break: " + partsCanBreak.ToString() + "\r\n"; }
public override void OnLoad(ConfigNode node) { HSUtils.DebugLog("HaystackScenarioModule#OnLoad: {0}", HighLogic.LoadedScene); DataManager.Instance.Load(node); }
public SunShieldingPartData(ConfigNode node) { distance = Lib.ConfigValue <double>(node, "distance", 1.0); thickness = Lib.ConfigValue <double>(node, "thickness", 1.0); }
// Apply PostSpawnOrbit patches void ApplyOrbitPatches() { // Bodies Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> > fixes = new Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> >(); for (Int32 i = 0; i < PSystemManager.Instance.localBodies.Count; i++) { CelestialBody body = PSystemManager.Instance.localBodies[i]; // Post spawn patcher if (!body.Has("orbitPatches")) { continue; } ConfigNode orbitNode = body.Get <ConfigNode>("orbitPatches"); OrbitLoader loader = new OrbitLoader(body); CelestialBody oldRef = body.referenceBody; Parser.LoadObjectFromConfigurationNode(loader, orbitNode, "Kopernicus"); oldRef.orbitingBodies.Remove(body); if (body.referenceBody == null) { // Log the exception Debug.Log("Exception: PostSpawnOrbit reference body for \"" + body.name + "\" could not be found. Missing body name is \"" + loader.referenceBody + "\"."); // Open the Warning popup Injector.DisplayWarning(); Destroy(this); return; } fixes.Add(body.transform.name, new KeyValuePair <CelestialBody, CelestialBody>(oldRef, body.referenceBody)); body.referenceBody.orbitingBodies.Add(body); body.referenceBody.orbitingBodies = body.referenceBody.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList(); body.orbit.Init(); body.orbitDriver.UpdateOrbit(); // Calculations if (!body.Has("sphereOfInfluence")) { body.sphereOfInfluence = body.orbit.semiMajorAxis * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.4); } if (!body.Has("hillSphere")) { body.hillSphere = body.orbit.semiMajorAxis * (1 - body.orbit.eccentricity) * Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.333333333333333); } if (!body.solarRotationPeriod) { continue; } Double rotPeriod = Utility .FindBody(PSystemManager.Instance.systemPrefab.rootBody, body.transform.name).celestialBody .rotationPeriod; Double num1 = Math.PI * 2 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter); body.rotationPeriod = rotPeriod * num1 / (num1 + rotPeriod); } // Update the order in the tracking station List <MapObject> trackingstation = new List <MapObject>(); Utility.DoRecursive(PSystemManager.Instance.localBodies[0], cb => cb.orbitingBodies, cb => { trackingstation.Add(PlanetariumCamera.fetch.targets.Find(t => t.celestialBody == cb)); }); PlanetariumCamera.fetch.targets.Clear(); PlanetariumCamera.fetch.targets.AddRange(trackingstation); // Undo stuff foreach (CelestialBody b in PSystemManager.Instance.localBodies.Where(b => b.Has("orbitPatches"))) { String transformName = b.transform.name; fixes[transformName].Value.orbitingBodies.Remove(b); fixes[transformName].Key.orbitingBodies.Add(b); fixes[transformName].Key.orbitingBodies = fixes[transformName].Key.orbitingBodies .OrderBy(cb => cb.orbit.semiMajorAxis).ToList(); } }
public override void Load(ConfigNode node) { base.Load(node); try { Role = (TCARole)Enum.Parse(typeof(TCARole), role); } catch { Role = default(TCARole); } }
public void Save(ConfigNode node) { node.AddValue("distance", distance); node.AddValue("thickness", thickness); }
/// <summary> /// Constructor /// </summary> /// <param name="v"></param> /// <param name="module"></param> internal ShipController(Vessel v, ConfigNode module) : base(v, module) { throw new Exception("Ship controller not implemented"); }
public override void Save(ConfigNode node) { role = Enum.GetName(typeof(TCARole), Role); base.Save(node); }
protected override void OnSave(ConfigNode node) { node.AddValue("Time_Needed", timeNeeded.ToString("N2")); node.AddValue("Time_Completed", orbitTime.ToString("N2")); }
public override void Save(ConfigNode node) { DB.ForEach(p => p.SaveInto(node)); base.Save(node); }