public override void OnStart(PartModule.StartState state)
        {
            if (state == StartState.Editor) { return; }

            if (telescopeInit == false || lastMaintained == 0)
            {
                telescopeInit = true;
                lastMaintained = (float)Planetarium.GetUniversalTime();
            }

            if (telescopeIsEnabled && lastActiveTime > 0)
            {
                double t0 = lastActiveTime - lastMaintained;
                double t1 = Math.Min(Planetarium.GetUniversalTime(), helium_depleted_time) - lastMaintained;
                //this isn't going to run if we are out of helium anyway, needs to be fixed to handle helium depletion, see isssue #22
                if (t1 > t0)
                {
                    double a = -GameConstants.telescopePerformanceTimescale;
                    double base_science = dpo ? GameConstants.telescopeGLensScience : GameConstants.telescopeBaseScience;
                    double avg_science_rate = base_science / a / a * (Math.Exp(a * t1) * (a * t1 - 1) - Math.Exp(a * t0) * (a * t0 - 1));
                    double time_diff = Planetarium.GetUniversalTime() - lastActiveTime;
                    double science_to_add = avg_science_rate / 86400 * time_diff;
                    lastActiveTime = (float)Planetarium.GetUniversalTime();
                    science_awaiting_addition = science_to_add;
                }
            }

            this.part.force_activate();
        }
        public override void OnStart(PartModule.StartState state)
        {
            FindDecoupler();

            if (decouple == null)
            {
                Debug.LogError("Unable to find any decoupler modules");
                isEnabled = enabled = false;
                return;
            }

            if (HighLogic.LoadedSceneIsEditor)
            {
                if (mass != 0)
                    UpdateMass(mass);

                Fields["isOmniDecoupler"].guiActiveEditor =
                    string.IsNullOrEmpty(separatorTechRequired) || ResearchAndDevelopment.GetTechnologyState(separatorTechRequired) == RDTech.State.Available;

                if (ejectionImpulse == 0)
                    ejectionImpulse = (float)Math.Round(decouple.ejectionForce * impulsePerForceUnit, 1);

                UI_FloatEdit ejectionImpulseEdit = (UI_FloatEdit)Fields["ejectionImpulse"].uiControlEditor;
                ejectionImpulseEdit.maxValue = maxImpulse;
            }
            else if (HighLogic.LoadedSceneIsFlight)
            {
                decouple.isOmniDecoupler = isOmniDecoupler;
                part.mass = mass;
            }
        }
		public override void OnStart(PartModule.StartState state) {
			String[] resources_to_supply = {FNResourceManager.FNRESOURCE_WASTEHEAT, FNResourceManager.FNRESOURCE_MEGAJOULES};
			this.resources_to_supply = resources_to_supply;
			base.OnStart (state);
			if (state == StartState.Editor) { return; }
			solarPanel = (ModuleDeployableSolarPanel)this.part.Modules["ModuleDeployableSolarPanel"];
		}
示例#4
0
    public override void OnStart(PartModule.StartState state)
    {
        base.OnStart(state);
        if (!HighLogic.LoadedSceneIsFlight)
            return;

        modeList.Add(new mode(primaryModeRange.x, primaryModeRange.y));

        engine = part.Modules.OfType<ModuleEngines>().FirstOrDefault();
        if (engine != null)
        {

        }
        else
        {
            Debug.Log("FSanimateThrottle: no engine module found");
        }

        anim = part.FindModelAnimators(animationName).FirstOrDefault();
        if (anim != null)
        {
            animTime = 0f;
            anim[animationName].layer = animationLayer;
            anim[animationName].speed = 0f;
            anim[animationName].normalizedTime = 0f;
            anim[animationName].wrapMode = WrapMode.ClampForever;
        }
        else
        {
            Debug.Log("FSanimateThrottle: no animation found called " + animationName);
        }
    }
 public override void OnStart(PartModule.StartState state)
 {
     if (state != PartModule.StartState.None && state != PartModule.StartState.Editor)
     {
         RenderingManager.AddToPostDrawQueue(1, DoMapView);
     }
 }
