예제 #1
0
 public override void OnSave(ConfigNode node)
 {
     base.OnSave(node);
     if (noseAnimControl != null)
     {
         noseAnimState = noseAnimControl.animationState.ToString();
         bodyAnimState = bodyAnimControl.animationState.ToString();
         tailAnimState = tailAnimControl.animationState.ToString();
         node.SetValue("noseAnimState", noseAnimState, true);
         node.SetValue("bodyAnimState", bodyAnimState, true);
         node.SetValue("tailAnimState", tailAnimState, true);
     }
 }
예제 #2
0
        //loop through parts on vessel
        //  loop through modules on part
        //    for each docking node found
        //      if no existing docking-port-fix module is found
        //        add new SSTUDockingPortFix set to index-in-docking-modules of the docking port being fixed
        // TODO - check for existing dock-port-fix modules?
        private void onVesselLoaded(Vessel v)
        {
            int len = v.Parts.Count;
            int dLen;
            Part p;
            ModuleDockingNode[] mdns;
            ModuleDockingNode mdn;
            SSTUDockingPortFix dpf;
            ConfigNode dpfNode = new ConfigNode("MODULE");
            dpfNode.AddValue("name", nameof(SSTUDockingPortFix));
            for (int i = 0; i < len; i++)
            {
                p = v.Parts[i];
                if (p == null) { continue; }

                mdns = p.GetComponents<ModuleDockingNode>();
                if (mdns == null || mdns.Length == 0) { continue; }
                dLen = mdns.Length;
                for (int k = 0; k < dLen; k++)
                {
                    mdn = mdns[k];
                    dpfNode.SetValue("portIndex", k, true);
                    //dpf = (SSTUDockingPortFix)p.AddModule(dpfNode);
                }
            }
        }
예제 #3
0
        public override void OnSave(ConfigNode node)
        {
            base.OnSave(node);
            ConfigNode efficiencyNode;

            if (node.HasValue("reputationIndex"))
                node.SetValue("reputationIndex", reputationIndex.ToString());
            else
                node.AddValue("reputationIndex", reputationIndex.ToString());

            if (node.HasValue("drillToolTipShown"))
                node.SetValue("drillToolTipShown", drillToolTipShown.ToString());
            else
                node.AddValue("drillToolTipShown", drillToolTipShown.ToString());

            foreach (EfficiencyData data in efficiencyDataMap.Values)
            {
                efficiencyNode = new ConfigNode(kEfficiencyData);
                data.Save(efficiencyNode);
                node.AddNode(efficiencyNode);
            }
        }
예제 #4
0
        public override void OnSave(ConfigNode node)
        {
            base.OnSave(node);
            ConfigNode efficiencyNode;

            if (node.HasValue("reputationIndex"))
                node.SetValue("reputationIndex", reputationIndex.ToString());
            else
                node.AddValue("reputationIndex", reputationIndex.ToString());

            foreach (EfficiencyData data in efficiencyDataMap.Values)
            {
                efficiencyNode = new ConfigNode(kEfficiencyData);
                data.Save(efficiencyNode);
                node.AddNode(efficiencyNode);
            }

            node.RemoveNodes(kToolTip);
            foreach (ConfigNode toolTipNode in toolTips.Values)
                node.AddNode(toolTipNode);
        }
예제 #5
0
 private void DodgeVesselLandedStatus(ConfigNode vesselNode)
 {
     if (vesselNode != null)
     {
         string situation = vesselNode.GetValue("sit");
         switch (situation)
         {
             case "LANDED":
                 vesselNode.SetValue("landed", "True");
                 vesselNode.SetValue("splashed", "False");
                 break;
             case "SPLASHED":
                 vesselNode.SetValue("splashed", "True");
                 vesselNode.SetValue("landed", "False");
                 break;
         }
     }
 }
예제 #6
0
		void SaveRippleOptions(ConfigNode node)
		{
			if(rippleDictionary != null)
			{
				rippleData = string.Empty;
				foreach(var wpnName in rippleDictionary.Keys)
				{
					rippleData += wpnName + "," + rippleDictionary[wpnName].rippleFire.ToString() + "," + rippleDictionary[wpnName].rpm.ToString() + ";";
				}


				node.SetValue("RippleData", rippleData, true);
			}
			Debug.Log("Saved ripple data: "+rippleData);
		}
