Ejemplo n.º 1
0
        public override void OnStart(StartState state)
        {
            if (HighLogic.LoadedSceneIsFlight && this.part != null && this.part.Modules != null)
            {
                this.wheelDamage = part.Modules.OfType <ModuleWheels.ModuleWheelDamage>().First();

                foreach (BaseEvent e in this.wheelDamage.Events)
                {
                    if (e.name == "EventRepairExternal")
                    {
                        EVARepairEvent = e;
                    }
                }

                this.wheelBase = part.Modules.OfType <ModuleWheelBase>().First();

                if (this.wheelBase.wheelType == WheelType.LEG)
                {
                    parttype = "leg";
                }
                else
                {
                    parttype = "wheel";
                }
            }
        }
        void LateUpdate()
        {
            if (launcherButtonNeedsInitializing)
            {
                Log("LateUpdate()", false);
                Audio.initializeAudio();

                GameEvents.onGameStateSaved.Add(OnSave);

                launcherButtonNeedsInitializing = false;
                updateStopwatch = new Stopwatch();
                updateStopwatch.Start();

                LoadSettings(settingsURL);

                ModuleWheelBase myModuleWheelBase = new ModuleWheelBase();

                Joint[] j = myModuleWheelBase.GetComponents <Joint>();

                foreach (Joint jo in j)
                {
                    UnityEngine.Debug.DrawLine(jo.transform.localPosition, jo.connectedBody.gameObject.transform.localPosition);
                }
            }
        }
Ejemplo n.º 3
0
 public ModuleWheelBaseAdaptor(Part part)
 {
     _moduleWheelBase          = part.FindModuleImplementing <ModuleWheelBase>();
     _moduleWheelMotor         = part.FindModuleImplementing <ModuleWheelMotor>();
     _moduleWheelMotorSteering = part.FindModuleImplementing <ModuleWheelMotorSteering>();
     _moduleWheelDamage        = part.FindModuleImplementing <ModuleWheelDamage>();
 }
 public ModuleWheelBaseAdaptor(Part part)
 {
     _moduleWheelBase = part.FindModuleImplementing<ModuleWheelBase>();
     _moduleWheelMotor = part.FindModuleImplementing<ModuleWheelMotor>();
     _moduleWheelMotorSteering = part.FindModuleImplementing<ModuleWheelMotorSteering>();
     _moduleWheelDamage = part.FindModuleImplementing<ModuleWheelDamage>();
 }
 public override void OnStart(StartState state)
 {
     base.OnStart(state);
     this.wheelBase     = base.part.FindModuleImplementing <ModuleWheelBase>();
     this.wheelSteering = base.part.FindModuleImplementing <ModuleWheelSteering>();
     this.wheelBrakes   = base.part.FindModuleImplementing <ModuleWheelBrakes>();
     this.wheelMotor    = base.part.FindModuleImplementing <ModuleWheelMotor>();
 }
        public override void OnAwake()
        {
            base.OnAwake();
            Log.dbg("GearHarpoonReconnector: awaking");

            // Still no idea how to reliably receive OnCollisionEnter event on wheels
            // so polling state each 0.5s and giving up in 10s
            // TODO: Make configurable
            wheelBase = (ModuleWheelBase)part.Modules ["ModuleWheelBase"];
            InvokeRepeating("checkLanded", WorldStabilizer.checkLandedPeriod, WorldStabilizer.checkLandedPeriod);
            Invoke("selfDestruct", WorldStabilizer.checkLandedTimeout);
        }
Ejemplo n.º 7
0
 static bool Prefix(ModuleWheelBase __instance, GameEvents.FromToAction <Part, Part> FromTo)
 {
     if (FromTo.from.vessel == __instance.vessel || FromTo.to.vessel == __instance.vessel)
     {
         VesselPhysicsHold physicsHold = __instance.vessel.GetComponent <VesselPhysicsHold>();
         if (physicsHold != null && (physicsHold.physicsHold || physicsHold.delayedPhysicsHoldEnableRequest))
         {
             return(false);
         }
     }
     return(true);
 }
Ejemplo n.º 8
0
        internal Leg(Part part)
        {
            if (!Is(part))
            {
                throw new ArgumentException("Part is not a landing leg");
            }
            Part = part;
            var internalPart = part.InternalPart;

            wheel      = internalPart.Module <ModuleWheelBase> ();
            deployment = internalPart.Module <ModuleWheels.ModuleWheelDeployment> ();
            damage     = internalPart.Module <ModuleWheels.ModuleWheelDamage> ();
        }
        public override void OnStart(StartState state)
        {
            if (state == StartState.Editor || state == StartState.None)
            {
                return;
            }

            string partParentName = part.name + "_" + this.moduleName;

            audioParent = part.gameObject.GetChild(partParentName);
            if (audioParent == null)
            {
                audioParent = new GameObject(partParentName);
                audioParent.transform.rotation = part.transform.rotation;
                audioParent.transform.position = part.transform.position;
                audioParent.transform.parent   = part.transform;
            }

            moduleWheel  = part.GetComponent <ModuleWheelBase>();
            moduleMotor  = part.GetComponent <ModuleWheelMotor>();
            moduleDeploy = part.GetComponent <ModuleWheelDeployment>();

            var configNode = AudioUtility.GetConfigNode(part.partInfo.name, this.moduleName);

            SoundLayerGroups.Clear();
            spools.Clear();
            foreach (var node in configNode.GetNodes())
            {
                string _wheelState = node.name;

                var soundLayers = AudioUtility.CreateSoundLayerGroup(node.GetNodes("SOUNDLAYER"));
                if (soundLayers.Count > 0)
                {
                    if (SoundLayerGroups.ContainsKey(_wheelState))
                    {
                        SoundLayerGroups[_wheelState].AddRange(soundLayers);
                    }
                    else
                    {
                        SoundLayerGroups.Add(_wheelState, soundLayers);
                    }
                }
            }

            GameEvents.onGamePause.Add(onGamePause);
            GameEvents.onGameUnpause.Add(onGameUnpause);

            initialized = true;
        }
Ejemplo n.º 10
0
        public override void OnStart(StartState state)
        {
            if (state == StartState.Editor || state == StartState.None)
            {
                return;
            }

            SetupParticles();
            if (scrapeSparks)
            {
                SetupLight();
            }

            if (part.Modules.Contains("ModuleWheelBase")) // Suppress the log message on failure.
            {
                moduleWheel = part.Modules["ModuleWheelBase"] as ModuleWheelBase;
            }
            if (part.Modules.Contains("ModuleWheelDamage"))
            {
                moduleWheelDamage = part.Modules["ModuleWheelDamage"] as ModuleWheelDamage;
            }
            wheelCollider = part.GetComponent <WheelCollider>();
            // No longer necessary, all wheel parts and landing gear parts are the same now - Alshain01

            /*if (wheelCollider == null)
             * {
             *  ModuleLandingGear gear = part.GetComponent<ModuleLandingGear>();
             *  if (gear != null)
             *  {
             *      wheelCollider = gear.wheelCollider;
             *  }
             * }*/

            SetupAudio();

            GameEvents.onGamePause.Add(OnPause);
            GameEvents.onGameUnpause.Add(OnUnpause);

#if DEBUG
            for (int i = 0; i < spheres.Length; i++)
            {
                spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                Destroy(spheres[i].GetComponent <Collider>());
            }
            spheres[0].GetComponent <Renderer>().material.color = Color.red;
            spheres[1].GetComponent <Renderer>().material.color = Color.green;
#endif
        }
Ejemplo n.º 11
0
        internal Wheel(Part part)
        {
            if (!Is(part))
            {
                throw new ArgumentException("Part is not a wheel");
            }
            Part = part;
            var internalPart = part.InternalPart;

            wheel      = internalPart.Module <ModuleWheelBase>();
            brakes     = internalPart.Module <ModuleWheels.ModuleWheelBrakes>();
            damage     = internalPart.Module <ModuleWheels.ModuleWheelDamage>();
            deployment = internalPart.Module <ModuleWheels.ModuleWheelDeployment>();
            motor      = internalPart.Module <ModuleWheels.ModuleWheelMotor> ();
            steering   = internalPart.Module <ModuleWheels.ModuleWheelSteering>();
            suspension = internalPart.Module <ModuleWheels.ModuleWheelSuspension>();
        }
        public override void OnStart(StartState state)
        {
            Log.InitLog();
            if (state == StartState.Editor || state == StartState.None)
            {
                return;
            }

            SetupParticles();
            if (scrapeSparks)
            {
                SetupLight();
            }

            moduleWheel = part.FindModuleImplementing <ModuleWheelBase>();
            if (moduleWheel != null)
            {
                moduleWheelDamage     = part.FindModuleImplementing <ModuleWheelDamage>();
                moduleWheelDeployment = part.FindModuleImplementing <ModuleWheelDeployment>();
                wheelCollider         = moduleWheel.wheelColliderHost.GetComponent <WheelCollider>();
                InvokeRepeating("checkLanding", 0f, 0.5f);
            }

            part.GetComponent <AudioBehaviour>().enabled = true;;

            SetupAudio();

            GameEvents.onGamePause.Add(OnPause);
            GameEvents.onGameUnpause.Add(OnUnpause);

#if DEBUG
            if (useSpheres)
            {
                for (int i = 0; i < spheres.Length; i++)
                {
                    spheres[i] = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                    Destroy(spheres[i].GetComponent <Collider>());
                }
                spheres[0].GetComponent <Renderer>().material.color = Color.red;
                spheres[1].GetComponent <Renderer>().material.color = Color.green;
                spheres[3].GetComponent <Renderer>().material.color = Color.yellow;
            }
#endif
            //_sparklauncher = gameObject.AddComponent<SparkLauncher>();
        }