示例#6
0
        public override void OnStart(PartModule.StartState state)
        {
            base.OnStart(state);
            if (HighLogic.LoadedSceneIsFlight && !Equals(vessel.vesselType, VesselType.Debris) && vessel.parts.Count > 1)
            {
                GameEvents.onGamePause.Add(new EventVoid.OnEvent(this.OnPause));
                GameEvents.onGameUnpause.Add(new EventVoid.OnEvent(this.OnUnPause));
                KFMW = this.part.GetComponentInChildren<KFModuleWheel>();
                if (!Equals(KFMW, null))
                    tweakScaleCorrector = KFMW.tweakScaleCorrector;
                KFLog.Warning(string.Format("TS Corrector: {0}", tweakScaleCorrector));

                colliderList = Extensions.SplitString(colliderNames);

                for (int i = 0; i < colliderList.Count(); i++)
                {
                    colliders.Add(transform.SearchStartsWith(colliderList[i]).GetComponent<WheelCollider>());
                    objectCount++;
                }
                susTrav = transform.SearchStartsWith(susTravName);

                initialPosition = susTrav.localPosition;
                susTravIndex = Extensions.SetAxisIndex(susTravAxis);

                MoveSuspension(susTravIndex, -lastFrameTraverse, susTrav); //to get the initial stuff correct
                if (objectCount > 0)
                {
                    //KFLog.Error(string.Format("lastFrameTraverse {0}", lastFrameTraverse));
                    StartCoroutine("WaitAndStart");
                }
                else
                    KFLog.Error("KFSuspension not configured correctly");
            }
        }
		public override void OnStart(PartModule.StartState state) 
        {
            antimatter = part.Resources[InterstellarResourcesConfiguration.Instance.Antimatter];

            if (state == StartState.Editor) return;
            this.part.force_activate();
		}
        public override void OnStart(PartModule.StartState state)
        {
            base.OnStart(state); // sets up the animation etc.
            stateCount = heatAnimStates.Length;

            SetDefaults();
        }
        public IntegratedIntakeEngineCrossSectionAdjuster(PartModule intake, Matrix4x4 worldToVesselMatrix)
        {
            this.part = intake.part;
            intakeModule = intake as ModuleResourceIntake;
            intakeTrans = intakeModule.intakeTransform;
            //ModuleResourceIntake intake = intake;


            /*vehicleBasisForwardVector = Vector3.forward;//intakeTrans.forward;

            foreach(AttachNode node in part.attachNodes)
                if(node.nodeType == AttachNode.NodeType.Stack && Vector3.Dot(node.position, (part.transform.worldToLocalMatrix * intakeTrans.localToWorldMatrix).MultiplyVector(Vector3.forward)) > 0)
                {
                    frontNode = node;
                    break;
                }*/

            thisToVesselMatrix = worldToVesselMatrix * intakeTrans.localToWorldMatrix;

            vehicleBasisForwardVector = Vector3.forward;
            vehicleBasisForwardVector = thisToVesselMatrix.MultiplyVector(vehicleBasisForwardVector);

            Type intakeType = intake.GetType();
            intakeArea = (float)intakeType.GetField("Area").GetValue(intake);
        }
        public static KISInventoryModuleWrapper FromComponent(PartModule component)
        {
            if (component != null)
                return new KISInventoryModuleWrapper(component);

            return null;
        }
        public override void OnStart(PartModule.StartState state)
        {
            if (CloseAnimationName != "")
            {

                openAnim = true;
            }
            if (LoopAnimationName != "")
            {
                loopAnim = true;
            }
            if (HighLogic.LoadedSceneIsFlight)
            {
                intake = gameObject.GetComponent<ModuleResourceIntake>();
                if (intake == null)
                {
                    Utils.LogError("AnimatedIntake requires an intake module!");
                    return;
                }
                if (openAnim)
                {
                    Utils.Log("Setting up close animation");
                    openStates = Utils.SetUpAnimation(CloseAnimationName, this.part);
                }
                if (loopAnim)
                {
                    Utils.Log("Setting up loop animation");
                    loopStates = Utils.SetUpAnimation(LoopAnimationName, this.part);
                }

            }
        }
        public override void OnStart(PartModule.StartState state)
        {
            if (state == StartState.Editor) { return; }

            if (telescopeInit == false || lastMaintained == 0)
            {
                telescopeInit = true;
                lastMaintained = (float)Planetarium.GetUniversalTime();
            }

            if (telescopeIsEnabled && lastActiveTime > 0)
            {
                calculateTimeToHeliumDepletion();

                double t0 = lastActiveTime - lastMaintained;
                double t1 = Math.Min(Planetarium.GetUniversalTime(), helium_depleted_time) - lastMaintained;
                if (t1 > t0)
                {
                    double a = -GameConstants.telescopePerformanceTimescale;
                    double base_science = dpo ? GameConstants.telescopeGLensScience : GameConstants.telescopeBaseScience;
                    double time_diff = Math.Min(Planetarium.GetUniversalTime(), helium_depleted_time) - lastActiveTime;
                    double avg_science_rate = 0.5*base_science * ( Math.Exp(a * t1)  + Math.Exp(a * t0) );
                    double science_to_add = avg_science_rate / 28800 * time_diff;
                    lastActiveTime = (float)Planetarium.GetUniversalTime();
                    science_awaiting_addition += (float)science_to_add;
                }
            }
        }
 public override void OnStart(PartModule.StartState state)
 {
     base.OnStart(state);
     dish = part.FindModelTransform(dishTransform);
     if (IsDeployed)
         fullyDeployed = true;
 }
 public override void OnStart(PartModule.StartState state)
 {
     BaseTransform = this.part.transform.FindChild("model").FindChild("Kethane Small Miner").FindChild("Main Box");
     Cyl3Transform = BaseTransform.FindChild("1 Cyl");
     Cyl2Transform = Cyl3Transform.FindChild("2 Cyl");
     Cyl1Transform = Cyl2Transform.FindChild("3 Cyl");
 }
 public override void OnStart(PartModule.StartState state) {
     uranium_mononitride = part.Resources["UraniumNitride"];
     depleted_fuel = part.Resources["DepletedFuel"];
     base.OnStart(state);
     initial_thermal_power = ThermalPower;
     initial_resource_rate = resourceRate;
 }
        public override void OnStart(PartModule.StartState state) {
            deuterium = part.Resources["Deuterium"];
            he3 = part.Resources["Helium-3"];
            un = part.Resources["EnrichedUranium"];
            base.OnStart(state);
            /*
            lightGameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            lightGameObject.collider.enabled = false;
            lightGameObject.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
            lightGameObject.AddComponent<Light>();
            lightGameObject.renderer.material.shader = Shader.Find("Unlit/Transparent");
            lightGameObject.renderer.material.mainTexture = GameDatabase.Instance.GetTexture("Interstellar/explode2", false);
            lightGameObject.renderer.material.color = new Color(Color.white.r, Color.white.g, Color.white.b, 0.9f);
            lightGameObject.renderer.enabled = false;
            light = lightGameObject.light;
            lightGameObject.transform.position = part.transform.position;
            light.type = LightType.Point;
            light.color = new Color(Color.white.r, Color.white.g, 0.87f, 1f);
            light.range = 1f;
            light.intensity = 50.0f;
            light.renderMode = LightRenderMode.ForcePixel;
             
            convert_charged_to_thermal = false;
            Destroy (lightGameObject.collider, 0.25f);
            Destroy(lightGameObject, 0.1f);
            */
            antimatter_rate = resourceRate * GameConstants.antimatter_initiated_antimatter_cons_constant*86400/1000000;
            d_he3_rate = resourceRate * GameConstants.antimatter_initiated_d_he3_cons_constant*86400;
            un_rate = resourceRate * GameConstants.antimatter_initiated_eu_cons_constant*86400;
            upgraded_d_he3_rate = upgradedResourceRate * GameConstants.antimatter_initiated_upgraded_eu_cons_constant;
            upgraded_amat_rate = upgradedResourceRate * GameConstants.antimatter_initiated_antimatter_cons_constant * 86400 / 1000000;


        }
        public IntakeCrossSectionAdjuster(PartModule intake, Matrix4x4 worldToVesselMatrix)
        {
            this.part = intake.part;
            intakeModule = intake as ModuleResourceIntake;
            intakeTrans = intakeModule.intakeTransform;

            if (!string.IsNullOrEmpty(intakeModule.occludeNode))
                node = intakeModule.node; 
            
            foreach (AttachNode candidateNode in part.attachNodes)
                if (candidateNode.nodeType == AttachNode.NodeType.Stack && Vector3.Dot(candidateNode.position, (part.transform.worldToLocalMatrix * intakeTrans.localToWorldMatrix).MultiplyVector(Vector3.forward)) > 0)
                {
                    if (candidateNode == node)
                        continue;

                    nodeOffsetArea = candidateNode.size;
                    if (nodeOffsetArea == 0)
                        nodeOffsetArea = 0.5;

                    nodeOffsetArea *= 0.625;     //scale it up as needed
                    nodeOffsetArea *= nodeOffsetArea;
                    nodeOffsetArea *= Math.PI;  //calc area;

                    nodeOffsetArea *= -1;        //and the adjustment area
                    break;
                }

            thisToVesselMatrix = worldToVesselMatrix * intakeTrans.localToWorldMatrix;

            vehicleBasisForwardVector = Vector3.forward;
            vehicleBasisForwardVector = thisToVesselMatrix.MultiplyVector(vehicleBasisForwardVector);

            Type intakeType = intake.GetType();
            intakeArea = (float)intakeType.GetField("Area").GetValue(intake);
        }
 public override void OnStart(PartModule.StartState state)
 {
     SimManager.UpdateModSettings();
     SimManager.OnReady -= this.GetStageInfo;
     SimManager.OnReady += this.GetStageInfo;
     base.OnAwake();
 }
 public override void OnStart(PartModule.StartState state) {
     if (state == StartState.Editor) { return; }
     List<ModuleEnginesFX> mefxs = part.FindModulesImplementing<ModuleEnginesFX>().Where(e => e.engineID == "AirBreathing").ToList();
     List<ModuleEngines> mes = part.FindModulesImplementing<ModuleEngines>().ToList();
     rapier_engine = mefxs.FirstOrDefault();
     rapier_engine2 = mes.FirstOrDefault();
 }
 public override void OnStart(PartModule.StartState state)
 {
     base.OnStart(state);
     if (HighLogic.LoadedSceneIsFlight) {
         sensorInt = sensorTypeInt(sensorType);
         Fields["readoutInfo"].guiName = guiReadout(sensorInt);
         //Assign transforms for all of the indicator needles, etc.. for each part type
         if (sensorInt == 1 || sensorInt == 2 || sensorInt == 3)
             indicator = part.FindModelTransform(sensorType);
         if (sensorInt == 3)
             indicatorPosition = indicator.localPosition;
         if (sensorInt == 4) {
             rotor1 = part.FindModelTransform(sensorType + "_000");
             rotor2 = part.FindModelTransform(sensorType + "_001");
             rotor3 = part.FindModelTransform(sensorType + "_002");
             tilt1 = part.FindModelTransform(sensorType + "_003");
         }
         //Prevent multiple modules from interfering with each other
         if (primary) {
             modList = this.part.FindModulesImplementing<DMEnviroSensor>();
             if (modList.Count > 1) {
                 modList[0].Events["toggleSensor"].active = true;
                 modList[1].Events["toggleSensor"].active = false;
             }
         }
     }
 }
        public override void OnStart(PartModule.StartState state)
        {
            predictor = core.GetComputerModule<MechJebModuleLandingPredictions>();

            if (landingSites == null && HighLogic.LoadedSceneIsFlight)
                InitLandingSitesList();
        }