예제 #7
0
파일: Editor.cs 프로젝트: erendrake/AGExt
         List<string> showAllPartsListTitles; //list of all parts with actions to show in group window
        //static Part partLastHighlight = null;
        ////static Color partHighlighLastColor;
        //static Part.HighlightType partHighlightLastType;
        //static Material[] partHighlightLastMaterial;

       
        
       
        public void Start()
        {
            //foreach (Part p in 

            //var EdPnl = EditorPanels.Instance.actions;
            //EditorActionGroups.Instance.groupActionsList.AddValueChangedDelegate(OnGroupActionsListChange);
            KSPActs[1] = KSPActionGroup.Custom01;
            KSPActs[2] = KSPActionGroup.Custom02;
            KSPActs[3] = KSPActionGroup.Custom03;
            KSPActs[4] = KSPActionGroup.Custom04;
            KSPActs[5] = KSPActionGroup.Custom05;
            KSPActs[6] = KSPActionGroup.Custom06;
            KSPActs[7] = KSPActionGroup.Custom07;
            KSPActs[8] = KSPActionGroup.Custom08;
            KSPActs[9] = KSPActionGroup.Custom09;
            KSPActs[10] = KSPActionGroup.Custom10;
            
            TestWin = new Rect(600, 300, 100, 200);
            RenderingManager.AddToPostDrawQueue(0, AGXOnDraw);
            AGEditorSelectedParts = new List<AGXPart>();
            PartActionsList = new List<BaseAction>();
            ScrollPosSelParts = Vector2.zero;
            ScrollPosSelPartsActs = Vector2.zero;
            ScrollGroups = Vector2.zero;
            CurGroupsWin = Vector2.zero;
            
            //AGXVsl = new AGXVessel();
            
            AGXWinStyle = new GUIStyle(HighLogic.Skin.window);
            
            BtnTexRed.SetPixel(0, 0, new Color(1, 0, 0, .5f));
            BtnTexRed.Apply();
            BtnTexGrn.SetPixel(0, 0, new Color(0, 1, 0, .5f));
            BtnTexGrn.Apply();
            
            AGXguiNames = new Dictionary<int,string>();
            
            
            AGXguiKeys = new Dictionary<int, KeyCode>();
           

           
            for (int i = 1; i <= 250; i = i + 1)
            {
                AGXguiNames[i] = "";
                AGXguiKeys[i] = KeyCode.None;
            }

            
            KeyCodeNames = new List<String>();
            KeyCodeNames.AddRange(Enum.GetNames(typeof(KeyCode)));
            KeyCodeNames.Remove("None");
            JoyStickCodes.AddRange(KeyCodeNames.Where(JoySticks));
            KeyCodeNames.RemoveAll(JoySticks);
           AGExtNode = ConfigNode.Load(KSPUtil.ApplicationRootPath + "GameData/Diazo/AGExt/AGExt.cfg");
           if (AGExtNode.GetValue("EditShow") == "0")
           {
               AGXShow = false;
           }
           else
           {
               AGXShow = true;
           }
           CurrentKeySet = Convert.ToInt32(AGExtNode.GetValue("ActiveKeySet"));
           //LoadCurrentKeySet();
           CurrentKeySetName = AGExtNode.GetValue("KeySetName" + CurrentKeySet);
           CurrentVesselActions = new List<AGXAction>();
           AGXRoot = null;
           GroupsWin = new Rect(Convert.ToInt32(AGExtNode.GetValue("EdGroupsX")), Convert.ToInt32(AGExtNode.GetValue("EdGroupsY")), 250, 530);
           SelPartsWin = new Rect(Convert.ToInt32(AGExtNode.GetValue("EdSelPartsX")), Convert.ToInt32(AGExtNode.GetValue("EdSelPartsY")), 365, 270);
           KeyCodeWin = new Rect(Convert.ToInt32(AGExtNode.GetValue("EdKeyCodeX")), Convert.ToInt32(AGExtNode.GetValue("EdKeyCodeY")), 410, 730);
           KeySetWin = new Rect(Convert.ToInt32(AGExtNode.GetValue("EdKeySetX")), Convert.ToInt32(AGExtNode.GetValue("EdKeySetY")), 185, 335);
           CurActsWin = new Rect(Convert.ToInt32(AGExtNode.GetValue("EdCurActsX")), Convert.ToInt32(AGExtNode.GetValue("EdCurActsY")), 345, 140);
            


           LoadCurrentKeyBindings();


           if (ToolbarManager.ToolbarAvailable) //check if toolbar available, load if it is
           {


               AGXBtn = ToolbarManager.Instance.add("AGX", "AGXBtn");
               AGXBtn.TexturePath = "Diazo/AGExt/icon_button";
               AGXBtn.ToolTip = "Action Groups Extended";
               AGXBtn.OnClick += (e) =>
               {
                   //List<UnityEngine.Transform> UIPanelList = new List<UnityEngine.Transform>(); //setup list to find Editor Actions UI transform into a list. Could not figure out how to find just a transform
                   //UIPanelList.AddRange(FindObjectsOfType<UnityEngine.Transform>().Where(n => n.name == "PanelActionGroups")); //actual find command
                   if (EditorLogic.fetch.editorScreen == EditorLogic.EditorScreen.Actions)
                   {
                       if (AGXShow)
                       {
                           //UIPanelList.First().Translate(new Vector3(500f, 0, 0), UIPanelList.First().parent.transform); //hide UI panel
                           AGXShow = false;
                           AGExtNode.SetValue("EditShow", "0");
                           EditorPanels.Instance.panelManager.BringIn(EditorPanels.Instance.actions);

                       }
                       else
                       {
                           // UIPanelList.First().Translate(new Vector3(-500f, 0, 0), UIPanelList.First().parent.transform); //show UI panel
                           AGXShow = true;
                           AGExtNode.SetValue("EditShow", "1");
                           EditorPanels.Instance.panelManager.Dismiss();
                       }
                       AGExtNode.Save(KSPUtil.ApplicationRootPath + "GameData/Diazo/AGExt/AGExt.cfg");
                   }
                   else
                   {
                       EditorLogic.fetch.SelectPanelActions();
                   }
               };
           }
           else
           {
               AGXShow = true; //toolbar not installed, show AGX regardless
           }
           
           DetachedPartActions = new List<AGXAction>();
          
            DetachedPartReset = new Timer();
           DetachedPartReset.Interval = 500;
           
           DetachedPartReset.Stop();
           DetachedPartReset.AutoReset = true;
           
           DetachedPartReset.Elapsed += new ElapsedEventHandler(ResetDetachedParts);

           SelectedWithSym = new List<Part>();
           SelectedWithSymActions = new List<AGXDefaultCheck>();

           EditorPanels.Instance.actions.AddValueChangedDelegate(OnUIChanged); //detect when EditorPanel moves. this ONLY detects editor panel, going from parts to crew will NOT trigger this
           EditorLogic.fetch.crewPanelBtn.AddValueChangedDelegate(OnOtherButtonClick); //detect when Part button clicked at top of screen
           EditorLogic.fetch.partPanelBtn.AddValueChangedDelegate(OnOtherButtonClick); //detect when Crew button clicked at top of screen
           EditorLogic.fetch.loadBtn.AddValueChangedDelegate(OnLoadButtonClick); //load button clicked to check for deleted ships
           EditorLogic.fetch.saveBtn.AddValueChangedDelegate(OnSaveButtonClick); //run save when save button clicked. auto-save from Scenario module only runs on leaving editor! not on clicking save button
           EditorLogic.fetch.launchBtn.AddValueChangedDelegate(OnSaveButtonClick);
           EditorLogic.fetch.exitBtn.AddValueChangedDelegate(OnSaveButtonClick);
           EditorLogic.fetch.newBtn.AddValueChangedDelegate(OnSaveButtonClick);

           IsGroupToggle = new Dictionary<int, bool>();
           ShowGroupInFlight = new bool[6, 251];
           ShowGroupInFlightNames = new string[6];
           
           ShowGroupInFlightNames[1] = "Group 1";
           ShowGroupInFlightNames[2] = "Group 2";
           ShowGroupInFlightNames[3] = "Group 3";
           ShowGroupInFlightNames[4] = "Group 4";
           ShowGroupInFlightNames[5] = "Group 5";
           
           
           
            for (int i = 1; i <= 250; i++)
           {
               IsGroupToggle[i] = false;
               for (int i2 = 1; i2 <= 5; i2++)
               {
                   ShowGroupInFlight[i2, i] = true;
               }
           }
            AGXSkin = (GUISkin)MonoBehaviour.Instantiate(HighLogic.Skin);
            AGXWinStyle = new GUIStyle(AGXSkin.window);
            AGXLblStyle = new GUIStyle(AGXSkin.label);
            AGXFldStyle = new GUIStyle(AGXSkin.textField);
            AGXFldStyle.fontStyle = FontStyle.Normal;
            //AGXFldStyle.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1);
            AGXFldStyle.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1f);
            AGXLblStyle.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1f);
            AGXLblStyle.wordWrap = false;

            AGXBtnStyle = new GUIStyle(AGXSkin.button);
            AGXBtnStyle.fontStyle = FontStyle.Normal;
            AGXBtnStyle.alignment = TextAnchor.MiddleCenter;
            AGXBtnStyle.normal.textColor = new Color(0.9f, 0.9f, 0.9f, 1f);
            //AGXScrollStyle.normal.background = null;
            //print("AGX " + AGXBtnStyle.normal.background);
            byte[] importTxt = File.ReadAllBytes(KSPUtil.ApplicationRootPath + "GameData/Diazo/AGExt/ButtonTexture.png");
            byte[] importTxtRed = File.ReadAllBytes(KSPUtil.ApplicationRootPath + "GameData/Diazo/AGExt/ButtonTextureRed.png");
            byte[] importTxtGreen = File.ReadAllBytes(KSPUtil.ApplicationRootPath + "GameData/Diazo/AGExt/ButtonTextureGreen.png");
            byte[] importPartCenter = File.ReadAllBytes(KSPUtil.ApplicationRootPath + "GameData/Diazo/AGExt/PartLocationCross.png");
            //byte[] testXport = AGXBtnStyle.normal.background.EncodeToPNG();
            //File.WriteAllBytes(Application.dataPath + "/SavedScreen.png", testXport);
            ButtonTexture.LoadImage(importTxt);
            ButtonTexture.Apply();
            ButtonTextureRed.LoadImage(importTxtRed);
            ButtonTextureRed.Apply();
            ButtonTextureGreen.LoadImage(importTxtGreen);
            ButtonTextureGreen.Apply();
            AGXBtnStyle.normal.background = ButtonTexture;
            AGXBtnStyle.onNormal.background = ButtonTexture;
            AGXBtnStyle.onActive.background = ButtonTexture;
            AGXBtnStyle.onFocused.background = ButtonTexture;
            AGXBtnStyle.onHover.background = ButtonTexture;
            AGXBtnStyle.active.background = ButtonTexture;
            AGXBtnStyle.focused.background = ButtonTexture;
            AGXBtnStyle.hover.background = ButtonTexture;
            PartCenter.LoadImage(importPartCenter);
            PartCenter.Apply();
            //EditorLoadFromFile();
            if (HighLogic.LoadedScene == GameScenes.EDITOR)
            {
                inVAB = true;
            }
            else
            {
                inVAB = false;
            }
            GameEvents.onPartAttach.Add(PartAttaching);// this game event only fires for part removed, not child parts
            GameEvents.onPartRemove.Add(PartRemove);
            EditorLoadFromFile();
            //print("Loading now");
           LoadFinished = true;
           
           }
        public void SaveState(ConfigNode configNode)
        {
            if (configNode != null)
            {
                configNode.SetValue("useStockSkin", m_UseKSPSkin ? "true" : "false");
                configNode.SetValue("useOldPresetEditor", m_UseOldPresetsWindow ? "true" : "false");
            }

            Configuration.Serialize(GetAbsoluteConfigurationPath(), m_Configuration);
        }