Ejemplo n.º 13
0
        static bool Prefix(ModuleWheelBase __instance, Vessel fromVessel, Vessel toVessel)
        {
            if (fromVessel == __instance.vessel || toVessel == __instance.vessel)
            {
                VesselPhysicsHold toVesselPhysicsHold = fromVessel.GetComponent <VesselPhysicsHold>();
                if (toVesselPhysicsHold != null && (toVesselPhysicsHold.physicsHold || toVesselPhysicsHold.delayedPhysicsHoldEnableRequest))
                {
                    return(false);
                }

                VesselPhysicsHold fromVesselPhysicsHold = toVessel.GetComponent <VesselPhysicsHold>();
                if (fromVesselPhysicsHold != null && (fromVesselPhysicsHold.physicsHold || fromVesselPhysicsHold.delayedPhysicsHoldEnableRequest))
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 14
0
        //Trying to use animation to shorten/widen the wheelbase looks really wonky, so we'll do this in code by moving the transforms.
        //Sadly this doesn't work to well when we have stuff piled onto the chassis. I think this is basically the right approach but
        //shelved for now.
        private void setWheelbase()
        {
            if (!toggledAtLeastOnce)
            {
                return;
            }

            ModuleWheelBase wheelBase = this.part.FindModuleImplementing <ModuleWheelBase>();

            if (isNarrowWheelbase)
            {
                wheelBase.wheelColliderHost.Translate(0.185f, 0f, 0f);
                wheelPylon.Translate(0.185f, 0f, 0f);
            }
            else
            {
                wheelBase.wheelColliderHost.Translate(-0.185f, 0f, 0f);
                wheelPylon.Translate(-0.185f, 0f, 0f);
            }

            ModuleWheelSteering steering = this.part.FindModuleImplementing <ModuleWheelSteering>();
        }
        private void SetupTransforms()
        {
            if (_wheel == null)
            {
                _wheel = part.FindModuleImplementing <ModuleWheelBase>();
            }
            if (_wheelTransform == null)
            {
                _wheelTransform = part.FindModelTransform(wheelTransform);
            }

            ServoTransforms = new List <ServoData>();
            var tList = transformConfig.Split(',');

            for (int i = 0; i < tList.Count(); i += 10)
            {
                var g   = part.FindModelTransform(tList[i]);
                var min = new ServoPosition {
                    x = float.Parse(tList[i + 1]), y = float.Parse(tList[i + 2]), z = float.Parse(tList[i + 3])
                };
                var max = new ServoPosition {
                    x = float.Parse(tList[i + 4]), y = float.Parse(tList[i + 5]), z = float.Parse(tList[i + 6])
                };
                var rot = new ServoPosition {
                    x = float.Parse(tList[i + 7]), y = float.Parse(tList[i + 8]), z = float.Parse(tList[i + 9])
                };
                var rx = Math.Abs(rot.x) > ResourceUtilities.FLOAT_TOLERANCE;
                var ry = Math.Abs(rot.y) > ResourceUtilities.FLOAT_TOLERANCE;
                var rz = Math.Abs(rot.z) > ResourceUtilities.FLOAT_TOLERANCE;
                ServoTransforms.Add(new ServoData {
                    ServoTransform = g, MinRange = min, MaxRange = max, StepAmount = rot, ChangeX = rx, ChangeY = ry, ChangeZ = rz
                });
            }
            LoadPositions();
            ApplyStartPosition();
            SetGUIValues();
            MonoUtilities.RefreshContextWindows(part);
        }
Ejemplo n.º 16
0
 public void OnDestroy()
 {
     this.wheelDamage    = null;
     this.wheelBase      = null;
     this.EVARepairEvent = null;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Checks standard wheels with module ModuleWheelBase
        /// </summary>
        private WheelTestResult CheckWheels()
        {
            double powerRequired = 0;
            double maxSpeedSum   = 0;
            int    inTheAir      = 0;
            int    operable      = 0;
            int    damaged       = 0;
            int    online        = 0;

            List <Part> wheels = new List <Part>();

            for (int i = 0; i < this.vessel.parts.Count; i++)
            {
                var part = this.vessel.parts [i];
                if (part.Modules.Contains("ModuleWheelBase"))
                {
                    wheels.Add(part);
                }
            }

            for (int i = 0; i < wheels.Count; i++)
            {
                ModuleWheelBase wheelBase = wheels[i].FindModuleImplementing <ModuleWheelBase> ();
                if (wheelBase.wheelType == WheelType.LEG)
                {
                    continue;
                }

                ModuleWheels.ModuleWheelDamage wheelDamage = wheels[i].FindModuleImplementing <ModuleWheels.ModuleWheelDamage> ();
                // Malemute and Karibou wheels do not implement moduleDamage, so they're unbreakable?
                if (wheelDamage != null)
                {
                    // Wheel is damaged
                    if (wheelDamage.isDamaged)
                    {
                        damaged++;
                        continue;
                    }
                }

                // Whether or not wheel is touching the ground
                if (!wheelBase.isGrounded)
                {
                    inTheAir++;
                    continue;
                }
                else
                {
                    operable++;
                }

                ModuleWheels.ModuleWheelMotor wheelMotor = wheels[i].FindModuleImplementing <ModuleWheels.ModuleWheelMotor> ();
                if (wheelMotor != null)
                {
                    // Wheel is on
                    if (wheelMotor.motorEnabled)
                    {
                        powerRequired += wheelMotor.avgResRate;
                        online++;
                        double maxWheelSpeed = 0;
                        if (wheelMotor.part.name == "roverWheel1")                         //RoveMax Model M1 gives crazy values
                        {
                            maxWheelSpeed = 42;
                        }
                        else
                        {
                            maxWheelSpeed = wheelMotor.wheelSpeedMax;
                        }
                        maxSpeedSum += maxWheelSpeed;
                    }
                }
            }
            return(new WheelTestResult(powerRequired, maxSpeedSum, inTheAir, operable, damaged, online));
        }
Ejemplo n.º 18
0
        private void OnWindow(int windowId)
        {
            try
            {
                GUILayout.BeginVertical();

                // Get all modules of the selected part:
                String                         partTitle              = "";
                Part                           part                   = null;
                KRnDModule                     rndModule              = null;
                List <ModuleEngines>           engineModules          = null;
                ModuleRCS                      rcsModule              = null;
                ModuleReactionWheel            reactionWheelModule    = null;
                ModuleDeployableSolarPanel     solarPanelModule       = null;
                ModuleWheelBase                landingLegModule       = null;
                PartResource                   electricChargeResource = null;
                ModuleGenerator                generatorModule        = null;
                PartModule                     fissionGenerator       = null;
                List <ModuleResourceConverter> converterModules       = null;
                ModuleParachute                parachuteModule        = null;
                List <PartResource>            fuelResources          = null;
                if (selectedPart != null)
                {
                    foreach (AvailablePart aPart in PartLoader.LoadedPartsList)
                    {
                        if (aPart.partPrefab.name == selectedPart.name)
                        {
                            part      = aPart.partPrefab;
                            partTitle = aPart.title;
                            break;
                        }
                    }
                    if (part)
                    {
                        rndModule              = KRnD.getKRnDModule(part);
                        engineModules          = KRnD.getEngineModules(part);
                        rcsModule              = KRnD.getRcsModule(part);
                        reactionWheelModule    = KRnD.getReactionWheelModule(part);
                        solarPanelModule       = KRnD.getSolarPanelModule(part);
                        landingLegModule       = KRnD.getLandingLegModule(part);
                        electricChargeResource = KRnD.getChargeResource(part);
                        generatorModule        = KRnD.getGeneratorModule(part);
                        fissionGenerator       = KRnD.getFissionGeneratorModule(part);
                        converterModules       = KRnD.getConverterModules(part);
                        parachuteModule        = KRnD.getParachuteModule(part);
                        fuelResources          = KRnD.getFuelResources(part);
                    }
                }
                if (!part)
                {
                    // No part selected:
                    GUILayout.BeginArea(new Rect(10, 5, windowStyle.fixedWidth, 20));
                    GUILayout.Label("<b>Kerbal R&D: Select a part to improve</b>", labelStyle);
                    GUILayout.EndArea();
                    GUILayout.EndVertical();
                    GUI.DragWindow();
                    return;
                }
                else if (!rndModule)
                {
                    // Invalid part selected:
                    GUILayout.BeginArea(new Rect(10, 5, windowStyle.fixedWidth, 20));
                    GUILayout.Label("<b>Kerbal R&D: Select a different part to improve</b>", labelStyle);
                    GUILayout.EndArea();
                    GUILayout.EndVertical();
                    GUI.DragWindow();
                    return;
                }

                // Get stats of the current version of the selected part:
                KRnDUpgrade currentUpgrade;
                if (!KRnD.upgrades.TryGetValue(part.name, out currentUpgrade))
                {
                    currentUpgrade = new KRnDUpgrade();
                }
                String currentInfo = getPartInfo(part, currentUpgrade);

                // Create a copy of the part-stats which we can use to mock an upgrade further below:
                KRnDUpgrade nextUpgrade = currentUpgrade.clone();

                // Title:
                GUILayout.BeginArea(new Rect(10, 5, windowStyle.fixedWidth, 20));
                String version = rndModule.getVersion();
                if (version != "")
                {
                    version = " - " + version;
                }
                GUILayout.Label("<b>" + partTitle + version + "</b>", labelStyle);
                GUILayout.EndArea();

                // List with upgrade-options:
                float optionsWidth  = 100;
                float optionsHeight = windowStyle.fixedHeight - 30 - 30 - 20;
                GUILayout.BeginArea(new Rect(10, 30 + 20, optionsWidth, optionsHeight));

                List <String> options = new List <String>();
                options.Add("Dry Mass");
                options.Add("Max Temp");
                if (engineModules != null || rcsModule)
                {
                    options.Add("ISP Vac");
                    options.Add("ISP Atm");
                    options.Add("Fuel Flow");
                }
                if (reactionWheelModule != null)
                {
                    options.Add("Torque");
                }
                if (solarPanelModule != null)
                {
                    options.Add("Charge Rate");
                }
                if (landingLegModule != null)
                {
                    options.Add("Crash Tolerance");
                }
                if (electricChargeResource != null)
                {
                    options.Add("Battery");
                }
                if (fuelResources != null)
                {
                    options.Add("Fuel Pressure");
                }
                if (generatorModule || fissionGenerator)
                {
                    options.Add("Generator");
                }
                if (converterModules != null)
                {
                    options.Add("Converter");
                }
                if (parachuteModule)
                {
                    options.Add("Parachute");
                }
                if (this.selectedUpgradeOption >= options.Count)
                {
                    this.selectedUpgradeOption = 0;
                }
                this.selectedUpgradeOption = GUILayout.SelectionGrid(this.selectedUpgradeOption, options.ToArray(), 1, buttonStyle);
                GUILayout.EndArea();

                String           selectedUpgradeOption = options.ToArray()[this.selectedUpgradeOption];
                int              currentUpgradeCount   = 0;
                int              nextUpgradeCount      = 0;
                int              scienceCost           = 0;
                float            currentImprovement    = 0;
                float            nextImprovement       = 0;
                Func <Part, int> upgradeFunction       = null;
                if (selectedUpgradeOption == "ISP Vac")
                {
                    upgradeFunction     = KRnDGUI.UpgradeIspVac;
                    currentUpgradeCount = currentUpgrade.ispVac;
                    nextUpgradeCount    = ++nextUpgrade.ispVac;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.ispVac_improvement, rndModule.ispVac_improvementScale, currentUpgrade.ispVac);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.ispVac_improvement, rndModule.ispVac_improvementScale, nextUpgrade.ispVac);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.ispVac_scienceCost, rndModule.ispVac_costScale, nextUpgrade.ispVac);
                }
                else if (selectedUpgradeOption == "ISP Atm")
                {
                    upgradeFunction     = KRnDGUI.UpgradeIspAtm;
                    currentUpgradeCount = currentUpgrade.ispAtm;
                    nextUpgradeCount    = ++nextUpgrade.ispAtm;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.ispAtm_improvement, rndModule.ispAtm_improvementScale, currentUpgrade.ispAtm);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.ispAtm_improvement, rndModule.ispAtm_improvementScale, nextUpgrade.ispAtm);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.ispAtm_scienceCost, rndModule.ispAtm_costScale, nextUpgrade.ispAtm);
                }
                else if (selectedUpgradeOption == "Fuel Flow")
                {
                    upgradeFunction     = KRnDGUI.UpgradeFuelFlow;
                    currentUpgradeCount = currentUpgrade.fuelFlow;
                    nextUpgradeCount    = ++nextUpgrade.fuelFlow;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.fuelFlow_improvement, rndModule.fuelFlow_improvementScale, currentUpgrade.fuelFlow);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.fuelFlow_improvement, rndModule.fuelFlow_improvementScale, nextUpgrade.fuelFlow);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.fuelFlow_scienceCost, rndModule.fuelFlow_costScale, nextUpgrade.fuelFlow);
                }
                else if (selectedUpgradeOption == "Dry Mass")
                {
                    upgradeFunction     = KRnDGUI.UpgradeDryMass;
                    currentUpgradeCount = currentUpgrade.dryMass;
                    nextUpgradeCount    = ++nextUpgrade.dryMass;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.dryMass_improvement, rndModule.dryMass_improvementScale, currentUpgrade.dryMass);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.dryMass_improvement, rndModule.dryMass_improvementScale, nextUpgrade.dryMass);

                    // Scale science cost with original mass:
                    PartStats originalStats;
                    if (!KRnD.originalStats.TryGetValue(part.name, out originalStats))
                    {
                        throw new Exception("no original-stats for part '" + part.name + "'");
                    }
                    float scaleReferenceFactor = 1;
                    if (rndModule.dryMass_costScaleReference > 0)
                    {
                        scaleReferenceFactor = originalStats.mass / rndModule.dryMass_costScaleReference;
                    }
                    int scaledCost = (int)Math.Round(rndModule.dryMass_scienceCost * scaleReferenceFactor);
                    if (scaledCost < 1)
                    {
                        scaledCost = 1;
                    }
                    scienceCost = KRnD.calculateScienceCost(scaledCost, rndModule.dryMass_costScale, nextUpgrade.dryMass);
                }
                else if (selectedUpgradeOption == "Torque")
                {
                    upgradeFunction     = KRnDGUI.UpgradeTorque;
                    currentUpgradeCount = currentUpgrade.torque;
                    nextUpgradeCount    = ++nextUpgrade.torque;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.torque_improvement, rndModule.torque_improvementScale, currentUpgrade.torque);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.torque_improvement, rndModule.torque_improvementScale, nextUpgrade.torque);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.torque_scienceCost, rndModule.torque_costScale, nextUpgrade.torque);
                }
                else if (selectedUpgradeOption == "Charge Rate")
                {
                    upgradeFunction     = KRnDGUI.UpgradeChargeRate;
                    currentUpgradeCount = currentUpgrade.chargeRate;
                    nextUpgradeCount    = ++nextUpgrade.chargeRate;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.chargeRate_improvement, rndModule.chargeRate_improvementScale, currentUpgrade.chargeRate);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.chargeRate_improvement, rndModule.chargeRate_improvementScale, nextUpgrade.chargeRate);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.chargeRate_scienceCost, rndModule.chargeRate_costScale, nextUpgrade.chargeRate);
                }
                else if (selectedUpgradeOption == "Crash Tolerance")
                {
                    upgradeFunction     = KRnDGUI.UpgradeCrashTolerance;
                    currentUpgradeCount = currentUpgrade.crashTolerance;
                    nextUpgradeCount    = ++nextUpgrade.crashTolerance;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.crashTolerance_improvement, rndModule.crashTolerance_improvementScale, currentUpgrade.crashTolerance);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.crashTolerance_improvement, rndModule.crashTolerance_improvementScale, nextUpgrade.crashTolerance);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.crashTolerance_scienceCost, rndModule.crashTolerance_costScale, nextUpgrade.crashTolerance);
                }
                else if (selectedUpgradeOption == "Battery")
                {
                    upgradeFunction     = KRnDGUI.UpgradeBatteryCharge;
                    currentUpgradeCount = currentUpgrade.batteryCharge;
                    nextUpgradeCount    = ++nextUpgrade.batteryCharge;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.batteryCharge_improvement, rndModule.batteryCharge_improvementScale, currentUpgrade.batteryCharge);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.batteryCharge_improvement, rndModule.batteryCharge_improvementScale, nextUpgrade.batteryCharge);

                    // Scale science cost with original battery charge:
                    PartStats originalStats;
                    if (!KRnD.originalStats.TryGetValue(part.name, out originalStats))
                    {
                        throw new Exception("no origional-stats for part '" + part.name + "'");
                    }
                    double scaleReferenceFactor = 1;
                    if (rndModule.batteryCharge_costScaleReference > 0)
                    {
                        scaleReferenceFactor = originalStats.batteryCharge / rndModule.batteryCharge_costScaleReference;
                    }
                    int scaledCost = (int)Math.Round(rndModule.batteryCharge_scienceCost * scaleReferenceFactor);
                    if (scaledCost < 1)
                    {
                        scaledCost = 1;
                    }
                    scienceCost = KRnD.calculateScienceCost(scaledCost, rndModule.batteryCharge_costScale, nextUpgrade.batteryCharge);
                }
                else if (selectedUpgradeOption == "Fuel Pressure")
                {
                    upgradeFunction     = KRnDGUI.UpgradeFuelCapacity;
                    currentUpgradeCount = currentUpgrade.fuelCapacity;
                    nextUpgradeCount    = ++nextUpgrade.fuelCapacity;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.fuelCapacity_improvement, rndModule.fuelCapacity_improvementScale, currentUpgrade.fuelCapacity);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.fuelCapacity_improvement, rndModule.fuelCapacity_improvementScale, nextUpgrade.fuelCapacity);

                    // Scale science cost with original fuel capacity:
                    PartStats originalStats;
                    if (!KRnD.originalStats.TryGetValue(part.name, out originalStats))
                    {
                        throw new Exception("no origional-stats for part '" + part.name + "'");
                    }
                    double scaleReferenceFactor = 1;
                    if (rndModule.fuelCapacity_costScaleReference > 0)
                    {
                        scaleReferenceFactor = originalStats.fuelCapacitiesSum / rndModule.fuelCapacity_costScaleReference;
                    }
                    int scaledCost = (int)Math.Round(rndModule.fuelCapacity_scienceCost * scaleReferenceFactor);
                    if (scaledCost < 1)
                    {
                        scaledCost = 1;
                    }
                    scienceCost = KRnD.calculateScienceCost(scaledCost, rndModule.fuelCapacity_costScale, nextUpgrade.fuelCapacity);
                }
                else if (selectedUpgradeOption == "Generator")
                {
                    upgradeFunction     = KRnDGUI.UpgradeGeneratorEfficiency;
                    currentUpgradeCount = currentUpgrade.generatorEfficiency;
                    nextUpgradeCount    = ++nextUpgrade.generatorEfficiency;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.generatorEfficiency_improvement, rndModule.generatorEfficiency_improvementScale, currentUpgrade.generatorEfficiency);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.generatorEfficiency_improvement, rndModule.generatorEfficiency_improvementScale, nextUpgrade.generatorEfficiency);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.generatorEfficiency_scienceCost, rndModule.generatorEfficiency_costScale, nextUpgrade.generatorEfficiency);
                }
                else if (selectedUpgradeOption == "Converter")
                {
                    upgradeFunction     = KRnDGUI.UpgradeConverterEfficiency;
                    currentUpgradeCount = currentUpgrade.converterEfficiency;
                    nextUpgradeCount    = ++nextUpgrade.converterEfficiency;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.converterEfficiency_improvement, rndModule.converterEfficiency_improvementScale, currentUpgrade.converterEfficiency);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.converterEfficiency_improvement, rndModule.converterEfficiency_improvementScale, nextUpgrade.converterEfficiency);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.converterEfficiency_scienceCost, rndModule.converterEfficiency_costScale, nextUpgrade.converterEfficiency);
                }
                else if (selectedUpgradeOption == "Parachute")
                {
                    upgradeFunction     = KRnDGUI.UpgradeParachuteStrength;
                    currentUpgradeCount = currentUpgrade.parachuteStrength;
                    nextUpgradeCount    = ++nextUpgrade.parachuteStrength;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.parachuteStrength_improvement, rndModule.parachuteStrength_improvementScale, currentUpgrade.parachuteStrength);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.parachuteStrength_improvement, rndModule.parachuteStrength_improvementScale, nextUpgrade.parachuteStrength);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.parachuteStrength_scienceCost, rndModule.parachuteStrength_costScale, nextUpgrade.parachuteStrength);
                }
                else if (selectedUpgradeOption == "Max Temp")
                {
                    upgradeFunction     = KRnDGUI.UpgradeMaxTemperature;
                    currentUpgradeCount = currentUpgrade.maxTemperature;
                    nextUpgradeCount    = ++nextUpgrade.maxTemperature;
                    currentImprovement  = KRnD.calculateImprovementFactor(rndModule.maxTemperature_improvement, rndModule.maxTemperature_improvementScale, currentUpgrade.maxTemperature);
                    nextImprovement     = KRnD.calculateImprovementFactor(rndModule.maxTemperature_improvement, rndModule.maxTemperature_improvementScale, nextUpgrade.maxTemperature);
                    scienceCost         = KRnD.calculateScienceCost(rndModule.maxTemperature_scienceCost, rndModule.maxTemperature_costScale, nextUpgrade.maxTemperature);
                }
                else
                {
                    throw new Exception("unexpected option '" + selectedUpgradeOption + "'");
                }
                String newInfo = getPartInfo(part, nextUpgrade); // Calculate part-info if the selected stat was upgraded.
                newInfo = highlightChanges(currentInfo, newInfo);

                // Current stats:
                GUILayout.BeginArea(new Rect(10 + optionsWidth + 10, 30, windowStyle.fixedWidth, 20));
                GUILayout.Label("<color=#FFFFFF><b>Current:</b> " + currentUpgradeCount.ToString() + " (" + currentImprovement.ToString("+0.##%;-0.##%;-") + ")</color>", labelStyle);
                GUILayout.EndArea();

                float areaWidth  = (windowStyle.fixedWidth - 20 - optionsWidth) / 2;
                float areaHeight = optionsHeight;
                GUILayout.BeginArea(new Rect(10 + optionsWidth, 30 + 20, areaWidth, areaHeight));
                scrollPos = GUILayout.BeginScrollView(scrollPos, scrollStyle, GUILayout.Width(areaWidth), GUILayout.Height(areaHeight));

                GUILayout.Label(currentInfo, labelStyleSmall);
                GUILayout.EndScrollView();
                GUILayout.EndArea();

                // Next stats:
                GUILayout.BeginArea(new Rect(10 + optionsWidth + areaWidth + 10, 30, windowStyle.fixedWidth, 20));
                GUILayout.Label("<color=#FFFFFF><b>Next upgrade:</b> " + nextUpgradeCount.ToString() + " (" + nextImprovement.ToString("+0.##%;-0.##%;-") + ")</color>", labelStyle);
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(10 + optionsWidth + areaWidth, 30 + 20, areaWidth, areaHeight));
                scrollPos = GUILayout.BeginScrollView(scrollPos, scrollStyle, GUILayout.Width(areaWidth), GUILayout.Height(areaHeight));
                GUILayout.Label(newInfo, labelStyleSmall);
                GUILayout.EndScrollView();
                GUILayout.EndArea();

                // Bottom-line (display only if the upgrade would have an effect):
                if (currentImprovement != nextImprovement)
                {
                    GUILayout.BeginArea(new Rect(10, windowStyle.fixedHeight - 25, windowStyle.fixedWidth, 30));
                    float currentScience = 0;
                    if (ResearchAndDevelopment.Instance != null)
                    {
                        currentScience = ResearchAndDevelopment.Instance.Science;
                    }
                    String color = "FF0000";
                    if (currentScience >= scienceCost)
                    {
                        color = "00FF00";
                    }
                    GUILayout.Label("<b>Science: <color=#" + color + ">" + scienceCost.ToString() + " / " + Math.Floor(currentScience).ToString() + "</color></b>", labelStyle);
                    GUILayout.EndArea();
                    if (currentScience >= scienceCost && ResearchAndDevelopment.Instance != null && upgradeFunction != null)
                    {
                        GUILayout.BeginArea(new Rect(windowStyle.fixedWidth - 110, windowStyle.fixedHeight - 30, 100, 30));
                        if (GUILayout.Button("Research", buttonStyle))
                        {
                            upgradeFunction(part);
                            ResearchAndDevelopment.Instance.AddScience(-scienceCost, TransactionReasons.RnDTechResearch);
                        }
                        GUILayout.EndArea();
                    }
                }

                GUILayout.EndVertical();
                GUI.DragWindow();
            }
            catch (Exception e)
            {
                Debug.LogError("[KRnD] GenerateWindow(): " + e.ToString());
            }
        }