示例#22
0
 public override void OnStart(PartModule.StartState state)
 {
     Flap = part.FindModelTransform(flapTransform);
     cachedRenderer = Flap.gameObject.GetComponent<Renderer>();
     if (FlapActive != false)
         ToggleFlaps();
 }
        public override void OnStart(PartModule.StartState state)
        {
            if (!HighLogic.LoadedSceneIsFlight && !HighLogic.LoadedSceneIsEditor) { return; }

            //In case of errors
            if (string.IsNullOrEmpty(this.animationName) || this.part.FindModelAnimators(this.animationName).Length <= 0)
            {
                Events.ForEach(e => e.active = false);
                Actions.ForEach(a => a.active = false);
                return;
            }

            //Initiates the animation
            InitiateAnimation();

            //Sets the action groups/part GUI
            BaseEvent  toggle = Events["GUIToggle"];
            BaseAction aEnable = Actions["ActionEnable"], aDisable = Actions["ActionDisable"], aToggle = Actions["ActionToggle"];

            toggle.guiActiveEditor = this.activeEditor;
            toggle.guiActive = this.activeFlight;
            toggle.guiActiveUnfocused = this.activeUnfocused;
            toggle.unfocusedRange = this.unfocusedRange;
            SetName();

            if (string.IsNullOrEmpty(this.actionEnableName)) { aEnable.active = false; }
            else { aEnable.guiName = this.actionEnableName; }

            if (string.IsNullOrEmpty(this.actionDisableName)) { aDisable.active = false; }
            else { aDisable.guiName = this.actionDisableName; }

            if (string.IsNullOrEmpty(this.actionToggleName)) { aToggle.active = false; }
            else { aToggle.guiName = this.actionToggleName; }
        }
        public override void OnStart(PartModule.StartState state)
        {
            if (state == StartState.Editor) return;

            System.Random rnd = new System.Random();
            _window_ID = rnd.Next(int.MaxValue);

            var unsortedList =  new List<IRefineryActivity>();

            try
            {
                unsortedList.Add(new AnthraquinoneProcessor(this.part));
                unsortedList.Add(new NuclearFuelReprocessor(this.part));
                unsortedList.Add(new AluminiumElectrolyser(this.part));
                unsortedList.Add(new SabatierReactor(this.part));
                unsortedList.Add(new WaterElectroliser(this.part));
                unsortedList.Add(new PeroxideProcess(this.part));
                unsortedList.Add(new UF4Ammonolysiser(this.part));
                unsortedList.Add(new HaberProcess(this.part));
                unsortedList.Add(new AmmoniaElectrolyzer(this.part));
                unsortedList.Add(new CarbonDioxideElectroliser(this.part));
                unsortedList.Add(new WaterGasShift(this.part));
                unsortedList.Add(new ReverseWaterGasShift(this.part));
            }
            catch (Exception e)
            {
                Debug.LogException(e, new UnityEngine.Object() { name = "ISRU Refinery" });
                Debug.LogWarning("ISRU Refinery Exception " + e.Message);
            }

            _refinery_activities = unsortedList.OrderBy(a => a.ActivityName).ToList();

            RenderingManager.AddToPostDrawQueue(0, OnGUI);
        }