예제 #9
0
        public virtual void SetConfiguration(string newConfiguration = null, bool resetTechLevels = false)
        {
            if (newConfiguration == null)
                newConfiguration = configuration;

            ConfigSaveLoad();

            ConfigNode newConfig = configs.Find (c => c.GetValue ("name").Equals (newConfiguration));
            if (!UnlockedConfig(newConfig, part))
            {
                if(newConfig == null)
                    Debug.Log("*RFMEC* ERROR Can't find configuration " + newConfiguration + ", falling back to first tech-available config.");

                foreach(ConfigNode cfg in configs)
                    if (UnlockedConfig(cfg, part))
                    {
                        newConfig = cfg;
                        newConfiguration = cfg.GetValue("name");
                        break;
                    }
            }
            if (newConfig != null)
            {
                if (configuration != newConfiguration && resetTechLevels)
                    techLevel = origTechLevel;

                // for asmi
                if (useConfigAsTitle)
                    part.partInfo.title = configuration;

                configuration = newConfiguration;
                config = new ConfigNode("MODULE");
                newConfig.CopyTo(config);
                config.name = "MODULE";

            #if DEBUG
                print ("replacing " + type + " with:");
                print (newConfig.ToString ());
            #endif

                pModule = null;
                // get correct module
                pModule = GetSpecifiedModule(part, engineID, moduleIndex, type, useWeakType);

                if ((object)pModule == null)
                {
                    Debug.Log("*RFMEC* Could not find appropriate module of type " + type + ", with ID=" + engineID + " and index " + moduleIndex);
                    return;
                }

                Type mType = pModule.GetType();
                config.SetValue("name", mType.Name);

                // clear all FloatCurves we need to clear (i.e. if our config has one, or techlevels are enabled)
                bool delAtmo = config.HasNode("atmosphereCurve") || techLevel >= 0;
                bool delDens = config.HasNode("atmCurve") || techLevel >= 0;
                bool delVel = config.HasNode("velCurve") || techLevel >= 0;
                foreach (FieldInfo field in mType.GetFields())
                {
                    if (field.FieldType == typeof(FloatCurve) &&
                        ((field.Name.Equals("atmosphereCurve") && delAtmo)
                        || (field.Name.Equals("atmCurve") && delDens)
                        || (field.Name.Equals("velCurve") && delVel)))
                    {
                        field.SetValue(pModule, new FloatCurve());
                    }
                }
                // clear propellant gauges
                foreach (FieldInfo field in mType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
                {
                    if (field.FieldType == typeof(Dictionary<Propellant, VInfoBox>))
                    {
                        Dictionary<Propellant, VInfoBox> boxes = (Dictionary<Propellant, VInfoBox>)(field.GetValue(pModule));
                        if (boxes == null)
                            continue;
                        foreach (VInfoBox v in boxes.Values)
                        {
                            if (v == null) //just in case...
                                continue;
                            try
                            {
                                part.stackIcon.RemoveInfo(v);
                            }
                            catch (Exception e)
                            {
                                Debug.Log("*RFMEC* Trying to remove info box: " + e.Message);
                            }
                        }
                        boxes.Clear();
                    }
                }
                if (type.Equals("ModuleRCS") || type.Equals("ModuleRCSFX"))
                {
                    ModuleRCS rcs = (ModuleRCS)pModule;
                    if (rcs != null)
                    {
                        DoConfig(config);
                        if (config.HasNode("PROPELLANT"))
                        {
                            rcs.propellants.Clear();
                        }
                        pModule.Load(config);
                    }
                }
                else
                { // is an ENGINE
                    ModuleEngines mE = (ModuleEngines)pModule;
                    if (mE != null)
                    {
                        if (config.HasNode("PROPELLANT"))
                        {
                            mE.propellants.Clear();
                        }
                    }

                    DoConfig(config);

                    // Handle Engine Ignitor
                    if (config.HasNode("ModuleEngineIgnitor"))
                    {
                        if (part.Modules.Contains("ModuleEngineIgnitor"))
                        {
                            ConfigNode eiNode = config.GetNode("ModuleEngineIgnitor");
                            if (eiNode.HasValue("ignitionsAvailable"))
                            {
                                int ignitions;
                                if (int.TryParse(eiNode.GetValue("ignitionsAvailable"), out ignitions))
                                {
                                    ignitions = ConfigIgnitions(ignitions);

                                    eiNode.SetValue("ignitionsAvailable", ignitions.ToString());
                                    if (eiNode.HasValue("ignitionsRemained"))
                                        eiNode.SetValue("ignitionsRemained", ignitions.ToString());
                                    else
                                        eiNode.AddValue("ignitionsRemained", ignitions.ToString());
                                }
                            }
                            if (!HighLogic.LoadedSceneIsEditor && !(HighLogic.LoadedSceneIsFlight && vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH)) // fix for prelaunch
                            {
                                int remaining = (int)(part.Modules["ModuleEngineIgnitor"].GetType().GetField("ignitionsRemained").GetValue(part.Modules["ModuleEngineIgnitor"]));
                                if (eiNode.HasValue("ignitionsRemained"))
                                    eiNode.SetValue("ignitionsRemained", remaining.ToString());
                                else
                                    eiNode.AddValue("ignitionsRemained", remaining.ToString());
                            }
                            ConfigNode tNode = new ConfigNode("MODULE");
                            eiNode.CopyTo(tNode);
                            tNode.SetValue("name", "ModuleEngineIgnitor");
                            part.Modules["ModuleEngineIgnitor"].Load(tNode);
                        }
                        else // backwards compatible with EI nodes when using RF ullage etc.
                        {
                            ConfigNode eiNode = config.GetNode("ModuleEngineIgnitor");
                            if (eiNode.HasValue("ignitionsAvailable") && !config.HasValue("ignitions"))
                            {
                                config.AddValue("ignitions", eiNode.GetValue("ignitionsAvailable"));
                            }
                            if (eiNode.HasValue("useUllageSimulation") && !config.HasValue("ullage"))
                                config.AddValue("ullage", eiNode.GetValue("useUllageSimulation"));
                            if (eiNode.HasValue("isPressureFed") && !config.HasValue("pressureFed"))
                                config.AddValue("pressureFed", eiNode.GetValue("isPressureFed"));
                            if (!config.HasNode("IGNITOR_RESOURCE"))
                                foreach (ConfigNode resNode in eiNode.GetNodes("IGNITOR_RESOURCE"))
                                    config.AddNode(resNode);
                        }
                    }
                    if (config.HasValue("ignitions"))
                    {
                        int ignitions;
                        if ((!HighLogic.LoadedSceneIsFlight || (vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH)))
                        {
                            if (int.TryParse(config.GetValue("ignitions"), out ignitions))
                            {
                                ignitions = ConfigIgnitions(ignitions);
                                config.SetValue("ignitions", ignitions.ToString());
                            }
                        }
                        else
                            config.RemoveValue("ignitions");
                    }

                    if (pModule is ModuleEnginesRF)
                        (pModule as ModuleEnginesRF).SetScale(1d);
                    pModule.Load(config);
                }
                // fix for editor NaN
                if (part.Resources.Contains("ElectricCharge") && part.Resources["ElectricCharge"].maxAmount < 0.1)
                { // hacking around a KSP bug here
                    part.Resources["ElectricCharge"].amount = 0;
                    part.Resources["ElectricCharge"].maxAmount = 0.1;
                }

                // set gimbal
                if (config.HasValue("gimbalRange"))
                {
                    float newGimbal = float.Parse(config.GetValue("gimbalRange"));
                    for (int m = 0; m < part.Modules.Count; ++m)
                    {
                        if (part.Modules[m] is ModuleGimbal)
                        {
                            ModuleGimbal g = part.Modules[m] as ModuleGimbal;
                            if (gimbalTransform.Equals("") || g.gimbalTransformName.Equals(gimbalTransform))
                            {
                                g.gimbalRange = newGimbal;
                                break;
                            }
                        }
                    }
                }
                if (config.HasValue("cost"))
                    configCost = scale * float.Parse(config.GetValue("cost"));
                else
                    configCost = 0f;

                UpdateOtherModules(config);

                // GUI disabled for now - UpdateTweakableMenu();

                // Finally, fire the modified event
                // more trouble than it is worth...
                /*if((object)(EditorLogic.fetch) != null && (object)(EditorLogic.fetch.ship) != null && HighLogic.LoadedSceneIsEditor)
                    GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);*/

                // fire config modified event
                /*if(HighLogic.LoadedSceneIsEditor || HighLogic.LoadedSceneIsFlight)
                    EngineConfigChanged();*/
                // do it manually
                List<Part> parts;
                if (HighLogic.LoadedSceneIsEditor && EditorLogic.fetch.ship != null)
                    parts = EditorLogic.fetch.ship.parts;
                else if (HighLogic.LoadedSceneIsFlight && vessel != null)
                    parts = vessel.parts;
                else parts = new List<Part>();
                for (int i = parts.Count - 1; i >= 0; --i)
                    parts[i].SendMessage("UpdateUsedBy");

                SetupFX();

                UpdateTFInterops(); // update TestFlight if it's installed
            }
            else
            {
                Debug.Log("*RFMEC* ERROR could not find configuration of name " + configuration + " and could find no fallback config.");
                Debug.Log("For part " + part.name + ", Current nodes:" + Utilities.PrintConfigs(configs));
            }
        }
        private void writeConfig(Config config)
        {
            ConfigNode root = new ConfigNode ();
            ConfigNode top = new ConfigNode (WASD_NODENAME);
            root.SetNode (WASD_NODENAME, top, true);
            top.SetValue ("defaultCamera", config.defaultCamera.ToString (), true);
            top.SetValue ("mouseWheelActive", config.mouseWheelActive.ToString (), true);
            top.SetValue ("enableExperimentalEditorExtensionsCompatibility", config.enableExperimentalEditorExtensionsCompatibility.ToString (), true);
            top.SetValue ("enforceBounds", config.enforceBounds.ToString (), true);
            top.SetValue ("sensitivity", config.sensitivity.ToString (), true);
            top.SetValue ("acceleration", config.acceleration.ToString (), true);
            top.SetValue ("mouseWheelAcceleration", config.mouseWheelAcceleration.ToString (), true);
            top.SetValue ("friction", config.friction.ToString (), true);
            top.SetValue ("runMultiplier", config.runMultiplier.ToString (), true);
            top.SetValue ("sneakMultiplier", config.sneakMultiplier.ToString (), true);

            ConfigNode keysNode = new ConfigNode ("KEYS");
            top.SetNode ("KEYS", keysNode, true);

            keysNode.SetValue ("forward", config.keyForward.ToString (), true);
            keysNode.SetValue ("back", config.keyBack.ToString (), true);
            keysNode.SetValue ("right", config.keyRight.ToString (), true);
            keysNode.SetValue ("left", config.keyLeft.ToString (), true);
            keysNode.SetValue ("up", config.keyUp.ToString (), true);
            keysNode.SetValue ("down", config.keyDown.ToString (), true);
            keysNode.SetValue ("switchMode", config.keySwitchMode.ToString (), true);
            keysNode.SetValue ("run", config.keyRun.ToString (), true);
            keysNode.SetValue ("sneak", config.keySneak.ToString (), true);

            ConfigNode editorsNode = new ConfigNode ("EDITORS");
            top.SetNode ("EDITORS", editorsNode, true);
            ConfigNode vabNode = new ConfigNode ("VAB");
            editorsNode.SetNode ("VAB", vabNode, true);
            string s;

            s = config.vab.initialPosition.ToString ();
            s = s.TrimStart ('(');
            s = s.TrimEnd (')');
            vabNode.SetValue ("initialPosition", s, true);
            vabNode.SetValue ("initialPitch", config.vab.initialPitch.ToString (), true);
            vabNode.SetValue ("initialYaw", config.vab.initialYaw.ToString (), true);
            ConfigNode vabBoundsNode = new ConfigNode ("BOUNDS");
            vabNode.SetNode ("BOUNDS", vabBoundsNode, true);
            s = config.vab.bounds.min.ToString ();
            s = s.TrimStart ('(');
            s = s.TrimEnd (')');
            vabBoundsNode.SetValue ("min", s, true);
            s = config.vab.bounds.max.ToString ();
            s = s.TrimStart ('(');
            s = s.TrimEnd (')');
            vabBoundsNode.SetValue ("max", s, true);

            // need to do bounds

            ConfigNode sphNode = new ConfigNode ("SPH");
            editorsNode.SetNode ("SPH", sphNode, true);
            s = config.sph.initialPosition.ToString ();
            s = s.TrimStart ('(');
            s = s.TrimEnd (')');
            sphNode.SetValue ("initialPosition", s, true);
            sphNode.SetValue ("initialPitch", config.sph.initialPitch.ToString (), true);
            sphNode.SetValue ("initialYaw", config.sph.initialYaw.ToString (), true);
            // need to do bounds
            ConfigNode sphBoundsNode = new ConfigNode ("BOUNDS");
            sphNode.SetNode ("BOUNDS", sphBoundsNode, true);
            s = config.sph.bounds.min.ToString ();
            s = s.TrimStart ('(');
            s = s.TrimEnd (')');

            sphBoundsNode.SetValue ("min", s, true);
            s = config.sph.bounds.max.ToString ();
            s = s.TrimStart ('(');
            s = s.TrimEnd (')');
            sphBoundsNode.SetValue ("max", s, true);

            root.Save (WASD_CFG_FILE);

            WasdEditorCameraBehaviour.setConfig (root);
        }
 public override void OnSave(ConfigNode node)
 {
     // Force saved value for enabled to be true.
     node.SetValue("isEnabled", "True");
 }
 public override void OnSave(ConfigNode node)
 {
     base.OnSave(node);
     savedAnimationState = panelState.ToString();
     node.SetValue("savedAnimationState", savedAnimationState, true);
 }
        /// <summary>
        /// Store fitted engine parameters in the database so they can be accessed later
        /// </summary>
        /// <param name="engine">Engine to associated this config node with</param>
        /// <param name="node">Config node describing engine parameters (both input parameters and fitted parameters)</param>
        public static void SetNodeForEngine(ModuleEnginesSolver engine, ConfigNode node)
        {
            string partName = engine.part.name;
            string engineType = engine.GetType().Name;
            string engineID = engine.engineID;

            Assembly assembly = engine.GetType().Assembly;

            node.SetValue("engineID", engineID, true);
            node.SetValue("DeclaringAssemblyVersion", EngineDatabase.AssemblyVersion(assembly), true);
            node.SetValue("DeclaringAssemblyChecksum", EngineDatabase.AssemblyChecksum(assembly), true);
            node.SetValue("SolverEnginesVersion", SolverEnginesVersion, true);
            node.SetValue("SolverEnginesAssemblyChecksum", SolverEnginesAssemblyChecksum, true);

            ConfigNode partNode = database.GetNode(partName);
            int nodeIndex = 0;

            if (partNode != null)
            {
                ConfigNode[] moduleNodes = partNode.GetNodes(engineType);
                for (int i = 0; i < moduleNodes.Length; i++ )
                {
                    ConfigNode mNode = moduleNodes[i];
                    if (mNode.GetValue("engineID") == engineID)
                    {
                        nodeIndex = i;
                    }
                }
            }
            else
            {
                partNode = new ConfigNode(partName);
                database.AddNode(partNode);
                nodeIndex = 0;
            }

            partNode.SetNode(engineType, node, nodeIndex, true);

            SaveDatabase();
        }
예제 #14
0
        /// <summary>
        /// Saves the internal state of the failure module to the persistence file.
        /// Put your custom save logic in DI_OnSave()
        /// </summary>
        public override void OnSave(ConfigNode node)
        {
            try
            {
                // Save the internal state
                node.SetValue("HasInitted", this.HasInitted.ToString());
                node.SetValue("Age", Age.ToString());
                node.SetValue("TimeOfLastReset", TimeOfLastReset.ToString());
                node.SetValue("TimeOfLastInspection", TimeOfLastInspection.ToString());
                node.SetValue("LastFixedUpdate", LastFixedUpdate.ToString());
                node.SetValue("CurrentMTBF", CurrentMTBF.ToString());
                node.SetValue("LifeTimeSecs", LifeTimeSecs.ToString());
                node.SetValue("HasFailed", HasFailed.ToString());

                // Run the subclass' custom onsave
                this.DI_OnSave(node);

                base.OnSave(node);
            }
            catch (Exception e)
            {
                this.OnError(e);
            }
        }
        public override void OnSave(ConfigNode config)
        {
            //Debug.Log("ResourceRecovery ResourceRecoveryData OnSave beginn1 config=" + config);
            //Debug.Log("ResourceRecovery ResourceRecoveryData OnSave beginn2 Foo.get_root()=" + SubRootNode.get_root());

            string lc = config.GetValue("loadcount");
            int lc2 = 0;
            Int32.TryParse(lc, out lc2);
            lc2 = lc2+1;
            config.SetValue("loadcount", lc2.ToString());

            config.SetValue("updated", DateTime.Now.ToString());

            //Debug.Log("ResourceRecovery ResourceRecoveryData OnSave ScenarioAttributes.get_ScenarioAttribute(version)=" + ScenarioAttributes.get_ScenarioAttribute("version"));
            config.SetValue("dll_version", ScenarioAttributes.get_ScenarioAttribute("dll_version"));
            config.SetValue("filesystem_version", ScenarioAttributes.get_ScenarioAttribute("filesystem_version"));

            config.SetValue("SaveGameKredits", ScenarioAttributes.get_ScenarioAttribute("SaveGameKredits"));

            config.AddNode(SubRootNode.get_sub_root());

            //Debug.Log("ResourceRecovery ResourceRecoveryData OnSave done config=" + config);
            Debug.Log("ResourceRecovery ResourceRecoveryData OnSave done");
        }
예제 #16
0
		public override void OnSave (ConfigNode cn)
		{
			if (_resourceFlags == null)
				return;
		
			foreach (var rf in _resourceFlags) {
				if (rf.Value != -1) {
					string flagName = rf.Key + "Flags";
					if (cn.HasValue (flagName))
						cn.SetValue (flagName, (rf.Value & 3).ToString ());
					else
						cn.AddValue (flagName, (rf.Value & 3).ToString ());
				}
			}
		}
예제 #17
0
		public static bool saveData (Configuration.dataLevel type)
		{
			Log.Info ("saveData dataLevel: " + type.ToString ());
			string path = getDataFile (type);
			Log.Info ("saveData: " + path);
			if (path == "")
				return false;
			
			ConfigNode root = new ConfigNode ();
			ConfigNode top = new ConfigNode (FileOperations.TT_NODENAME);
			root.SetNode (FileOperations.TT_NODENAME, top, true);

			switch (type) {
			case Configuration.dataLevel.game:
				top.SetValue ("secInGame", TotalTime.secInGame.ToString (), true);
				break;
			case Configuration.dataLevel.install:
				top.SetValue ("secInInstall", TotalTime.secInInstall.ToString (), true);
				break;
			case Configuration.dataLevel.global:
				top.SetValue ("secTotal", TotalTime.secTotal.ToString (), true);
				break;
			}


			root.Save (path);
			return false;
		}
 public override void OnSave(ConfigNode node)
 {
     base.OnSave(node);
     if (node.HasValue("RTAntennaTarget"))
     {
         node.SetValue("RTAntennaTarget", RTAntennaTarget.ToString());
     }
     else
     {
         node.AddValue("RTAntennaTarget", RTAntennaTarget.ToString());
     }
 }
예제 #19
0
        public static void WriteSetting(string settingName, string settingValue)
        {
            var fileInfo = new FileInfo(GetSaveFilePath());

            // File doesn't exist, so we only need to create the file and write the value.
            if (!fileInfo.Exists)
            {
                var rootConfigNode = new ConfigNode();
                var persistenceNode = rootConfigNode.AddNode("KerbTownPersistence");
                persistenceNode.AddValue(settingName, settingValue);

                rootConfigNode.Save(fileInfo.FullName);

                _ktSave = rootConfigNode;
                return;
            }

            var rootNode = ConfigNode.Load(fileInfo.FullName);
            _ktSave = rootNode.GetNode("KerbTownPersistence") ?? rootNode.AddNode("KerbTownPersistence");

            if (_ktSave.HasValue(settingName))
            {
                _ktSave.SetValue(settingName, settingValue);
            }
            else
            {
                _ktSave.AddValue(settingName, settingValue);
            }

            rootNode.Save(fileInfo.FullName);
        }
예제 #20
0
        private void SanitizeNode(ConfigNode module, ConfigNode[] templates)
        {
            string name = module.GetValue("name");

            if (module.HasNode("ScienceData"))
            {
                module.RemoveNodes("ScienceData");
            }
            if (name == "Log")
                module.ClearValues();

            ConfigNode template = templates.FirstOrDefault(t => t.GetValue("name") == name);
            if (template == null) return;
            ConfigNode.ValueList values = template.values;
            foreach (ConfigNode.Value val in values)
            {
                module.SetValue(val.name, val.value);
            }

            foreach (ConfigNode node in template.GetNodes()) //This should account for nested nodes, like RealChutes' PARACHUTE node
            {
                if (module.HasNode(node.name))
                {
                    foreach (ConfigNode.Value val in node.values)
                        module.GetNode(node.name).SetValue(val.name, val.value);
                }
            }

            foreach (ConfigNode node in module.GetNodes("MODULE"))
                SanitizeNode(node, templates);

            /*
            if (name.Contains("ModuleEngines"))
            {
                module.SetValue("staged", "False");
                module.SetValue("flameout", "False");
                module.SetValue("EngineIgnited", "False");
                module.SetValue("engineShutdown", "False");
                module.SetValue("currentThrottle", "0");
                module.SetValue("manuallyOverridden", "False");
            }
            else if (name == "ModuleScienceExperiment")
            {
                module.SetValue("Deployed", "False");
                module.SetValue("Inoperable", "False");
            }
            else if (name == "ModuleParachute")
            {
                module.SetValue("staged", "False");
                module.SetValue("persistentState", "STOWED");
            }
            else if (name == "Log")
            {
                module.ClearValues();
            }

            if (module.HasNode("ScienceData"))
            {
                module.RemoveNodes("ScienceData");
            }
            */
        }
        /// <summary>
        /// Re-initializes the engine and gimbal modules from their original config nodes -- this should -hopefully- allow them to grab updated transforms and update FX stuff properly
        /// </summary>
        private void reInitEngineModule()
        {
            SSTUEngineLayout layout = currentEngineLayout.getLayoutData();
            StartState state = HighLogic.LoadedSceneIsEditor ? StartState.Editor : HighLogic.LoadedSceneIsFlight ? StartState.Flying : StartState.None;

            //model constraints need to be updated whenever the number of models (or just the game-objects) are updated
            SSTUModelConstraint constraint = part.GetComponent<SSTUModelConstraint>();
            if (constraint != null)
            {
                constraint.reInitialize();
            }

            //animations need to be updated to find the new animations for the updated models
            SSTUAnimateControlled[] anims = part.GetComponents<SSTUAnimateControlled>();
            foreach (SSTUAnimateControlled controlled in anims)
            {
                controlled.reInitialize();
            }

            SSTUAnimateEngineHeat[] heatAnims = part.GetComponents<SSTUAnimateEngineHeat>();
            foreach (SSTUAnimateEngineHeat heatAnim in heatAnims)
            {
                heatAnim.reInitialize();
            }

            //update the engine module(s), forcing them to to reload their thrust, transforms, and effects.
            ModuleEngines[] engines = part.GetComponents<ModuleEngines>();
            if (minThrustBase == null)
            {
                setupThrustCache(engines);
                setupSplitThrustCache(engines);
            }
            ConfigNode engineNode;
            float maxThrust, minThrust;
            int positions = layout.positions.Count;
            for (int i = 0; i < engines.Length; i++)
            {
                engineNode = new ConfigNode("MODULE");
                minThrust = minThrustBase[i] * (float)positions;
                maxThrust = maxThrustBase[i] * (float)positions;
                engineNode.SetValue("minThrust", minThrust.ToString(), true);
                engineNode.SetValue("maxThrust", maxThrust.ToString(), true);
                if (trsMults[i].Length > 0)
                {
                    engineNode.AddNode(getSplitThrustNode(trsMults[i], positions));
                }
                engines[i].Load(engineNode);
                engines[i].OnStart(state);
            }
            SSTUModInterop.onEngineConfigChange(part, null, positions);//this forces ModuleEngineConfigs to reload the config, with the # of engines as the 'scale'

            //update the gimbal modules, force them to reload transforms
            ModuleGimbal[] gimbals = part.GetComponents<ModuleGimbal>();
            float limit = 0;
            for (int i = 0; i < gimbals.Length; i++)
            {
                limit = gimbals[i].gimbalLimiter;
                gimbals[i].gimbalTransforms = null;
                gimbals[i].initRots = null;
                gimbals[i].OnStart(state);
                gimbals[i].gimbalLimiter = limit;
            }
        }
예제 #22
0
        public ModuleResourceConverter AddFromTemplate(ConfigNode node)
        {
            string converterName = node.GetValue("ConverterName");
            Log("AddFromTemplate called for converter: " + converterName);

            ConfigNode settingsNode = null;
            if (converterStates.ContainsKey(converterName))
                settingsNode = converterStates[converterName];

            string value = node.GetValue("needs");
            if (string.IsNullOrEmpty(value) == false)
                if (TemplatesModel.CheckNeeds(value) == EInvalidTemplateReasons.RequiredModuleNotFound)
                    return null;

            //Courtesy of http://forum.kerbalspaceprogram.com/threads/27851-part-AddModule%28ConfigNode-node%29-NullReferenceException-in-PartModule-Load%28node%29-help
            ModuleResourceConverter converter = (ModuleResourceConverter)this.part.AddModule(node.GetValue("name"));
            object[] parameters = new object[] { };
            MethodInfo awakenMethod = typeof(PartModule).GetMethod("Awake", BindingFlags.Instance | BindingFlags.NonPublic);
            if (awakenMethod == null)
            {
                Log("No awaken method!");
                return null;
            }
            awakenMethod.Invoke(converter, parameters);
            converter.OnAwake();
            converter.OnActive();

            if (settingsNode != null)
            {
                foreach (ConfigNode.Value nodeValue in settingsNode.values)
                {
                    if (nodeValue.name != "name")
                        node.SetValue(nodeValue.name, nodeValue.value, true);
                }
                //Actions
                if (settingsNode.HasNode("ACTIONS"))
                {
                    ConfigNode actionsNode = settingsNode.GetNode("ACTIONS");
                    BaseAction action;

                    foreach (ConfigNode nodeAction in actionsNode.nodes)
                    {
                        action = converter.Actions[nodeAction.name];
                        if (action != null)
                        {
                            action.actionGroup = (KSPActionGroup)Enum.Parse(typeof(KSPActionGroup), nodeAction.GetValue("actionGroup"));
                        }
                    }
                }
            }
            converter.Load(node);

            if (HighLogic.LoadedSceneIsFlight)
            {
                switch (this.part.vessel.situation)
                {
                    case Vessel.Situations.ORBITING:
                        converter.OnStart(PartModule.StartState.Orbital);
                        break;
                    case Vessel.Situations.LANDED:
                        converter.OnStart(PartModule.StartState.Landed);
                        break;
                    case Vessel.Situations.SPLASHED:
                        converter.OnStart(PartModule.StartState.Splashed);
                        break;

                    case Vessel.Situations.SUB_ORBITAL:
                        converter.OnStart(PartModule.StartState.SubOrbital);
                        break;

                    case Vessel.Situations.FLYING:
                        converter.OnStart(PartModule.StartState.Flying);
                        break;

                    default:
                        converter.OnStart(PartModule.StartState.None);
                        break;
                }
            }

            else
            {
                converter.OnStart(PartModule.StartState.None);
            }
            converter.EnableModule();
            setConverterState(converter);

            //Remove the converter's GUI
            RunHeadless(converter);

            //Add it to the list
            this.converters.Add(converter);
            Debug.Log("Added converter " + converter.ConverterName);

            return converter;
        }
예제 #23
0
        public virtual void DoConfig(ConfigNode cfg)
        {
            configMaxThrust = configMinThrust = configHeat = -1f;
            // Get thrusts
            if (config.HasValue(thrustRating))
            {
                float thr;
                if (float.TryParse(config.GetValue(thrustRating), out thr))
                    configMaxThrust = scale * thr;
            }
            if (config.HasValue("minThrust"))
            {
                float thr;
                if (float.TryParse(config.GetValue("minThrust"), out thr))
                    configMinThrust = scale * thr;
            }

            // Get, multiply heat
            if (cfg.HasValue("heatProduction"))
            {
                float heat;
                if(float.TryParse(cfg.GetValue("heatProduction"), out heat))
                    configHeat = (float)Math.Round(heat * RFSettings.Instance.heatMultiplier, 0);
            }

            // load throttle (for later)
            configThrottle = throttle;
            if (cfg.HasValue("throttle"))
                float.TryParse(cfg.GetValue("throttle"), out configThrottle);
            else if (configMinThrust >= 0f && configMaxThrust >= 0f)
                configThrottle = configMinThrust / configMaxThrust;

            float TLMassMult = 1.0f;

            float gimbal = -1f;
            if (cfg.HasValue("gimbalRange"))
                gimbal = float.Parse(cfg.GetValue("gimbalRange"));

            float cost = 0f;
            if (cfg.HasValue("cost"))
                cost = scale * float.Parse(cfg.GetValue("cost"));

            if (techLevel != -1)
            {
                // load techlevels
                TechLevel cTL = new TechLevel();
                cTL.Load(cfg, techNodes, engineType, techLevel);
                TechLevel oTL = new TechLevel();
                oTL.Load(cfg, techNodes, engineType, origTechLevel);

                // set atmosphereCurve
                if (cfg.HasValue("IspSL") && cfg.HasValue("IspV"))
                {
                    cfg.RemoveNode("atmosphereCurve");

                    ConfigNode curve = new ConfigNode("atmosphereCurve");

                    // get the multipliers
                    float ispSL = 1f, ispV = 1f;
                    float.TryParse(cfg.GetValue("IspSL"), out ispSL);
                    float.TryParse(cfg.GetValue("IspV"), out ispV);

                    // Mod the curve by the multipliers
                    FloatCurve newAtmoCurve = new FloatCurve();
                    newAtmoCurve = Utilities.Mod(cTL.AtmosphereCurve, ispSL, ispV);
                    newAtmoCurve.Save(curve);

                    cfg.AddNode(curve);
                }

                // set heatProduction
                if (configHeat > 0)
                {
                    configHeat = MassTL(configHeat);
                }

                // set thrust and throttle
                if (configMaxThrust >= 0)
                {
                    configMaxThrust = ThrustTL(configMaxThrust);
                    if (configMinThrust >= 0)
                    {
                        configMinThrust = ThrustTL(configMinThrust);
                    }
                    else if (thrustRating.Equals("thrusterPower"))
                    {
                        configMinThrust = configMaxThrust * 0.5f;
                    }
                    else
                    {
                        configMinThrust = configMaxThrust;
                        if (configThrottle > 1.0f)
                        {
                            if (techLevel >= configThrottle)
                                configThrottle = 1.0f;
                            else
                                configThrottle = -1.0f;
                        }
                        if (configThrottle >= 0.0f)
                        {
                            configThrottle = (float)((double)configThrottle * cTL.Throttle());
                            configMinThrust *= configThrottle;
                        }
                    }
                    configThrottle = configMinThrust / configMaxThrust;
                    if (origMass > 0)
                        TLMassMult = MassTL(1.0f);
                }
                // Don't want to change gimbals on TL-enabled engines willy-nilly
                // So we don't unless either a transform is specified, or we override.
                // We assume if it was specified in the CONFIG that we should use it anyway.
                if (gimbal < 0 && (!gimbalTransform.Equals("") || useGimbalAnyway))
                    gimbal = cTL.GimbalRange;
                if (gimbal >= 0)
                {
                    // allow local override of gimbal mult
                    if (cfg.HasValue("gimbalMult"))
                        gimbal *= float.Parse(cfg.GetValue("gimbalMult"));
                }

                // Cost (multiplier will be 1.0 if unspecified)
                cost = scale * CostTL(cost, cfg);
            }
            else
            {
                if (cfg.HasValue(thrustRating) && configThrottle > 0f && !cfg.HasValue("minThrust"))
                {
                    configMinThrust = configThrottle * configMaxThrust;
                }
            }

            // Now update the cfg from what we did.
            // thrust updates
            if(configMaxThrust >= 0f)
                cfg.SetValue(thrustRating, configMaxThrust.ToString("0.0000"));
            if(configMinThrust >= 0f)
                cfg.SetValue("minThrust", configMinThrust.ToString("0.0000")); // will be ignored by RCS, so what.

            // heat update
            if(configHeat >= 0f)
                cfg.SetValue("heatProduction", configHeat.ToString("0"));

            // mass change
            if (origMass > 0)
            {
                float ftmp;
                configMassMult = scale;
                if (cfg.HasValue("massMult"))
                    if (float.TryParse(cfg.GetValue("massMult"), out ftmp))
                        configMassMult *= ftmp;

                part.mass = origMass * configMassMult * RFSettings.Instance.EngineMassMultiplier * TLMassMult;
                massDelta = 0;
                if ((object)(part.partInfo) != null)
                    if ((object)(part.partInfo.partPrefab) != null)
                        massDelta = part.mass - part.partInfo.partPrefab.mass;
            }

            // KIDS integration
            if (cfg.HasNode("atmosphereCurve"))
            {
                ConfigNode newCurveNode = new ConfigNode("atmosphereCurve");
                FloatCurve oldCurve = new FloatCurve();
                oldCurve.Load(cfg.GetNode("atmosphereCurve"));
                FloatCurve newCurve = Utilities.Mod(oldCurve, ispSLMult, ispVMult);
                newCurve.Save(newCurveNode);
                cfg.RemoveNode("atmosphereCurve");
                cfg.AddNode(newCurveNode);
            }
            // gimbal change
            if (gimbal >= 0 && !cfg.HasValue("gimbalRange")) // if TL set a gimbal
            {
                // apply module-wide gimbal mult on top of any local ones
                cfg.AddValue("gimbalRange", (gimbal * gimbalMult).ToString("N4"));
            }
            if (cost != 0f)
            {
                if (cfg.HasValue("cost"))
                    cfg.SetValue("cost", cost.ToString("N3"));
                else
                    cfg.AddValue("cost", cost.ToString("N3"));
            }
        }
예제 #24
0
        public virtual void FitEngineIfNecessary()
        {
            bool doFit = false;

            foreach (EngineParameterInfo entry in engineFitParameters)
            {
                if (ShouldFitParameter(entry))
                {
                    doFit = true;
                    break;
                }

            }

            // No parameters can be fit
            if (!doFit)
                return;

            doFit = false;

            ConfigNode node = EngineDatabase.GetNodeForEngine(this);
            if (node != null)
            {
                doFit |= EngineDatabase.PluginUpdateCheck(this, node);

                // Check for changes
                foreach (EngineParameterInfo entry in engineFitParameters)
                {
                    // Don't check things we're going to fit
                    if (ShouldFitParameter(entry))
                        continue;

                    if (!entry.EqualsValueInNode(node))
                    {
                        doFit = true;
                        break;
                    }
                }
                if (!doFit && node != null)
                {
                    Debug.Log("[" + this.GetType().Name + "] Reading engine params from cache for engine " + part.name);

                    CreateEngineIfNecessary();

                    foreach (EngineParameterInfo entry in engineFitParameters)
                    {
                        // Only copy things that would be fitted
                        if (ShouldFitParameter(entry))
                            entry.SetValueFromNode(node);
                    }
                    PushFitParamsToSolver();
                }
            }
            else
            {
                doFit = true;
            }

            if (doFit)
            {
                Debug.Log("[" + this.GetType().Name + "] Fitting params for engine " + part.name);

                CreateEngineIfNecessary();

                // Copy valid fit results from database - they might still be correct
                if (node != null)
                {
                    foreach (EngineParameterInfo entry in engineFitParameters)
                    {
                        // Only copy things that would be fitted
                        if (ShouldFitParameter(entry))
                            entry.SetValueFromNode(node);
                    }
                }

                // Make sure everything has the correct value
                PushFitParamsToSolver();
                DoEngineFit();

                ConfigNode newNode = new ConfigNode();

                foreach (EngineParameterInfo entry in engineFitParameters)
                {
                    newNode.SetValue(entry.Name, entry.GetValueStr(), true);
                }

                EngineDatabase.SetNodeForEngine(this, newNode);
            }
        }
예제 #25
0
        protected void loadModuleSettings(PartModule module, ConfigNode moduleNode, int index)
        {
            if (HighLogic.LoadedSceneIsFlight == false)
                return;

            Log("loadModuleSettings called");
            if (index > moduleSettings.Count - 1)
            {
                Log("Index > moduleSettings.Count!");
                return;
            }
            ConfigNode nodeSettings = moduleSettings[index];

            //Add any missing settings
            foreach (ConfigNode.Value nodeValue in moduleNode.values)
            {
                if (nodeSettings.HasValue(nodeValue.name) == false)
                    nodeSettings.AddValue(nodeValue.name, nodeValue.value);
            }

            //nodeSettings may have persistent fields. If so, then set them.
            foreach (ConfigNode.Value nodeValue in nodeSettings.values)
            {
                try
                {
                    if (nodeValue.name != "name")
                        moduleNode.SetValue(nodeValue.name, nodeValue.value, true);

                    if (module.Fields[nodeValue.name] != null)
                    {
                        Log("Set Field " + nodeValue.name + " to " + nodeValue.value);
                        module.Fields[nodeValue.name].Read(nodeValue.value, module);
                    }
                }
                catch (Exception ex)
                {
                    Log("Encountered an exception while setting values for " + moduleNode.GetValue("name") + ": " + ex);
                    continue;
                }
            }

            //Actions
            if (nodeSettings.HasNode("ACTIONS"))
            {
                ConfigNode actionsNode = nodeSettings.GetNode("ACTIONS");
                BaseAction action;

                foreach (ConfigNode node in actionsNode.nodes)
                {
                    action = module.Actions[node.name];
                    if (action != null)
                    {
                        action.actionGroup = (KSPActionGroup)Enum.Parse(typeof(KSPActionGroup), node.GetValue("actionGroup"));
                        Log("Set " + node.name + " to " + action.actionGroup);
                    }
                }
            }
        }
예제 #26
0
        virtual public void SetConfiguration(string newConfiguration = null)
        {
            if (newConfiguration == null)
                newConfiguration = configuration;
            ConfigNode newConfig = configs.Find (c => c.GetValue ("name").Equals (newConfiguration));
            if (newConfig != null) {

                // for asmi
                if (useConfigAsTitle)
                    part.partInfo.title = configuration;

                configuration = newConfiguration;
                config = new ConfigNode ("MODULE");
                newConfig.CopyTo (config);
                config.name = "MODULE";

                // fix for HotRockets etc.
                if (type.Equals("ModuleEngines") && part.Modules.Contains("ModuleEnginesFX") && !part.Modules.Contains("ModuleEngines"))
                    type = "ModuleEnginesFX";
                if (type.Equals("ModuleEnginesFX") && part.Modules.Contains("ModuleEngines") && !part.Modules.Contains("ModuleEnginesFX"))
                    type = "ModuleEngines";
                // fix for ModuleRCSFX etc
                if (type.Equals("ModuleRCS") && part.Modules.Contains("ModuleRCSFX") && !part.Modules.Contains("ModuleRCS"))
                    type = "ModuleRCSFX";
                if (type.Equals("ModuleRCSFX") && part.Modules.Contains("ModuleRCS") && !part.Modules.Contains("ModuleRCSFX"))
                    type = "ModuleRCS";

                config.SetValue("name", type);

                #if DEBUG
                print ("replacing " + type + " with:");
                print (newConfig.ToString ());
                #endif

                pModule = null;
                if (part.Modules.Contains(type))
                {
                    if (type.Equals("ModuleEnginesFX"))
                    {
                        if (engineID != "")
                        {
                            foreach (ModuleEnginesFX mFX in part.Modules.OfType<ModuleEnginesFX>())
                            {
                                if (mFX.engineID.Equals(engineID))
                                    pModule = (PartModule)mFX;
                            }
                        }
                        else if (moduleIndex >= 0)
                        {
                            int tmpIdx = 0;
                            pModule = null;
                            foreach (PartModule pM in part.Modules)
                            {
                                if (pM.GetType().Equals(type))
                                {
                                    if (tmpIdx == moduleIndex)
                                        pModule = pM;
                                    tmpIdx++;
                                }
                            }
                        }
                        else
                            pModule = part.Modules[type];
                    }
                    else
                        pModule = part.Modules[type];

                    if ((object)pModule == null)
                    {
                        Debug.Log("*RF* Could not find appropriate module of type " + type + ", with ID=" + engineID + " and index " + moduleIndex);
                        return;
                    }
                    // clear all FloatCurves
                    Type mType = pModule.GetType();
                    foreach (FieldInfo field in mType.GetFields())
                    {
                        if (field.FieldType == typeof(FloatCurve) && (field.Name.Equals("atmosphereCurve") || field.Name.Equals("velocityCurve")))
                        {
                            //print("*MFS* resetting curve " + field.Name);
                            field.SetValue(pModule, new FloatCurve());
                        }
                    }
                    // clear propellant gauges
                    foreach (FieldInfo field in mType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
                    {
                        if (field.FieldType == typeof(Dictionary<Propellant, VInfoBox>))
                        {
                            Dictionary<Propellant, VInfoBox> boxes = (Dictionary<Propellant, VInfoBox>)(field.GetValue(pModule));
                            if (boxes == null)
                                continue;
                            foreach (VInfoBox v in boxes.Values)
                            {
                                if (v == null) //just in case...
                                    continue;
                                try
                                {
                                    part.stackIcon.RemoveInfo(v);
                                }
                                catch (Exception e)
                                {
                                    print("*MFS* Trying to remove info box: " + e.Message);
                                }
                            }
                            boxes.Clear();
                        }
                    }
                }
                if (type.Equals("ModuleRCS") || type.Equals("ModuleRCSFX"))
                {
                    ModuleRCS rcs = (ModuleRCS)pModule;
                    if (rcs != null)
                    {
                        rcs.G = 9.80665f;
                        /*bool oldRes = config.HasValue("resourceName");
                        string resource = "";
                        if (oldRes)
                        {
                            resource = config.GetValue("resourceName");
                            rcs.resourceName = resource;
                        }*/
                        DoConfig(config);
                        if (config.HasNode("PROPELLANT"))
                        {
                            rcs.propellants.Clear();
                        }
                        pModule.Load(config);
                        /*if (oldRes)
                        {
                            rcs.resourceName = resource;
                            rcs.SetResource(resource);
                        }*/
                        // PROPELLANT handling is automatic.
                        fastRCS = rcs;
                        if(type.Equals("ModuleRCS") && !part.Modules.Contains("ModuleRCSFX"))
                            fastType = ModuleType.MODULERCS;
                        else
                            fastType = ModuleType.MODULERCSFX;
                    }
                }
                else
                { // is an ENGINE
                    if (type.Equals("ModuleEngines"))
                    {
                        ModuleEngines mE = (ModuleEngines)pModule;
                        if (mE != null)
                        {
                            configMaxThrust = mE.maxThrust;
                            configMinThrust = mE.minThrust;
                            fastEngines = mE;
                            fastType = ModuleType.MODULEENGINES;
                            mE.g = 9.80665f;
                            if (config.HasNode("PROPELLANT"))
                            {
                                mE.propellants.Clear();
                            }
                        }
                        if (config.HasValue("maxThrust"))
                        {
                            float thr;
                            if(float.TryParse(config.GetValue("maxThrust"), out thr))
                                configMaxThrust = thr;
                        }
                        if (config.HasValue("minThrust"))
                        {
                            float thr;
                            if(float.TryParse(config.GetValue("minThrust"), out thr))
                                configMinThrust = thr;
                        }
                    }
                    else if (type.Equals("ModuleEnginesFX"))
                    {
                        ModuleEnginesFX mE = (ModuleEnginesFX)pModule;
                        if (mE != null)
                        {
                            configMaxThrust = mE.maxThrust;
                            configMinThrust = mE.minThrust;
                            fastEnginesFX = mE;
                            fastType = ModuleType.MODULEENGINESFX;
                            mE.g = 9.80665f;
                            if (config.HasNode("PROPELLANT"))
                            {
                                mE.propellants.Clear();
                            }
                        }
                        if (config.HasValue("maxThrust"))
                        {
                            float thr;
                            if (float.TryParse(config.GetValue("maxThrust"), out thr))
                                configMaxThrust = thr;
                        }
                        if (config.HasValue("minThrust"))
                        {
                            float thr;
                            if (float.TryParse(config.GetValue("minThrust"), out thr))
                                configMinThrust = thr;
                        }
                    }
                    DoConfig(config);
                    if(pModule != null)
                        pModule.Load (config);
                    if (config.HasNode("ModuleEngineIgnitor") && part.Modules.Contains("ModuleEngineIgnitor"))
                    {
                        ConfigNode eiNode = config.GetNode("ModuleEngineIgnitor");
                        if (eiNode.HasValue("ignitionsAvailable"))
                        {
                            int ignitions;
                            if (int.TryParse(eiNode.GetValue("ignitionsAvailable"), out ignitions))
                            {
                                if (ignitions < 0)
                                {
                                    ignitions = techLevel + ignitions;
                                    if (ignitions < 1)
                                        ignitions = 1;
                                }
                                else if (ignitions == 0)
                                    ignitions = -1;

                                eiNode.SetValue("ignitionsAvailable", ignitions.ToString());
                                if (eiNode.HasValue("ignitionsRemained"))
                                    eiNode.SetValue("ignitionsRemained", ignitions.ToString());
                                else
                                    eiNode.AddValue("ignitionsRemained", ignitions.ToString());
                            }
                        }
                        if (!HighLogic.LoadedSceneIsEditor && !(HighLogic.LoadedSceneIsFlight && vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH)) // fix for prelaunch
                        {
                            int remaining = (int)(part.Modules["ModuleEngineIgnitor"].GetType().GetField("ignitionsRemained").GetValue(part.Modules["ModuleEngineIgnitor"]));
                            if(eiNode.HasValue("ignitionsRemained"))
                                eiNode.SetValue("ignitionsRemained", remaining.ToString());
                            else
                                eiNode.AddValue("ignitionsRemained", remaining.ToString());
                        }
                        ConfigNode tNode = new ConfigNode("MODULE");
                        eiNode.CopyTo(tNode);
                        tNode.SetValue("name", "ModuleEngineIgnitor");
                        part.Modules["ModuleEngineIgnitor"].Load(tNode);
                    }
                }
                if (part.Resources.Contains("ElectricCharge") && part.Resources["ElectricCharge"].maxAmount < 0.1)
                { // hacking around a KSP bug here
                    part.Resources["ElectricCharge"].amount = 0;
                    part.Resources["ElectricCharge"].maxAmount = 0.1;
                }
                if (config.HasValue("cost"))
                    configCost = float.Parse(config.GetValue("cost"));
                UpdateTweakableMenu();
                // Check for and enable the thrust curve
                useThrustCurve = false;
                Fields["thrustCurveDisplay"].guiActive = false;
                if (config.HasNode("thrustCurve") && config.HasValue("curveResource"))
                {
                    curveResource = config.GetValue("curveResource");
                    if (curveResource != "")
                    {
                        double ratio = 0.0;
                        switch (fastType)
                        {
                            case ModuleType.MODULEENGINES:
                                configHeat = fastEngines.heatProduction;
                                for (int i = 0; i < fastEngines.propellants.Count; i++ )
                                    if (fastEngines.propellants[i].name.Equals(curveResource))
                                        curveProp = i;
                                if (curveProp >= 0)
                                    ratio = fastEngines.propellants[curveProp].totalResourceAvailable / fastEngines.propellants[curveProp].totalResourceCapacity;
                                break;

                            case ModuleType.MODULEENGINESFX:
                                configHeat = fastEnginesFX.heatProduction;
                                for (int i = 0; i < fastEnginesFX.propellants.Count; i++)
                                    if (fastEnginesFX.propellants[i].name.Equals(curveResource))
                                        curveProp = i;
                                if (curveProp >= 0)
                                    ratio = fastEnginesFX.propellants[curveProp].totalResourceAvailable / fastEnginesFX.propellants[curveProp].totalResourceCapacity;
                                break;

                            case ModuleType.MODULERCS:
                                for (int i = 0; i < fastRCS.propellants.Count; i++)
                                    if (fastRCS.propellants[i].name.Equals(curveResource))
                                        curveProp = i;
                                if (curveProp >= 0)
                                    ratio = fastRCS.propellants[curveProp].totalResourceAvailable / fastRCS.propellants[curveProp].totalResourceCapacity;
                                break;
                        }
                        if (curveProp != -1)
                        {
                            useThrustCurve = true;
                            configThrustCurve = new FloatCurve();
                            configThrustCurve.Load(config.GetNode("thrustCurve"));
                            print("*RF* Found thrust curve for " + part.name);
                            Fields["thrustCurveDisplay"].guiActive = true;
                        }
                        
                    }
                }
            }
            
        }
        private void LoadState(ConfigNode configNode)
        {
            if (configNode != null)
            {
                if (configNode.HasValue("useStockSkin"))
                {
                    if (configNode.GetValue("useStockSkin") == "true")
                    {
                        configNode.SetValue("useStockSkin", "true");
                    }
                }

                if (configNode.HasValue("useOldPresetEditor"))
                {
                    if (configNode.GetValue("useOldPresetEditor") == "true")
                    {
                        configNode.SetValue("useOldPresetEditor", "true");
                    }
                }
            }

            m_Configuration = Configuration.Deserialize(GetAbsoluteConfigurationPath());
            if (m_Configuration == null)
            {
                m_Configuration = new Configuration();
                Configuration.Serialize(GetAbsoluteConfigurationPath(), m_Configuration);
            }

            m_FlightManager.m_Configuration = m_Configuration;
        }
예제 #28
0
 public void Save(ConfigNode node)
 {
     node.SetValue("positive", KSPUtil.WriteVector(positive));
     node.SetValue("negative", KSPUtil.WriteVector(negative));
 }
예제 #29
0
 public void Save(ConfigNode node)
 {
     node.SetValue("Kp", Kp.ToString());
     node.SetValue("Ki", Ki.ToString());
     node.SetValue("Kd", Kd.ToString());
 }
예제 #30
0
        override public void SetConfiguration(string newConfiguration = null)
        {
            if (newConfiguration == null)
                newConfiguration = configuration;
            ConfigNode newConfig = configs.Find (c => c.GetValue ("name").Equals (newConfiguration));
            pModule = part.Modules[type];
            if (newConfig == null || pModule == null)
                return;

            // fix for HotRockets etc.
            if (type.Equals("ModuleEngines") && part.Modules.Contains("ModuleEnginesFX") && !part.Modules.Contains("ModuleEngines"))
                type = "ModuleEnginesFX";

            if (type.Equals("ModuleEnginesFX"))
                ActiveEngine = new EngineWrapper((ModuleEnginesFX)part.Modules[type]);
            else if (type.Equals("ModuleEngines"))
                ActiveEngine = new EngineWrapper((ModuleEngines)part.Modules[type]);
            else
                print("*RF* trying to start " + part.name + " but is neither ME nor MEFX! (type = " + type + ")");

            ActiveEngine.g = 9.80665f;

            Fields ["configuration"].guiActive = true;
            Fields ["configuration"].guiName = "Current Mode";

            configuration = newConfiguration;
            config = new ConfigNode ("MODULE");
            newConfig.CopyTo (config);
            config.name = "MODULE";
            config.SetValue ("name", type);

            // clear all relevant FloatCurves
            Type mType = pModule.GetType();
            foreach (FieldInfo field in mType.GetFields())
            {
                if (field.FieldType == typeof(FloatCurve) && (field.Name.Equals("atmosphereCurve") || field.Name.Equals("velocityCurve")))
                {
                    //print("*MFS* resetting curve " + field.Name);
                    field.SetValue(pModule, new FloatCurve());
                }
            }
            // clear propellant gauges Squad made
            foreach (FieldInfo field in mType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (field.FieldType == typeof(Dictionary<Propellant, VInfoBox>))
                {
                    Dictionary<Propellant, VInfoBox> boxes = (Dictionary<Propellant, VInfoBox>)(field.GetValue(pModule));
                    if (boxes == null)
                        continue;
                    foreach (VInfoBox v in boxes.Values)
                    {
                        if (v == null) //just in case...
                            continue;
                        try
                        {
                            part.stackIcon.RemoveInfo(v);
                        }
                        catch (Exception e)
                        {
                            print("*MFS* Trying to remove info box: " + e.Message);
                        }
                    }
                    boxes.Clear();
                }
            }
            

            bool engineActive = ActiveEngine.getIgnitionState;
            ActiveEngine.EngineIgnited = false;

            //  remove all fuel gauges we made
            ClearMeters ();
            propellants.Clear ();

            if (type.Equals("ModuleEngines"))
            {
                ModuleEngines mE = (ModuleEngines)pModule;
                if (mE != null)
                {
                    configMaxThrust = mE.maxThrust;
                    configMinThrust = mE.minThrust;
                    fastEngines = mE;
                    fastType = ModuleType.MODULEENGINES;
                }
                if (config.HasValue("maxThrust"))
                {
                    float thr;
                    if (float.TryParse(config.GetValue("maxThrust"), out thr))
                        configMaxThrust = thr;
                }
                if (config.HasValue("minThrust"))
                {
                    float thr;
                    if (float.TryParse(config.GetValue("minThrust"), out thr))
                        configMinThrust = thr;
                }
            }
            else if (type.Equals("ModuleEnginesFX"))
            {
                ModuleEnginesFX mE = (ModuleEnginesFX)pModule;
                if (mE != null)
                {
                    configMaxThrust = mE.maxThrust;
                    configMinThrust = mE.minThrust;
                    fastEnginesFX = mE;
                    fastType = ModuleType.MODULEENGINESFX;
                }
                if (config.HasValue("maxThrust"))
                {
                    float thr;
                    if (float.TryParse(config.GetValue("maxThrust"), out thr))
                        configMaxThrust = thr;
                }
                if (config.HasValue("minThrust"))
                {
                    float thr;
                    if (float.TryParse(config.GetValue("minThrust"), out thr))
                        configMinThrust = thr;
                }
            }

            DoConfig(config); // from MEC

            //  load the new engine state
            pModule.Load(config);

            // I'd think the load, above, would do this already. So maybe unnecessary?
            if (config.HasValue ("useVelocityCurve") && (config.GetValue ("useVelocityCurve").ToLowerInvariant () == "true")) {
                ActiveEngine.velocityCurve.Load (config.GetNode ("velocityCurve"));
            } else {
                ActiveEngine.useVelocityCurve = false;
            }

            //  set up propellants
            foreach (Propellant propellant in ActiveEngine.propellants) {
                if(propellant.drawStackGauge) { // we need to handle fuel gauges ourselves
                    propellant.drawStackGauge = false;
                    propellants.Add (propellant);
                }
            }
            ActiveEngine.SetupPropellant ();

            if (engineActive)
                ActiveEngine.Actions ["ActivateAction"].Invoke (new KSPActionParam (KSPActionGroup.None, KSPActionType.Activate));

            UpdateTweakableMenu();
        }