Ejemplo n.º 19
0
        // Returns the info-text of the given part with the given upgrades to be displayed in the GUI-comparison.
        private String getPartInfo(Part part, KRnDUpgrade upgradesToApply = null)
        {
            String      info             = "";
            KRnDUpgrade originalUpgrades = null;

            try
            {
                KRnDModule rndModule = KRnD.getKRnDModule(part);
                if (rndModule == null || (originalUpgrades = rndModule.getCurrentUpgrades()) == null)
                {
                    return(info);
                }

                // Upgrade the part to get the correct info, we revert it back to its previous values in the finally block below:
                KRnD.updatePart(part, upgradesToApply);
                List <ModuleEngines>           engineModules          = KRnD.getEngineModules(part);
                ModuleRCS                      rcsModule              = KRnD.getRcsModule(part);
                ModuleReactionWheel            reactionWheelModule    = KRnD.getReactionWheelModule(part);
                ModuleDeployableSolarPanel     solarPanelModule       = KRnD.getSolarPanelModule(part);
                ModuleWheelBase                landingLegModule       = KRnD.getLandingLegModule(part);
                PartResource                   electricChargeResource = KRnD.getChargeResource(part);
                ModuleGenerator                generatorModule        = KRnD.getGeneratorModule(part);
                PartModule                     fissionGenerator       = KRnD.getFissionGeneratorModule(part);
                List <ModuleResourceConverter> converterModules       = KRnD.getConverterModules(part);
                ModuleParachute                parachuteModule        = KRnD.getParachuteModule(part);
                ModuleProceduralFairing        fairingModule          = KRnD.getFairingModule(part);
                List <PartResource>            fuelResources          = KRnD.getFuelResources(part);

                // Basic stats:
                info  = "<color=#FFFFFF><b>Dry Mass:</b> " + part.mass.ToString("0.#### t") + "\n";
                info += "<b>Max Temp.:</b> " + part.maxTemp.ToString("0.#") + "/" + part.skinMaxTemp.ToString("0.#") + " °K\n";
                if (landingLegModule != null)
                {
                    info += "<b>Crash Tolerance:</b> " + part.crashTolerance.ToString("0.#### m/s") + "\n";
                }
                if (electricChargeResource != null)
                {
                    info += "<b>Electric Charge:</b> " + electricChargeResource.maxAmount.ToString() + "\n";
                }

                // Fuels:
                if (fuelResources != null)
                {
                    foreach (PartResource fuelResource in fuelResources)
                    {
                        // Reformat resource-names like "ElectricCharge" to "Electric Charge":
                        String fuelName = fuelResource.resourceName.ToString();
                        fuelName = Regex.Replace(fuelName, @"([a-z])([A-Z])", "$1 $2");
                        info    += "<b>" + fuelName + ":</b> " + fuelResource.maxAmount.ToString() + "\n";
                    }
                }

                // Module stats:
                info += "\n";
                if (engineModules != null)
                {
                    foreach (ModuleEngines engineModule in engineModules)
                    {
                        info += "<color=#99FF00><b>Engine";
                        if (engineModules.Count > 1)
                        {
                            info += " (" + engineModule.engineID.ToString() + ")";
                        }
                        info += ":</b></color>\n" + engineModule.GetInfo();
                        if (engineModules.Count > 1)
                        {
                            info += "\n";
                        }
                    }
                }
                if (rcsModule)
                {
                    info += "<color=#99FF00><b>RCS:</b></color>\n" + rcsModule.GetInfo();
                }
                if (reactionWheelModule)
                {
                    info += "<color=#99FF00><b>Reaction Wheel:</b></color>\n" + reactionWheelModule.GetInfo();
                }
                if (solarPanelModule)
                {
                    info += "<color=#99FF00><b>Solar Panel:</b></color>\n" + KRnD.getSolarPanelInfo(solarPanelModule);
                }
                if (generatorModule)
                {
                    info += "<color=#99FF00><b>Generator:</b></color>\n" + generatorModule.GetInfo();
                }
                if (fissionGenerator)
                {
                    info += "<color=#99FF00><b>Fission-Generator:</b></color>\n" + fissionGenerator.GetInfo();
                }
                if (converterModules != null)
                {
                    foreach (ModuleResourceConverter converterModule in converterModules)
                    {
                        info += "<color=#99FF00><b>Converter " + converterModule.ConverterName + ":</b></color>\n" + converterModule.GetInfo() + "\n";
                    }
                }
                if (parachuteModule)
                {
                    info += "<color=#99FF00><b>Parachute:</b></color>\n" + parachuteModule.GetInfo();
                }
                if (fairingModule)
                {
                    info += "<color=#99FF00><b>Fairing:</b></color>\n" + fairingModule.GetInfo();
                }
                info += "</color>";
            }
            catch (Exception e)
            {
                Debug.LogError("[KRnDGUI] getPartInfo(): " + e.ToString());
            }
            finally
            {
                try
                {
                    if (originalUpgrades != null)
                    {
                        KRnD.updatePart(part, originalUpgrades);
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError("[KRnDGUI] getPartInfo() restore of part failed: " + e.ToString());
                }
            }
            return(info);
        }
Ejemplo n.º 20
0
        private void OnWindow(int window_id)
        {
            try {
                GUILayout.BeginVertical();

                // Get all modules of the selected part:
                var                            part_title               = "";
                Part                           part                     = null;
                KRnDModule                     rnd_module               = null;
                List <ModuleEngines>           engine_modules           = null;
                ModuleRCS                      rcs_module               = null;
                ModuleReactionWheel            reaction_wheel_module    = null;
                ModuleDeployableSolarPanel     solar_panel_module       = null;
                ModuleWheelBase                landing_leg_module       = null;
                PartResource                   electric_charge_resource = null;
                ModuleGenerator                generator_module         = null;
                PartModule                     fission_generator        = null;
                List <ModuleResourceConverter> converter_modules        = null;
                ModuleParachute                parachute_module         = null;
                ModuleDataTransmitter          antenna_module           = null;
                ModuleScienceLab               science_lab              = null;
                List <PartResource>            fuel_resources           = null;
                ModuleResourceHarvester        harvester_module         = null;
                ModuleActiveRadiator           radiator_module          = null;
                ELConverter                    el_converter             = null;


                if (selectedPart != null)
                {
                    foreach (var a_part in PartLoader.LoadedPartsList)
                    {
                        if (a_part.partPrefab.name == selectedPart.name)
                        {
                            part       = a_part.partPrefab;
                            part_title = a_part.title;
                            break;
                        }
                    }

                    if (part)
                    {
                        antenna_module           = PartStats.GetModuleDataTransmitter(part);
                        science_lab              = PartStats.GetModuleScienceLab(part);
                        rnd_module               = PartStats.GetKRnDModule(part);
                        engine_modules           = PartStats.GetModuleEnginesList(part);
                        rcs_module               = PartStats.GetModuleRCS(part);
                        reaction_wheel_module    = PartStats.GetModuleReactionWheel(part);
                        solar_panel_module       = PartStats.GetModuleDeployableSolarPanel(part);
                        landing_leg_module       = PartStats.GetModuleWheelBase(part);
                        electric_charge_resource = PartStats.GetElectricCharge(part);
                        generator_module         = PartStats.GetModuleGenerator(part);
                        fission_generator        = PartStats.GetFissionGenerator(part);
                        converter_modules        = PartStats.GetModuleResourceConverterList(part);
                        parachute_module         = PartStats.GetModuleParachute(part);
                        fuel_resources           = PartStats.GetFuelResources(part);
                        harvester_module         = PartStats.GetModuleResourceHarvester(part);
                        radiator_module          = PartStats.GetModuleActiveRadiator(part);
                        el_converter             = PartStats.GetModuleElConverter(part);
                    }
                }

                if (!part)
                {
                    // No part selected:
                    GUILayout.BeginArea(new Rect(10, 5, _windowStyle.fixedWidth, 20));
                    GUILayout.Label("<b>Kerbal R&D: Select a part to improve</b>", _labelStyle);
                    GUILayout.EndArea();
                    GUILayout.EndVertical();
                    GUI.DragWindow();
                    return;
                }

                if (!rnd_module)
                {
                    // Invalid part selected:
                    GUILayout.BeginArea(new Rect(10, 5, _windowStyle.fixedWidth, 20));
                    GUILayout.Label("<b>Kerbal R&D: Select a different part to improve</b>", _labelStyle);
                    GUILayout.EndArea();
                    GUILayout.EndVertical();
                    GUI.DragWindow();
                    return;
                }

                // Get stats of the current version of the selected part:
                if (!KRnD.upgrades.TryGetValue(part.name, out var current_upgrade))
                {
                    current_upgrade = new PartUpgrades();
                }
                var current_info = BuildPartInfoString(part, current_upgrade);

                // Create a copy of the part-stats which we can use to mock an upgrade further below:
                var next_upgrade = current_upgrade.Clone();

                // Title:
                GUILayout.BeginArea(new Rect(10, 5, _windowStyle.fixedWidth, 20));
                var version = rnd_module.GetVersion();
                if (version != "")
                {
                    version = " - " + version;
                }
                GUILayout.Label("<b>" + part_title + version + "</b>", _labelStyle);
                GUILayout.EndArea();

                // List with upgrade-options:
                float options_width  = 100;
                var   options_height = _windowStyle.fixedHeight - 30 - 30 - 20;
                GUILayout.BeginArea(new Rect(10, 30 + 20, options_width, options_height));


                GUILayout.BeginVertical();

                var options = new List <string> {
                    "Dry Mass", "Max Temp"
                };
                if (engine_modules != null || rcs_module)
                {
                    options.Add("ISP Vac");
                    options.Add("ISP Atm");
                    options.Add("Fuel Flow");
                }

                if (antenna_module != null)
                {
                    options.Add("Antenna Power");
                }
                if (antenna_module != null && antenna_module.antennaType != AntennaType.INTERNAL)
                {
                    options.Add("Packet Size");
                }
                if (science_lab != null)
                {
                    options.Add("Data Storage");
                }

                if (reaction_wheel_module != null)
                {
                    options.Add("Torque");
                }
                if (solar_panel_module != null)
                {
                    options.Add("Charge Rate");
                }
                if (landing_leg_module != null)
                {
                    options.Add("Crash Tolerance");
                }
                if (electric_charge_resource != null)
                {
                    options.Add("Battery");
                }
                //if (fuel_resources != null) options.Add("Fuel Pressure");
                if (generator_module || fission_generator)
                {
                    options.Add("Generator");
                }
                if (converter_modules != null)
                {
                    options.Add("Converter");
                }
                if (parachute_module)
                {
                    options.Add("Parachute");
                }
                if (harvester_module)
                {
                    options.Add("Harvester");
                }
                if (radiator_module)
                {
                    options.Add("Radiator");
                }
                if (el_converter)
                {
                    options.Add("EL Converter");
                }

                if (_selectedUpgradeOption >= options.Count)
                {
                    _selectedUpgradeOption = 0;
                }
                _selectedUpgradeOption = GUILayout.SelectionGrid(_selectedUpgradeOption, options.ToArray(), 1, _buttonStyle);

                GUILayout.EndVertical();

                GUILayout.EndArea();

                var              selected_upgrade_option = options.ToArray()[_selectedUpgradeOption];
                int              current_upgrade_level;
                int              next_upgrade_level;
                int              science_cost;
                float            current_improvement_factor;
                float            next_improvement_factor;
                UpgradeConstants u_constants;

                if (!KRnD.originalStats.TryGetValue(part.name, out var original_stats))
                {
                    throw new Exception("no original-stats for part '" + part.name + "'");
                }

                //Func<PartUpgrades, int> improve_function;
                if (selected_upgrade_option == "ISP Vac")
                {
                    //improve_function = KRnD.ImproveIspVac;
                    current_upgrade_level      = current_upgrade.ispVac;
                    next_upgrade_level         = ++next_upgrade.ispVac;
                    u_constants                = ValueConstants.GetData(StringConstants.ISP_VAC);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.ispVac);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.ispVac);
                    science_cost               = u_constants.CalculateScienceCost(0, next_upgrade.ispVac);
                }
                else if (selected_upgrade_option == "ISP Atm")
                {
                    //improve_function = KRnD.ImproveIspAtm;
                    current_upgrade_level      = current_upgrade.ispAtm;
                    next_upgrade_level         = ++next_upgrade.ispAtm;
                    u_constants                = ValueConstants.GetData(StringConstants.ISP_ATM);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.ispAtm);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.ispAtm);
                    science_cost               = u_constants.CalculateScienceCost(0, next_upgrade.ispAtm);
                }
                else if (selected_upgrade_option == "Fuel Flow")
                {
                    //improve_function = KRnD.ImproveFuelFlow;
                    current_upgrade_level      = current_upgrade.fuelFlow;
                    next_upgrade_level         = ++next_upgrade.fuelFlow;
                    u_constants                = ValueConstants.GetData(StringConstants.FUEL_FLOW);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.fuelFlow);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.fuelFlow);
                    science_cost               = u_constants.CalculateScienceCost(0, next_upgrade.fuelFlow);
                }
                else if (selected_upgrade_option == "Dry Mass")
                {
                    //improve_function = KRnD.ImproveDryMass;
                    current_upgrade_level      = current_upgrade.dryMass;
                    next_upgrade_level         = ++next_upgrade.dryMass;
                    u_constants                = ValueConstants.GetData(StringConstants.DRY_MASS);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.dryMass);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.dryMass);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.dryMass, next_upgrade.dryMass);
                }
                else if (selected_upgrade_option == "Torque")
                {
                    //improve_function = KRnD.ImproveTorque;
                    current_upgrade_level      = current_upgrade.torqueStrength;
                    next_upgrade_level         = ++next_upgrade.torqueStrength;
                    u_constants                = ValueConstants.GetData(StringConstants.TORQUE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.torqueStrength);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.torqueStrength);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.torqueStrength, next_upgrade.torqueStrength);
                }
                else if (selected_upgrade_option == "Antenna Power")
                {
                    //improve_function = KRnD.ImproveAntennaPower;
                    current_upgrade_level      = current_upgrade.antennaPower;
                    next_upgrade_level         = ++next_upgrade.antennaPower;
                    u_constants                = ValueConstants.GetData(StringConstants.ANTENNA_POWER);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.antennaPower);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.antennaPower);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.antennaPower, next_upgrade.antennaPower);
                }
                else if (selected_upgrade_option == "Packet Size")
                {
                    //improve_function = KRnD.ImprovePacketSize;
                    current_upgrade_level      = current_upgrade.packetSize;
                    next_upgrade_level         = ++next_upgrade.packetSize;
                    u_constants                = ValueConstants.GetData(StringConstants.PACKET_SIZE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.packetSize);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.packetSize);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.packetSize, next_upgrade.packetSize);
                }
                else if (selected_upgrade_option == "Data Storage")
                {
                    //improve_function = KRnD.ImproveDataStorage;
                    current_upgrade_level      = current_upgrade.dataStorage;
                    next_upgrade_level         = ++next_upgrade.dataStorage;
                    u_constants                = ValueConstants.GetData(StringConstants.DATA_STORAGE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.dataStorage);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.dataStorage);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.dataStorage, next_upgrade.dataStorage);
                }
                else if (selected_upgrade_option == "Harvester")
                {
                    //improve_function = KRnD.ImproveResourceHarvester;
                    current_upgrade_level      = current_upgrade.resourceHarvester;
                    next_upgrade_level         = ++next_upgrade.resourceHarvester;
                    u_constants                = ValueConstants.GetData(StringConstants.RESOURCE_HARVESTER);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.resourceHarvester);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.resourceHarvester);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.resourceHarvester, next_upgrade.resourceHarvester);
                }
                else if (selected_upgrade_option == "Radiator")
                {
                    //improve_function = KRnD.ImproveActiveRadiator;
                    current_upgrade_level      = current_upgrade.maxEnergyTransfer;
                    next_upgrade_level         = ++next_upgrade.maxEnergyTransfer;
                    u_constants                = ValueConstants.GetData(StringConstants.ENERGY_TRANSFER);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.maxEnergyTransfer);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.maxEnergyTransfer);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.maxEnergyTransfer, next_upgrade.maxEnergyTransfer);
                }
                else if (selected_upgrade_option == "Charge Rate")
                {
                    //improve_function = KRnD.ImproveChargeRate;
                    current_upgrade_level      = current_upgrade.efficiencyMult;
                    next_upgrade_level         = ++next_upgrade.efficiencyMult;
                    u_constants                = ValueConstants.GetData(StringConstants.CHARGE_RATE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.efficiencyMult);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.efficiencyMult);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.efficiencyMult, next_upgrade.efficiencyMult);
                }
                else if (selected_upgrade_option == "Crash Tolerance")
                {
                    //improve_function = KRnD.ImproveCrashTolerance;
                    current_upgrade_level      = current_upgrade.crashTolerance;
                    next_upgrade_level         = ++next_upgrade.crashTolerance;
                    u_constants                = ValueConstants.GetData(StringConstants.CRASH_TOLERANCE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.crashTolerance);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.crashTolerance);
                    science_cost               = u_constants.CalculateScienceCost(original_stats.crashTolerance, next_upgrade.crashTolerance);
                }
                else if (selected_upgrade_option == "Battery")
                {
                    //improve_function = KRnD.ImproveBatteryCharge;
                    current_upgrade_level      = current_upgrade.batteryCharge;
                    next_upgrade_level         = ++next_upgrade.batteryCharge;
                    u_constants                = ValueConstants.GetData(StringConstants.BATTERY_CHARGE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.batteryCharge);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.batteryCharge);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.batteryCharge, next_upgrade.batteryCharge);
                }
                else if (selected_upgrade_option == "Fuel Pressure")
                {
                    //improve_function = KRnD.ImproveFuelCapacity;
                    current_upgrade_level      = current_upgrade.fuelCapacity;
                    next_upgrade_level         = ++next_upgrade.fuelCapacity;
                    u_constants                = ValueConstants.GetData(StringConstants.FUEL_CAPACITY);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.fuelCapacity);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.fuelCapacity);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.fuelCapacitiesSum, next_upgrade.fuelCapacity);
                }
                else if (selected_upgrade_option == "Generator")
                {
                    //improve_function = KRnD.ImproveGeneratorEfficiency;
                    current_upgrade_level      = current_upgrade.generatorEfficiency;
                    next_upgrade_level         = ++next_upgrade.generatorEfficiency;
                    u_constants                = ValueConstants.GetData(StringConstants.GENERATOR_EFFICIENCY);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.generatorEfficiency);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.generatorEfficiency);
                    science_cost               = u_constants.CalculateScienceCost(0, next_upgrade.generatorEfficiency);
                }
                else if (selected_upgrade_option == "Converter")
                {
                    //improve_function = KRnD.ImproveConverterEfficiency;
                    current_upgrade_level      = current_upgrade.converterEfficiency;
                    next_upgrade_level         = ++next_upgrade.converterEfficiency;
                    u_constants                = ValueConstants.GetData(StringConstants.CONVERTER_EFFICIENCY);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.converterEfficiency);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.converterEfficiency);
                    science_cost               = u_constants.CalculateScienceCost(0, next_upgrade.converterEfficiency);
                }
                else if (selected_upgrade_option == "Parachute")
                {
                    //improve_function = KRnD.ImproveParachuteStrength;
                    current_upgrade_level      = current_upgrade.parachuteStrength;
                    next_upgrade_level         = ++next_upgrade.parachuteStrength;
                    u_constants                = ValueConstants.GetData(StringConstants.PARACHUTE_STRENGTH);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.parachuteStrength);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.parachuteStrength);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.chuteMaxTemp, next_upgrade.parachuteStrength);
                }
                else if (selected_upgrade_option == "Max Temp")
                {
                    //improve_function = KRnD.ImproveMaxTemperature;
                    current_upgrade_level      = current_upgrade.maxTemperature;
                    next_upgrade_level         = ++next_upgrade.maxTemperature;
                    u_constants                = ValueConstants.GetData(StringConstants.MAX_TEMPERATURE);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.maxTemperature);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.maxTemperature);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.intMaxTemp, next_upgrade.maxTemperature);
                }
                else if (selected_upgrade_option == "EL Converter")
                {
                    //improve_function = KRnD.ImproveMaxTemperature;
                    current_upgrade_level      = current_upgrade.elConverter;
                    next_upgrade_level         = ++next_upgrade.elConverter;
                    u_constants                = ValueConstants.GetData(StringConstants.EL_CONVERTER);
                    current_improvement_factor = u_constants.CalculateImprovementFactor(current_upgrade.elConverter);
                    next_improvement_factor    = u_constants.CalculateImprovementFactor(next_upgrade.elConverter);
                    science_cost               = u_constants.CalculateScienceCost((float)original_stats.ELConverter, next_upgrade.elConverter);
                }
                else
                {
                    throw new Exception("unexpected option '" + selected_upgrade_option + "'");
                }

                var new_info = BuildPartInfoString(part, next_upgrade);                 // Calculate part-info if the selected stat was upgraded.
                new_info = HighlightChanges(current_info, new_info);

                // Current stats:
                GUILayout.BeginArea(new Rect(10 + options_width + 10, 30, _windowStyle.fixedWidth, 20));
                GUILayout.Label("<color=#FFFFFF><b>Current:</b> " + current_upgrade_level + " (" + current_improvement_factor.ToString("+0.##%;-0.##%;-") + ")</color>", _labelStyle);
                GUILayout.EndArea();

                var area_width  = (_windowStyle.fixedWidth - 20 - options_width) / 2;
                var area_height = options_height;
                GUILayout.BeginArea(new Rect(10 + options_width, 30 + 20, area_width, area_height));
                _scrollPos = GUILayout.BeginScrollView(_scrollPos, _scrollStyle, GUILayout.Width(area_width), GUILayout.Height(area_height));

                GUILayout.Label(current_info, _labelStyleSmall);
                GUILayout.EndScrollView();
                GUILayout.EndArea();

                // Next stats:
                GUILayout.BeginArea(new Rect(10 + options_width + area_width + 10, 30, _windowStyle.fixedWidth, 20));
                GUILayout.Label("<color=#FFFFFF><b>Next upgrade:</b> " + next_upgrade_level + " (" + next_improvement_factor.ToString("+0.##%;-0.##%;-") + ")</color>", _labelStyle);
                GUILayout.EndArea();

                GUILayout.BeginArea(new Rect(10 + options_width + area_width, 30 + 20, area_width, area_height));
                _scrollPos = GUILayout.BeginScrollView(_scrollPos, _scrollStyle, GUILayout.Width(area_width), GUILayout.Height(area_height));
                GUILayout.Label(new_info, _labelStyleSmall);
                GUILayout.EndScrollView();
                GUILayout.EndArea();

                // Bottom-line (display only if the upgrade would have an effect):
                if (Math.Abs(current_improvement_factor - next_improvement_factor) > float.Epsilon)
                {
                    GUILayout.BeginArea(new Rect(10, _windowStyle.fixedHeight - 25, _windowStyle.fixedWidth, 30));
                    float current_science = 0;
                    if (ResearchAndDevelopment.Instance != null)
                    {
                        current_science = ResearchAndDevelopment.Instance.Science;
                    }
                    var color = "FF0000";
                    if (current_science >= science_cost)
                    {
                        color = "00FF00";
                    }
                    GUILayout.Label("<b>Science: <color=#" + color + ">" + science_cost + " / " + Math.Floor(current_science) + "</color></b>", _labelStyle);
                    GUILayout.EndArea();
                    if (current_science >= science_cost && ResearchAndDevelopment.Instance != null && u_constants != null /*&& improve_function != null*/)
                    {
                        GUILayout.BeginArea(new Rect(_windowStyle.fixedWidth - 110, _windowStyle.fixedHeight - 30, 100, 30));
                        if (GUILayout.Button("Research", _buttonStyle))
                        {
                            //upgrade_function(part);
                            try {
                                if (!KRnD.upgrades.TryGetValue(part.name, out var store))
                                {
                                    store = new PartUpgrades();
                                    KRnD.upgrades.Add(part.name, store);
                                }

                                u_constants.upgradeFunction(store);
                                //improve_function(store);
                                KRnD.UpdateGlobalParts();
                                KRnD.UpdateEditorVessel();
                            } catch (Exception e) {
                                Debug.LogError("[KRnD] UpgradeIspVac(): " + e);
                            }



                            ResearchAndDevelopment.Instance.AddScience(-science_cost, TransactionReasons.RnDTechResearch);
                        }

                        GUILayout.EndArea();
                    }
                }

                GUILayout.EndVertical();
                GUI.DragWindow();
            } catch (Exception e) {
                Debug.LogError("[KRnD] GenerateWindow(): " + e);
            }
        }
        // cargo = C - needs cargo bay
        // spaceplane = SP - needs rockets and wings & landing gear
        // aircraft = A - wings, landing gear and launched from the SPH/runway
        // Disposable_Drone = DD - unmanned, no chutes
        // Reusable_Drone = RD - unmanned, chutes
        // Crew_Transfer = CT - non-command crew capacity
        // Tanker = T - part has resources other than electricity and the resource is either locked or isn't a fuel resource used by any engine
        // Station = S - no engines
        // Tug = Tg -
        // Compound_Vehicle = CV
        // Rover = Rv - needs wheels, not landing gear
        static public string  getVesselType(PartModule pm2, int stage, KeyValuePair <string, PDPN.Tuple <string, NameValueCollection, bool> > t)
        {
            List <string> enginepropellents = getPropellentsInEngines(pm2, stage, t);
            string        vesseltypeabbr    = "";
            bool          cargo             = false;
            bool          wings             = false;
            bool          chutes            = false;
            bool          manned            = false;
            bool          nonCommandCrew    = false;
            bool          tanker            = false;
            bool          station           = true;
            bool          landingGear       = false;
            bool          wheels            = false;
            bool          engines           = false;

            //List<Part> pl = Utils.getPartList(pm2);
            //for (int i = pl.Count - 1; i >= 0; --i)
            //{
            //    Part part = pl[i];

            foreach (Part part in Utils.getPartList(pm2))
            {
                //Log.Info ("Contains: Part: " + part.partName + " name: " + part.name + "   Stage: " + part.inverseStage.ToString () + "  currentStage: " + stage.ToString ());
                cargo          = cargo || part.Modules.Contains <ModuleCargoBay> ();
                wings          = wings || part.Modules.Contains <ModuleLiftingSurface> ();
                chutes         = chutes || part.Modules.Contains <ModuleParachute> ();
                engines        = engines || part.Modules.Contains <ModuleEngines> ();
                station        = station & !engines;
                nonCommandCrew = (part.CrewCapacity > 0 && !part.Modules.Contains <ModuleCommand> ());

                //	Log.Info (part.partName + " contains " + part.Resources.Count.ToString () + " resources");
                foreach (PartResource pr in part.Resources)
                {
                    if (pr.resourceName != "ElectricCharge" && pr.resourceName != "MonoPropellant")
                    {
                        tanker = tanker || (!enginepropellents.Contains(pr.resourceName) || pr.flowState == false);
                    }
                }

                if (part.Modules.Contains <ModuleWheelBase> ())
                {
                    foreach (PartModule pm in part.Modules)
                    {
                        if (pm.moduleName == "ModuleWheelBase")
                        {
                            ModuleWheelBase mwb = pm as ModuleWheelBase;
                            landingGear = landingGear || (mwb.wheelType == WheelType.MOTORIZED);
                            wheels      = wheels || (mwb.wheelType == WheelType.MOTORIZED);
                        }
                    }
                }
            }
            manned = (Utils.getCurrentVessel(pm2).GetCrewCount() > 0);
            if (!chutes && !manned)
            {
                vesseltypeabbr += "DD:";
            }
            if (chutes && !manned)
            {
                vesseltypeabbr += "RD:";
            }
            if (nonCommandCrew)
            {
                vesseltypeabbr += "CT";
            }
            if (tanker)
            {
                vesseltypeabbr += "T";
            }
            if (station)
            {
                vesseltypeabbr += "S";
            }
            if (wheels)
            {
                vesseltypeabbr += "RV";
            }
            if (landingGear && wings && engines)
            {
                vesseltypeabbr += "SP";
            }
            if (vesseltypeabbr == "" && manned)
            {
                vesseltypeabbr = "M";
            }

            return(vesseltypeabbr);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Test stock wheels implementing standard module ModuleWheelBase
        /// </summary>
        /// <returns></returns>
        private WheelTestResult CheckStockWheels()
        {
            double powerRequired  = 0;
            double maxSpeedSum    = 0;
            int    inTheAir       = 0;
            int    operable       = 0;
            int    damaged        = 0;
            int    online         = 0;
            float  maxWheelRadius = 0;

            // Get wheel modules
            List <Part> wheels = new List <Part>();

            for (int i = 0; i < vessel.parts.Count; i++)
            {
                var part = vessel.parts[i];
                if (part.Modules.Contains("ModuleWheelBase"))
                {
                    wheels.Add(part);
                }
            }

            for (int i = 0; i < wheels.Count; i++)
            {
                ModuleWheelBase wheelBase = wheels[i].FindModuleImplementing <ModuleWheelBase>();

                // Skip legs
                if (wheelBase.wheelType == WheelType.LEG)
                {
                    continue;
                }

                // Save max wheel radius for height compensations
                if (wheelBase.radius < maxWheelRadius)
                {
                    maxWheelRadius = wheelBase.radius;
                }

                // Check damaged wheels
                ModuleWheels.ModuleWheelDamage wheelDamage = wheels[i].FindModuleImplementing <ModuleWheels.ModuleWheelDamage>();
                if (wheelDamage != null)
                {
                    if (wheelDamage.isDamaged)
                    {
                        damaged++;
                        continue;
                    }
                }

                // Whether or not wheel is touching the ground
                if (!wheelBase.isGrounded)
                {
                    inTheAir++;
                    continue;
                }
                else
                {
                    operable++;
                }

                // Check motorized wheels
                ModuleWheels.ModuleWheelMotor wheelMotor = wheels[i].FindModuleImplementing <ModuleWheels.ModuleWheelMotor>();
                if (wheelMotor != null)
                {
                    // Wheel is on
                    if (wheelMotor.motorEnabled)
                    {
                        powerRequired += wheelMotor.avgResRate;
                        online++;
                        double maxWheelSpeed = 0;

                        // RoveMax M1 and RoveMax M1-F (Making History expansion) don't have max wheels speed defined, so we just set it to something sensible
                        if ((wheelMotor.part.name == "roverWheel1") || (wheelMotor.part.name == "roverWheelM1-F "))
                        {
                            maxWheelSpeed = 42;
                        }
                        else
                        {
                            maxWheelSpeed = wheelMotor.wheelSpeedMax;
                        }
                        maxSpeedSum += maxWheelSpeed;
                    }
                }
            }

            return(new WheelTestResult(powerRequired, maxSpeedSum, inTheAir, operable, damaged, online, maxWheelRadius));
        }
Ejemplo n.º 23
0
        public PartStats(Part part)
        {
            this.mass = part.mass;

            if (part.partInfo.variant != null)
            {
                kRnDVariants       = KRnD.getVariants(part);
                currentVariant     = part.partInfo.variant.Name;
                currentVariantMass = part.partInfo.variant.Mass;
                variantBaseMass    = part.baseVariant.Mass;
            }
            if (kRnDVariants != null)
            {
                hasVariants = true;
            }
            else
            {
                currentVariantMass = 0;
                variantBaseMass    = 0;
                hasVariants        = false;
            }
            this.skinMaxTemp = part.skinMaxTemp;
            this.intMaxTemp  = part.maxTemp;

            // There should only be one or the other, engines or RCS:
            List <ModuleEngines> engineModules = KRnD.getEngineModules(part);
            ModuleRCS            rcsModule     = KRnD.getRcsModule(part);

            if (engineModules != null)
            {
                this.maxFuelFlows     = new List <float>();
                this.atmosphereCurves = new List <FloatCurve>();

                for (int i = 0; i < engineModules.Count; i++)
                {
                    ModuleEngines engineModule = engineModules[i];

                    this.maxFuelFlows.Add(engineModule.maxFuelFlow);

                    FloatCurve atmosphereCurve = new FloatCurve();
                    for (int i5 = 0; i5 < engineModule.atmosphereCurve.Curve.length; i5++)
                    {
                        Keyframe frame = engineModule.atmosphereCurve.Curve[i5];
                        atmosphereCurve.Add(frame.time, frame.value);
                    }
                    this.atmosphereCurves.Add(atmosphereCurve);
                }
            }
            else if (rcsModule)
            {
                this.maxFuelFlows     = new List <float>();
                this.atmosphereCurves = new List <FloatCurve>();

                this.maxFuelFlows.Add(rcsModule.thrusterPower);
                FloatCurve atmosphereCurve = new FloatCurve();
                for (int i = 0; i < rcsModule.atmosphereCurve.Curve.length; i++)
                {
                    Keyframe frame = rcsModule.atmosphereCurve.Curve[i];
                    atmosphereCurve.Add(frame.time, frame.value);
                }
                this.atmosphereCurves.Add(atmosphereCurve);
            }

            ModuleReactionWheel reactionWheel = KRnD.getReactionWheelModule(part);

            if (reactionWheel)
            {
                this.torque = reactionWheel.RollTorque; // There is also pitch- and yaw-torque, but they should all be the same
            }

            // WIP
            //ModuleDataTransmitter dataTransmitter = KRnD.getDataTransmitterModule(part);
            //if (dataTransmitter)
            //{
            //    this.antPower = dataTransmitter.antennaPower;
            //}

            ModuleResourceHarvester resourceHarvester = KRnD.getResourceHarvesterModule(part);

            if (resourceHarvester)
            {
                this.harvester = resourceHarvester.Efficiency;
            }

            ModuleActiveRadiator activeRadiator = KRnD.getActiveRadiatorModule(part);

            if (activeRadiator)
            {
                this.radiatorEfficiency = activeRadiator.maxEnergyTransfer;
            }

            ModuleDeployableSolarPanel solarPanel = KRnD.getSolarPanelModule(part);

            if (solarPanel)
            {
                this.chargeRate = solarPanel.chargeRate;
            }

            ModuleWheelBase landingLeg = KRnD.getLandingLegModule(part);

            if (landingLeg)
            {
                this.crashTolerance = part.crashTolerance; // Every part has a crash tolerance, but we only want to improve landing legs.
            }

            PartResource electricCharge = KRnD.getChargeResource(part);

            if (electricCharge != null)
            {
                this.batteryCharge = electricCharge.maxAmount;
            }

            ModuleGenerator generator = KRnD.getGeneratorModule(part);

            if (generator != null)
            {
                generatorEfficiency = new Dictionary <String, double>();
                for (int i = 0; i < generator.resHandler.outputResources.Count; i++)
                {
                    ModuleResource outputResource = generator.resHandler.outputResources[i];

                    generatorEfficiency.Add(outputResource.name, outputResource.rate);
                }
            }

            PartModule fissionGenerator = KRnD.getFissionGeneratorModule(part);

            if (fissionGenerator != null)
            {
                fissionPowerGeneration = KRnD.getGenericModuleValue(fissionGenerator, "PowerGeneration");
            }

            // There might be different converter-modules in the same part with different names (eg for Fuel, Monopropellant, etc):
            List <ModuleResourceConverter> converterList = KRnD.getConverterModules(part);

            if (converterList != null)
            {
                converterEfficiency = new Dictionary <String, Dictionary <String, double> >();
                for (int i = 0; i < converterList.Count; i++)
                {
                    ModuleResourceConverter converter = converterList[i];

                    Dictionary <String, double> thisConverterEfficiency = new Dictionary <String, double>();
                    for (int i2 = 0; i2 < converter.outputList.Count; i2++)
                    {
                        ResourceRatio resourceRatio = converter.outputList[i2];

                        thisConverterEfficiency.Add(resourceRatio.ResourceName, resourceRatio.Ratio);
                    }
                    converterEfficiency.Add(converter.ConverterName, thisConverterEfficiency);
                }
            }

            ModuleParachute parachute = KRnD.getParachuteModule(part);

            if (parachute)
            {
                this.chuteMaxTemp = parachute.chuteMaxTemp;
            }

            ModuleProceduralFairing fairing = KRnD.getFairingModule(part);

            if (fairing)
            {
                this.fairingAreaMass = fairing.UnitAreaMass;
            }

            List <PartResource> fuelResources = KRnD.getFuelResources(part);

            if (fuelResources != null)
            {
                fuelCapacities    = new Dictionary <string, double>();
                fuelCapacitiesSum = 0;
                for (int i = 0; i < fuelResources.Count; i++)
                {
                    PartResource fuelResource = fuelResources[i];

                    fuelCapacities.Add(fuelResource.resourceName, fuelResource.maxAmount);
                    fuelCapacitiesSum += fuelResource.maxAmount;
                }
            }
        }