示例#25
0
 public override void OnStart(PartModule.StartState state)
 {
     base.OnStart(state);
         engine = part.Modules.OfType<ModuleEngines>().FirstOrDefault();
        partTransform = part.FindModelTransform(thrustTransform);
         //maxThrust = engine.maxThrust;
 }
示例#26
0
        public override void OnStart(PartModule.StartState state)
        {
            this.part.force_activate();
            animator = part.Modules.OfType<IExtractorAnimator>().SingleOrDefault();

            if (animator == null)
            {
                animator = new DefaultExtractorAnimator();
            }
            else
            {
                Events["DeployDrill"].guiActiveEditor = true;
                Events["RetractDrill"].guiActiveEditor = true;
            }

            headTransform = this.part.FindModelTransform(HeadTransform);
            tailTransform = this.part.FindModelTransform(TailTransform);

            if (state == StartState.Editor) { return; }
            if (FlightGlobals.fetch == null) { return; }

            emitters = part.Modules.OfType<KethaneParticleEmitter>().ToArray();

            foreach (var emitter in emitters)
            {
                emitter.Setup();
                emitter.EmitterTransform.parent = headTransform;
                emitter.EmitterTransform.localRotation = Quaternion.identity;
            }
        }
示例#27
0
        public override void OnStart(PartModule.StartState state)
        {
            // Sync settings with the runtime
            this.StartCoroutine("RuntimeFetch");

            this.Events["TakeParts"].active = true;
        }
示例#28
0
 public override void OnStart(PartModule.StartState state)
 {
     base.OnStart(state);
     engine = part.Modules.OfType<ModuleEngines>().FirstOrDefault();
     intake = part.Modules.OfType<ModuleResourceIntake>().FirstOrDefault();
     toggleMenuItems(false);
 }
示例#29
0
        public override void OnStart(PartModule.StartState state)
        {
            DragManager = part.gameObject.GetComponent<DragManager>();

            if (DragManager == null) {
                DragManager = part.gameObject.AddComponent<DragManager>();
                DragManager.SetPart(part);
            }

            anim = part.FindModelAnimators(AnimationName)[0];
            animState = anim[AnimationName];
            animState.wrapMode = WrapMode.Clamp;

            if (FixAnimLayers) {
                int i = 0;
                foreach (AnimationState s in anim)
                    s.layer = i++;
            }

            animState.normalizedSpeed = 0;
            if (engaged) {
                animState.normalizedTime = Drag / 100;
                spoilerState = ModuleLandingGear.GearStates.DEPLOYED;
            }
            else {
                animState.normalizedTime = 0;
                spoilerState = ModuleLandingGear.GearStates.RETRACTED;
            }
            anim.Play(AnimationName);
        }
        public override void OnStart(PartModule.StartState state)
        {
            double time_diff = lastActiveTime - Planetarium.GetUniversalTime();

            if (state == StartState.Editor)
                return;

            if (part.Resources.Contains(resourceName))
                decay_resource = part.Resources[resourceName];
            else
            {
                decay_resource = null;
                return;
            }

            resourceDefinitionsContainDecayProduct = PartResourceLibrary.Instance.resourceDefinitions.Contains(decayProduct);
            if (resourceDefinitionsContainDecayProduct)
                density_rat = decay_resource.info.density / PartResourceLibrary.Instance.GetDefinition(decayProduct).density;

            if (decay_resource != null && time_diff > 0)
            {
                double n_0 = decay_resource.amount;
                decay_resource.amount = n_0 * Math.Exp(-decayConstant * time_diff);
                double n_change = n_0 - decay_resource.amount;

                if (resourceDefinitionsContainDecayProduct)
                    ORSHelper.fixedRequestResource(part, decayProduct, -n_change * density_rat);
            }
        }
示例#31
0
 public ColorSourceException(PartModule module, string message, Exception cause) : base(message, cause)
 {
     this.module = module;
 }
示例#32
0
            /// <summary>
            /// Try to get a pulsate color source from a ParsedParameters. The expected format is:
            ///
            /// pulsate(origin, cycleMillis, multiplier)
            ///
            /// ...where multiplier is a float in the range 0 - 1.
            /// </summary>
            public static IColorSource TryParse(PartModule module, ParsedParameters parsedParams)
            {
                if (parsedParams == null)
                {
                    return(null);
                }
                if (!TYPE_NAME.Equals(parsedParams.Identifier))
                {
                    return(null);
                }
                if ((parsedParams.Count < 3) || (parsedParams.Count > 4))
                {
                    throw new ColorSourceException(
                              module,
                              TYPE_NAME + "() source specified " + parsedParams.Count + " parameters (3-4 required)");
                }

                IColorSource origin;

                try
                {
                    origin = FindPrivate(module, parsedParams[0]);
                }
                catch (ColorSourceException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "() source has invalid origin", e);
                }

                long cycleMillis;

                try
                {
                    cycleMillis = long.Parse(parsedParams[1]);
                }
                catch (FormatException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): Invalid cycle milliseconds value '" + parsedParams[1] + "'", e);
                }
                if (cycleMillis < 1)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): cycle milliseconds must be positive");
                }

                float multiplier2;

                try
                {
                    multiplier2 = float.Parse(parsedParams[2]);
                }
                catch (FormatException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): Invalid multiplier value '" + parsedParams[2] + "' (must be a float)", e);
                }
                if ((multiplier2 < 0) || (multiplier2 > 1))
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): Invalid multiplier value '" + parsedParams[2] + "' (must be in range 0 - 1)");
                }

                float multiplier1 = 1;

                if (parsedParams.Count > 3)
                {
                    try
                    {
                        multiplier1 = float.Parse(parsedParams[3]);
                    }
                    catch (FormatException e)
                    {
                        throw new ColorSourceException(module, TYPE_NAME + "(): Invalid multiplier value '" + parsedParams[3] + "' (must be a float)", e);
                    }
                    if ((multiplier1 < 0) || (multiplier1 > 1))
                    {
                        throw new ColorSourceException(module, TYPE_NAME + "(): Invalid multiplier value '" + parsedParams[3] + "' (must be in range 0 - 1)");
                    }
                }

                if ((multiplier1 >= 1) && (multiplier2 >= 1))
                {
                    return(origin);
                }

                return(new PulsateColorSource(origin, cycleMillis, multiplier1, multiplier2));
            }
示例#33
0
            /// <summary>
            /// Try to get a blink color source from a ParsedParameters. The expected format is:
            ///
            /// blink(onSource, onMillis, offSource, offMillis)
            /// </summary>
            public static IColorSource TryParse(PartModule module, ParsedParameters parsedParams)
            {
                if (parsedParams == null)
                {
                    return(null);
                }
                if (!TYPE_NAME.Equals(parsedParams.Identifier))
                {
                    return(null);
                }
                if ((parsedParams.Count < 4) || (parsedParams.Count > 5))
                {
                    throw new ColorSourceException(
                              module,
                              TYPE_NAME + "() source specified " + parsedParams.Count + " parameters (4-5 required)");
                }

                IColorSource onSource;

                try
                {
                    onSource = FindPrivate(module, parsedParams[0]);
                }
                catch (ColorSourceException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "() source has invalid 'on' parameter", e);
                }


                long onMillis;

                try
                {
                    onMillis = long.Parse(parsedParams[1]);
                }
                catch (FormatException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): Invalid 'on' milliseconds value '" + parsedParams[1] + "' (must be an integer)", e);
                }
                if (onMillis < 1)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): 'on' milliseconds must be positive");
                }

                IColorSource offSource;

                try
                {
                    offSource = FindPrivate(module, parsedParams[2]);
                }
                catch (ColorSourceException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "() source has invalid 'off' parameter", e);
                }

                long offMillis;

                try
                {
                    offMillis = long.Parse(parsedParams[3]);
                }
                catch (FormatException e)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): Invalid 'off' milliseconds value '" + parsedParams[3] + "' (must be an integer)", e);
                }
                if (offMillis < 1)
                {
                    throw new ColorSourceException(module, TYPE_NAME + "(): 'off' milliseconds must be positive");
                }

                float phase = 0F;

                if (parsedParams.Count > 4)
                {
                    try
                    {
                        phase = float.Parse(parsedParams[4]);
                    }
                    catch (FormatException e)
                    {
                        throw new ColorSourceException(module, TYPE_NAME + "(): Invalid phase value '" + parsedParams[4] + "' (must be a float)", e);
                    }
                }

                return(new BlinkColorSource(onSource, onMillis, offSource, offMillis, phase));
            }
示例#34
0
        /// <summary>
        /// Given a color source ID (which might be a literal color, the ID of a controller,
        /// or a parameterized source), try to find the appropriate source. If it can't
        /// be parsed or found, throws a ColorSourceException.
        private static IColorSource FindPrivate(PartModule module, string sourceID)
        {
            if (string.IsNullOrEmpty(sourceID))
            {
                throw new ColorSourceException(module, "Null or empty color source");
            }

            // Maybe it's a color string.
            if (Colors.IsColorString(sourceID))
            {
                return(Constant(Colors.Parse(sourceID, Color.black)));
            }

            // Is it a parameterized source?
            ParsedParameters parsedParams = ParsedParameters.TryParse(sourceID);

            if (parsedParams != null)
            {
                // It has the right syntax for a parameterizeed source. Do we recognize it?
                for (int i = 0; i < PARSEABLE_SOURCES.Length; ++i)
                {
                    IColorSource candidate = PARSEABLE_SOURCES[i](module, parsedParams);
                    if (candidate != null)
                    {
                        return(candidate);
                    }
                }
                throw new ColorSourceException(module, "Unknown function type '" + parsedParams.Identifier + "'");
            }

            // Maybe it's another field on the module?
            for (int i = 0; i < module.Fields.Count; ++i)
            {
                BaseField field = module.Fields[i];
                if (!sourceID.Equals(field.name))
                {
                    continue;
                }
                if (!ColorSourceIDField.Is(field))
                {
                    throw new ColorSourceException(
                              module, sourceID + " field on " + module.ClassName + " of "
                              + module.part.GetTitle() + " is not a color source ID field");
                }
                return(Find(module, field.GetValue <string>(module)));
            }

            // Maybe it's a module on the part?
            for (int i = 0; i < module.part.Modules.Count; ++i)
            {
                IColorSource candidate = module.part.Modules[i] as IColorSource;
                if (candidate == null)
                {
                    continue;
                }
                if (sourceID.Equals(candidate.ColorSourceID))
                {
                    return(candidate);
                }
            }

            // not found
            throw new ColorSourceException(module, "Can't find a color source named '" + sourceID + "'");
        }
示例#35
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);
                List <ModuleResourceConverter> converterModules       = KRnD.getConverterModules(part);
                ModuleParachute                parachuteModule        = KRnD.getParachuteModule(part);
                ModuleProceduralFairing        fairingModule          = KRnD.getFairingModule(part);
                List <PartResource>            fuelResources          = KRnD.getFuelResources(part);
                PartModule                     IFSModule              = KRnD.getIFSModule(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";
                    }
                }
                // IFS Fuels
                if (IFSModule != null)
                {
                    int      i = 0;
                    String[] ifsResourceNames   = KRnD.parseIFSField((String)IFSModule.Fields.GetValue(KRnDUpgrade.RESOURCE_NAMES), ';');
                    String[] ifsResourceAmounts = KRnD.parseIFSField((String)IFSModule.Fields.GetValue(KRnDUpgrade.RESOURCE_AMOUNTS), ';');
                    foreach (String ifsResource in ifsResourceNames)
                    {
                        String fuelName = ifsResource;
                        fuelName = Regex.Replace(fuelName, @"([a-z])([A-Z])", "$1 $2");
                        info    += "<b>IFS: " + fuelName + ":</b> " + ifsResourceAmounts[i] + "\n";
                        i++;
                    }
                }

                // 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 (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);
        }
示例#36
0
 // partInfo is assigned after modules are created and loaded
 public static bool ParsedPrefab(this PartModule module) => module.part.partInfo != null;
示例#37
0
 public static void LogError(this PartModule module, object message) => module.part.LogError($"{module.LogTagString()} {message}");
        private IEnumerator deployEvent()
        {
            if (USTwoScience)
            {
                RaycastHit hit;

                if (_raySource != null && Physics.Raycast(_raySource.position, _raySource.forward, out hit, 1f, LayerUtil.DefaultEquivalent))
                {
                    if (hit.collider != null)
                    {
                        bool primary   = false;
                        bool secondary = false;

                        if (hit.collider.gameObject.name == "PrimaryDoorCollider")
                        {
                            primary = true;
                        }
                        else if (hit.collider.gameObject.name == "SecondaryDoorCollider")
                        {
                            secondary = true;
                        }

                        if (primary || secondary)
                        {
                            Part p = FlightGlobals.GetPartUpwardsCached(hit.collider.gameObject);// Part.GetComponentUpwards<Part>(hit.collider.gameObject);

                            if (p != null)
                            {
                                IScalarModule scalar      = null;
                                float         deployLimit = 1;
                                PartModule    USAnimate   = null;

                                for (int i = p.Modules.Count - 1; i >= 0; i--)
                                {
                                    if (p.Modules[i].moduleName == "USAnimateGeneric")
                                    {
                                        USAnimate = p.Modules[i];

                                        if (USAnimate is IScalarModule)
                                        {
                                            scalar = USAnimate as IScalarModule;
                                        }

                                        break;
                                    }
                                }

                                if (USAnimate != null && scalar != null)
                                {
                                    BaseEvent doorEvent = null;
                                    BaseField doorLimit = null;

                                    if (primary)
                                    {
                                        doorEvent = USAnimate.Events["toggleEventPrimary"];

                                        doorLimit = USAnimate.Fields["primaryDeployLimit"];
                                    }
                                    else if (secondary)
                                    {
                                        doorEvent = USAnimate.Events["toggleEventSecondary"];

                                        doorLimit = USAnimate.Fields["secondaryDeployLimit"];
                                    }

                                    if (doorLimit != null)
                                    {
                                        deployLimit = doorLimit.GetValue <float>(USAnimate) * 0.01f;
                                    }

                                    if (doorEvent != null)
                                    {
                                        if (doorEvent.active && doorEvent.guiActive)
                                        {
                                            doorEvent.Invoke();

                                            DMUtils.Logging("Door Invoked");

                                            while (scalar.GetScalar < deployLimit)
                                            {
                                                yield return(null);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            var ownColliders = part.GetComponentsInChildren <Collider>();

                            bool flag = false;

                            for (int i = ownColliders.Length - 1; i >= 0; i--)
                            {
                                if (hit.collider == ownColliders[i])
                                {
                                    flag = true;

                                    break;
                                }
                            }

                            if (!flag)
                            {
                                ScreenMessages.PostScreenMessage(
                                    string.Format(
                                        "<b><color=orange>Obstruction detected preventing {0} from being deployed.</color></b>"
                                        , part.partInfo.title)
                                    , 5f, ScreenMessageStyle.UPPER_CENTER);

                                yield break;
                            }
                        }
                    }
                }
            }

            IsDeployed = true;

            animator(1f, 0f, Anim, animationName);

            if (USScience)
            {
                animator(1f, 0f, USAnim, USBayAnimation);
            }

            yield return(new WaitForSeconds(Anim[animationName].length));

            fullyDeployed = true;
        }
示例#39
0
 public bool isAvailable(PartModule module)
 {
     return(string.IsNullOrEmpty(upgradeName) || upgradeName.Equals("none", StringComparison.InvariantCultureIgnoreCase) || module.upgradesApplied.Contains(upgradeName));
 }
示例#40
0
        private void SetupICrossSectionAdjusters()
        {
            Matrix4x4 worldToVesselMatrix;

            if (HighLogic.LoadedSceneIsFlight)
            {
                worldToVesselMatrix = vessel.vesselTransform.worldToLocalMatrix;
            }
            else
            {
                worldToVesselMatrix = EditorLogic.RootPart.partTransform.worldToLocalMatrix;
            }
            crossSectionAdjusters = new List <ICrossSectionAdjuster>();

            string intakeType = "", engineType = "";

            if (part.Modules.Contains("ModuleEnginesAJEJet"))       //hard-coded support for AJE; TODO: separate out for more configurable compatibility on 3rd-party end
            {
                engineType = "ModuleEnginesAJEJet";
            }
            else if (part.Modules.Contains("ModuleEngines"))
            {
                engineType = "ModuleEngines";
            }
            else if (part.Modules.Contains("ModuleEnginesFX"))
            {
                engineType = "ModuleEnginesFX";
            }


            if (part.Modules.Contains("AJEInlet"))
            {
                intakeType = "AJEInlet";
            }
            else if (part.Modules.Contains("ModuleResourceIntake"))
            {
                intakeType = "ModuleResourceIntake";
            }

            if (intakeType != "" && engineType != "")
            {
                PartModule module = part.Modules[intakeType];

                if (module is ModuleResourceIntake)
                {
                    ModuleResourceIntake intake = (ModuleResourceIntake)module;

                    IntegratedIntakeEngineCrossSectionAdjuster intakeAdjuster = IntegratedIntakeEngineCrossSectionAdjuster.CreateAdjuster(intake, worldToVesselMatrix);
                    crossSectionAdjusters.Add(intakeAdjuster);
                }
                else
                {
                    IntegratedIntakeEngineCrossSectionAdjuster intakeAdjuster = IntegratedIntakeEngineCrossSectionAdjuster.CreateAdjuster(module, worldToVesselMatrix);
                    crossSectionAdjusters.Add(intakeAdjuster);
                }
                return;
            }
            if (intakeType != "")
            {
                PartModule module = part.Modules[intakeType];

                if (module is ModuleResourceIntake)
                {
                    ModuleResourceIntake intake = (ModuleResourceIntake)module;

                    IntakeCrossSectionAdjuster intakeAdjuster = IntakeCrossSectionAdjuster.CreateAdjuster(intake, worldToVesselMatrix);
                    crossSectionAdjusters.Add(intakeAdjuster);
                }
                else
                {
                    IntakeCrossSectionAdjuster intakeAdjuster = IntakeCrossSectionAdjuster.CreateAdjuster(module, worldToVesselMatrix);
                    crossSectionAdjusters.Add(intakeAdjuster);
                }
                return;
            }
            if (engineType != "")
            {
                ModuleEngines engines     = (ModuleEngines)part.Modules[engineType];
                bool          airBreather = false;

                if (engineType == "ModuleEnginesAJEJet")
                {
                    airBreather = true;
                }
                else
                {
                    for (int i = 0; i < engines.propellants.Count; ++i)
                    {
                        Propellant p = engines.propellants[i];
                        if (p.name == "IntakeAir")
                        {
                            airBreather = true;
                            break;
                        }
                    }
                }

                if (airBreather)
                {
                    AirbreathingEngineCrossSectonAdjuster engineAdjuster = new AirbreathingEngineCrossSectonAdjuster(engines, worldToVesselMatrix);
                    crossSectionAdjusters.Add(engineAdjuster);
                }
                return;
            }
        }
 public FNResourceManager(PartModule pm, String resource_name) : base(pm, resource_name)
 {
     windowPosition = new Rect(200, 200, 350, 100);
 }
示例#42
0
 protected override void LoadPartModules()
 {
     base.LoadPartModules();
     pmFairing   = part.Modules["ProceduralFairingSide"];
     pmDecoupler = part.Modules["ProceduralFairingDecoupler"];
 }
示例#43
0
 public BackgroundModule(BackgroundFunctionInfo functionInfo, Vessel vessel, ProtoPartSnapshot protoPartSnapshot, ProtoPartModuleSnapshot protoPartModuleSnapshot, Part part, PartModule partModule)
 {
     FunctionInfo            = functionInfo;
     Vessel                  = vessel;
     ProtoPartSnapshot       = protoPartSnapshot;
     ProtoPartModuleSnapshot = protoPartModuleSnapshot;
     Part       = part;
     PartModule = partModule;
 }
示例#44
0
 public BackgroundSuppliableModule(BackgroundFunctionInfo functionInfo, Vessel vessel, ProtoPartSnapshot protoPartSnapshot, ProtoPartModuleSnapshot protoPartModuleSnapshot, Part part, PartModule partModule) : base(functionInfo, vessel, protoPartSnapshot, protoPartModuleSnapshot, part, partModule)
 {
 }
示例#45
0
 // get the corresponding PartModule in the part prefab
 public static PartModule GetPrefab(this PartModule module)
 {
     return(module.part.GetPrefab().Modules[module.part.Modules.IndexOf(module)]);
 }
示例#46
0
 public ScannerDevice(PartModule scanner)
 {
     this.scanner = scanner;
 }
示例#47
0
 public override void OnCopy(PartModule fromModule)
 {
     base.OnCopy(fromModule);
     KSPLog.print("Core: OnCopy");
 }
示例#48
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);
            Events["HideUI"].active = false;
            Events["ShowUI"].active = true;

            if (isTimed)
            {
                Fields["detonationTime"].guiActive       = true;
                Fields["detonationTime"].guiActiveEditor = true;
            }
            else
            {
                Fields["detonationTime"].guiActive       = false;
                Fields["detonationTime"].guiActiveEditor = false;
            }

            if (HighLogic.LoadedSceneIsEditor)
            {
                WeaponNameWindow.OnActionGroupEditorOpened.Add(OnActionGroupEditorOpened);
                WeaponNameWindow.OnActionGroupEditorClosed.Add(OnActionGroupEditorClosed);
                Fields["CruiseAltitude"].guiActiveEditor      = true;
                Events["SwitchTargetingMode"].guiActiveEditor = true;
                Events["SwitchGuidanceMode"].guiActiveEditor  = true;
            }
            else
            {
                Fields["CruiseAltitude"].guiActiveEditor      = false;
                Events["SwitchTargetingMode"].guiActiveEditor = false;
                Events["SwitchGuidanceMode"].guiActiveEditor  = false;
                SetMissileTransform();
                DisablingExplosives();
            }
            if (string.IsNullOrEmpty(GetShortName()))
            {
                shortName = "Unnamed";
            }
            part.force_activate();
            RefreshGuidanceMode();

            UpdateTargetingMode((TargetingModes)Enum.Parse(typeof(TargetingModes), _targetingLabel));

            _targetDecoupler = FindFirstDecoupler(part.parent, null);

            DisableResourcesFlow();

            weaponClass = WeaponClasses.Missile;
            WeaponName  = GetShortName();

            InitializeEngagementRange(minStaticLaunchRange, maxStaticLaunchRange);
            this.ToggleEngageOptions();
            this.activeRadarRange = ActiveRadarRange;

            if (this.DetonationDistance == -1)
            {
                this.DetonationDistance = GetBlastRadius();
            }


            //TODO: BDModularGuidance should be configurable?
            lockedSensorFOV = 5;
            radarLOAL       = true;
        }
示例#49
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;
                List <ModuleResourceConverter> converterModules       = null;
                ModuleParachute                parachuteModule        = null;
                List <PartResource>            fuelResources          = null;
                String[]                       IFSResourceNames       = null;
                String[]                       IFSResourceAmounts     = 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);
                        converterModules       = KRnD.getConverterModules(part);
                        parachuteModule        = KRnD.getParachuteModule(part);
                        fuelResources          = KRnD.getFuelResources(part);
                        PartModule ifsModule = KRnD.getIFSModule(part);
                        if (ifsModule != null)
                        {
                            IFSResourceNames   = KRnD.parseIFSField((String)ifsModule.Fields.GetValue(KRnDUpgrade.RESOURCE_NAMES), ';');
                            IFSResourceAmounts = KRnD.parseIFSField((String)ifsModule.Fields.GetValue(KRnDUpgrade.RESOURCE_AMOUNTS), ';');
                        }
                    }
                }
                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 || IFSResourceNames != null)
                {
                    options.Add("Fuel Pressure");
                }
                if (generatorModule)
                {
                    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());
            }
        }
示例#50
0
 internal ModSolarPanel(PartModule pModule, Part iPart)
 {
     PanelModule = pModule;
     SPart       = iPart;
 }