Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //ID-ICE InfiniteDice Internal Combustion Engine - Module for KSP. Mod, code, models, textures are shared under
- //Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - You are free to:Share — copy and redistribute the material in any medium or format - You can modify files for your personal use.
- //If you remix, transform, or build upon the material, you may not distribute the modified material. You may not use the material for commercial purposes.
- //A note on the license - I have dozens of hours in this and other mods, which I share out to the community for no fees. Id you like the mod please share your thoughts/images/videos on the KSP forum thread!
- //Thanks for using this mod.
- //ID ICE is not perfect! I don't claim this is a totally realistic simulation of how a real engine works. My overall goal was to experiment with making an alternative engine module for KSP.
- //Secondly to support and inspire the community to take more advantage of EVA activities. Have fun!
- class IDwheel : PartModule
- {
- #region variables
- [KSPField]
- public string wheelColliderName = "wheelCollider";
- [KSPField]
- public string boundsCollider = "Bounds";
- [KSPField]
- public string wheelMeshName = "Wheel";
- [KSPField]
- public string suspensionParentName = "suspensionParent";
- [KSPField]
- public int numberOfWheels = 1;
- [KSPField]
- public string sfxBurnoutLoop = "IDiCEr1/Sounds/burnout";
- public FXGroup soundLoop = null;
- public GameObject fxBoInstance;
- [KSPField]
- public string altWheelLocP = "adjSusParLoc";
- public Transform alterWheelCPos = null;
- public bool useAltWLoc = false;
- [KSPField]
- public bool disableColliderWhenRetracted = false;
- [KSPField]
- public bool usesIDdDrive = false;
- [KSPField]
- public float wheelRadius = 0.25f;
- [KSPField]
- public float wheelWidth = 0.125f;
- public IDice getICEOutput;
- public IDdDrive getICEdDrive;
- public bool firstRun = true;
- [KSPField]
- public float origDrag = 2.2f;
- [KSPField(isPersistant = true)]
- public bool tireFlat = false;
- [KSPField(isPersistant = true)]
- public bool isDestroyed = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "GearDrag Multi"), UI_FloatRange(minValue = 100f, maxValue = 300f, stepIncrement = 50f)]
- public float gearDragMulti = 150f;
- [KSPField]
- public string animationName = "Retract";
- [KSPField]
- public int animationLayer = 1;
- [KSPField]
- public float deploymentCooldown = 0.5f;
- [KSPField(isPersistant = true)]
- public string deploymentState = "Deployed";
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Brake Torque"), UI_FloatRange(minValue = 0f, maxValue = 40f, stepIncrement = 2.5f)]
- public float brakeTorque = 5f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Spring Rate"), UI_FloatRange(minValue = 0.1f, maxValue = 1.8f, stepIncrement = 0.1f)]
- public float suspSpring = 0.2f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Damp Rate"), UI_FloatRange(minValue = 0.1f, maxValue = 1.8f, stepIncrement = 0.1f)]
- public float suspDamp = 0.1f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Rest Height"), UI_FloatRange(minValue = 0.05f, maxValue = 0.5f, stepIncrement = 0.05f)]
- public float suspRHeight = 0.25f;
- [KSPField]
- public float brakeSpeed = 0.75f;
- [KSPField(isPersistant = true)]
- public bool brakesEngaged = false;
- public float velocitySlipMod = 1f;
- public float alterSlipMod = 2.5f;
- [KSPField]
- public float hubDrag = 1.5f;
- [KSPField(isPersistant = true)]
- public bool hubDamage = false;
- public float sideSlipMod, forwardSlipMod;
- public KSPParticleEmitter[] findKspEmitter;
- [KSPField(isPersistant = true)]
- public float origSFriction;
- [KSPField(isPersistant = true)]
- public float origFFriction;
- public AnimationCurve vSlipCurve;
- public AnimationCurve aMSlipCurve;
- public float cornerLoad = 0f;
- public float origCLoad = 0f;
- public bool setOnce = true;
- public float lastSlipMod = 0f;
- public float percentGripMod = 1f;
- [KSPField]
- public bool hasMotor = true;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Motor Enabled"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool motorEnabled = false;
- [KSPField]
- public float motorTorque = 80f;
- [KSPField]
- public float maxSpeed = 30f;
- [KSPField]
- public string resourceName = "ElectricCharge";
- [KSPField]
- public float resourceConsumptionRate = 0.2f;
- [KSPField(isPersistant = true, guiActiveEditor = false, guiActive = true, guiName = "Motor Reversed"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool reverseMotor = false;
- [KSPField(isPersistant = true)]
- public bool reverseMotorSet = false;
- [KSPField(isPersistant = true)]
- public bool motorStartsReversed = false;
- #region wheel collider settings
- [KSPField]
- public bool overrideModelFrictionValues = false;
- [KSPField]
- public float forwardsStiffness = 10.0f;
- [KSPField]
- public float forwardsExtremumSlip = 1.0f;
- [KSPField]
- public float forwardsExtremumValue = 20000.0f;
- [KSPField]
- public float forwardsAsymptoteSlip = 2.0f;
- [KSPField]
- public float forwardsAsymptoteValue = 10000.0f;
- [KSPField]
- public float sidewaysStiffness = 1.0f;
- [KSPField]
- public float sidewaysExtremumSlip = 1.0f;
- [KSPField]
- public float sidewaysExtremumValue = 20000.0f;
- [KSPField]
- public float sidewaysAsymptoteSlip = 2.0f;
- [KSPField]
- public float sidewaysAsymptoteValue = 10000.0f;
- [KSPField]
- public float wheelColliderMass = -1f;
- [KSPField]
- public float wheelColliderRadius = -1f;
- [KSPField]
- public float wheelColliderSuspensionDistance = -1f;
- [KSPField]
- public float suspensionSpring = -1f;
- [KSPField]
- public float suspensionDamper = -1f;
- [KSPField]
- public float suspensionTargetPosition = -1f;
- #endregion
- [KSPField]
- public float rotationAdjustment = 1f;
- [KSPField]
- public float deployedDrag = 0f;
- [KSPField]
- public float retractedDrag = 0f;
- [KSPField]
- public bool guiActiveUnfocused = true;
- [KSPField]
- public float unfocusedRange = 5f;
- public bool bWasDown = false;
- public float animTime = 0f;
- public float animSpeed = 0f;
- public float rotation = 0f;
- public bool fixOngoing = false;
- public float doneTime = 0f;
- public bool canFixFlat = true;
- private Animation anim;
- private WheelList wheelList = new WheelList();
- public int gWheelNum;
- private bool boundsColliderRemoved = false;
- [KSPField]
- public bool debugMode = false;
- #endregion
- #region Actions and Events
- [KSPAction("Raise Lower Gear", KSPActionGroup.Gear)]
- public void ToggleGearAction(KSPActionParam param)
- {
- if (param.type == KSPActionType.Activate)
- {
- LowerGear();
- }
- else
- {
- RaiseGear();
- }
- param.Cooldown = deploymentCooldown;
- }
- [KSPEvent(guiName = "Raise Gear", guiActive = true, guiActiveUnfocused = true, unfocusedRange = 5f)]
- public void RaiseGear()
- {
- animate("Retract");
- }
- [KSPEvent(guiName = "Lower Gear", guiActive = true, guiActiveUnfocused = true, unfocusedRange = 5f)]
- public void LowerGear()
- {
- animate("Deploy");
- }
- [KSPAction("Reverse Motor")]
- public void ReverseMotorAction(KSPActionParam param)
- {
- ReverseMotorEvent();
- }
- [KSPEvent(guiName = "Toggle Reverse Motor", guiActive = true)]
- public void ReverseMotorEvent()
- {
- bool changeOnce = true;
- if (reverseMotor == true && changeOnce == true)
- {
- reverseMotor = false;
- changeOnce = false;
- }
- else if (reverseMotor == false && changeOnce == true)
- {
- reverseMotor = true;
- changeOnce = false;
- }
- }
- [KSPAction("Toggle Motor")]
- public void ToggleMotorAction(KSPActionParam param)
- {
- if (param.type == KSPActionType.Activate)
- {
- EnableMotorEvent();
- }
- else
- {
- DisableMotorEvent();
- }
- }
- [KSPEvent(active = true, guiName = "Fix Flat", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 5f)]
- public void fixTire()
- {
- if (fixOngoing == false && tireFlat == true && canFixFlat == true)
- {
- float fixTime = 10f;
- float startTime = Time.time;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Fixing the flat tire...", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- doneTime = fixTime + startTime;
- Events["fixTire"].active = false;
- }
- if (canFixFlat == false)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Wheel too badly damaged to fix flat, repair vessel first!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- [KSPEvent(guiName = "Enable Motor", guiActive = false)]
- public void EnableMotorEvent()
- {
- motorEnabled = true;
- Events["EnableMotorEvent"].guiActive = false;
- Events["DisableMotorEvent"].guiActive = false;
- }
- [KSPEvent(guiName = "Disable Motor", guiActive = false)]
- public void DisableMotorEvent()
- {
- motorEnabled = false;
- Events["EnableMotorEvent"].guiActive = false;
- Events["DisableMotorEvent"].guiActive = false;
- }
- private void animate(string mode)
- {
- if (anim != null)
- {
- animTime = anim[animationName].normalizedTime;
- if (deploymentState == "Retracted")
- animTime = 1f;
- if (mode == "Deploy")
- {
- if (deploymentState == "Retracted")
- animTime = 1f;
- animSpeed = -1f;
- deploymentState = "Deploying";
- }
- else if (mode == "Retract")
- {
- if (deploymentState == "Deployed")
- animTime = 0f;
- animSpeed = 1f;
- deploymentState = "Retracting";
- }
- else if (mode == "Stop")
- {
- animSpeed = 0f;
- deploymentState = "Stopped";
- }
- anim[animationName].normalizedTime = animTime;
- anim[animationName].speed = animSpeed;
- if (animSpeed != 0f)
- {
- anim.Play(animationName);
- }
- else
- {
- anim.Stop();
- }
- }
- }
- [KSPAction("Brakes", KSPActionGroup.Brakes)]
- public void BrakesAction(KSPActionParam param)
- {
- if (param.type == KSPActionType.Activate)
- {
- brakesEngaged = true;
- }
- else
- {
- brakesEngaged = false;
- }
- }
- [KSPEvent(name = "brakesOn", guiActive = true, active = true, guiName = "Brakes On", externalToEVAOnly = true, unfocusedRange = 6f, guiActiveUnfocused = true)]
- public void brakesOnEvent()
- {
- brakesEngaged = true;
- Events["brakesOnEvent"].guiActive = false;
- Events["brakesOffEvent"].guiActive = true;
- }
- [KSPEvent(name = "brakesOff", guiActive = true, active = true, guiName = "Brakes Off", externalToEVAOnly = true, unfocusedRange = 6f, guiActiveUnfocused = true)]
- public void brakesOffEvent()
- {
- brakesEngaged = false;
- Events["brakesOnEvent"].guiActive = true;
- Events["brakesOffEvent"].guiActive = false;
- }
- #endregion
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- #region In flight
- if (HighLogic.LoadedSceneIsFlight)
- {
- #region SoundFX
- soundLoop.audio = gameObject.AddComponent<AudioSource>();
- if (soundLoop.audio != null)
- {
- soundLoop.audio.volume = GameSettings.SHIP_VOLUME;
- soundLoop.audio.rolloffMode = AudioRolloffMode.Linear;
- soundLoop.audio.dopplerLevel = 0f;
- soundLoop.audio.panLevel = 1f;
- soundLoop.audio.clip = GameDatabase.Instance.GetAudioClip(sfxBurnoutLoop);
- soundLoop.audio.loop = true;
- soundLoop.audio.playOnAwake = false;
- soundLoop.audio.priority = 1;
- }
- #endregion
- #region FX
- try
- {
- fxBoInstance = GameDatabase.Instance.GetModel("IDiCEr1/Effects/BurnoutFX/model");
- }
- catch
- {
- print("Problem locating BurnoutFX");
- }
- if (fxBoInstance != null)
- {
- fxBoInstance.SetActive(false);
- fxBoInstance.transform.parent = this.part.transform;
- fxBoInstance.transform.position = this.part.transform.position;
- }
- #endregion
- #region create wheel setup
- List<WheelCollider> colliderList = new List<WheelCollider>();
- List<Transform> wheelMeshList = new List<Transform>();
- List<Transform> suspensionList = new List<Transform>();
- for (int i = 0; i < numberOfWheels; i++)
- {
- string suffix = (i + 1).ToString();
- if (i == 0)
- suffix = "";
- Transform colliderTransform = part.FindModelTransform(wheelColliderName + suffix);
- if (colliderTransform != null)
- {
- WheelCollider collider = colliderTransform.GetComponent<WheelCollider>();
- if (collider != null)
- {
- colliderList.Add(collider);
- Transform wheelMeshTransform = part.FindModelTransform(wheelMeshName + suffix);
- if (wheelMeshTransform != null)
- {
- wheelMeshList.Add(wheelMeshTransform);
- }
- else
- {
- Debug.Log("FSwheel: missing wheel mesh " + wheelMeshName + suffix);
- }
- Transform suspensionTransform = part.FindModelTransform(suspensionParentName + suffix);
- if (suspensionTransform != null)
- {
- suspensionList.Add(suspensionTransform);
- }
- else
- {
- Debug.Log("FSwheel: missing suspensionParent " + suspensionParentName + suffix);
- }
- }
- }
- else
- {
- Debug.Log("FSwheel: missing wheel collider " + wheelColliderName + suffix);
- }
- }
- wheelList.Create(colliderList, wheelMeshList, suspensionList);
- if (wheelList != null)
- {
- if (!wheelList.enabled)
- {
- wheelList.enabled = true;
- }
- }
- if (wheelList.wheels.Count > 0)
- {
- if (!reverseMotorSet)
- {
- float dot = Vector3.Dot(wheelList.wheels[0].wheelCollider.transform.forward, vessel.ReferenceTransform.up);
- if (dot < 0)
- {
- reverseMotor = true;
- }
- else
- {
- reverseMotor = false;
- }
- if (motorStartsReversed)
- reverseMotor = !reverseMotor;
- reverseMotorSet = true;
- }
- }
- if (disableColliderWhenRetracted)
- {
- if (deploymentState == "Retracted")
- {
- wheelList.enabled = false;
- }
- }
- if (overrideModelFrictionValues)
- {
- wheelList.forwardStiffness = forwardsStiffness;
- wheelList.forwardsAsymptoteSlip = forwardsAsymptoteSlip;
- wheelList.forwardsAsymptoteValue = forwardsAsymptoteValue;
- wheelList.forwardsExtremumSlip = forwardsExtremumSlip;
- wheelList.forwardsExtremumValue = forwardsExtremumValue;
- wheelList.sidewaysStiffness = sidewaysStiffness;
- wheelList.forwardsAsymptoteSlip = sidewaysAsymptoteSlip;
- wheelList.sidewaysAsymptoteValue = sidewaysAsymptoteValue;
- wheelList.sidewaysExtremumSlip = sidewaysExtremumSlip;
- wheelList.sidewaysExtremumValue = sidewaysExtremumValue;
- wheelList.updateWheelFriction();
- }
- if (suspensionSpring >= 0f && suspensionDamper >= 0f && suspensionTargetPosition >= 0f)
- {
- wheelList.updateSpring(suspensionSpring, suspensionDamper, suspensionTargetPosition);
- }
- if (wheelColliderRadius >= 0f) wheelList.radius = wheelColliderRadius;
- if (wheelColliderMass >= 0f) wheelList.mass = wheelColliderMass;
- if (wheelColliderSuspensionDistance >= 0f) wheelList.suspensionDistance = wheelColliderSuspensionDistance;
- #endregion
- #region animation
- anim = part.FindModelAnimators(animationName).FirstOrDefault();
- if (anim != null)
- {
- anim[animationName].layer = animationLayer;
- float startAnimTime = 0f;
- if (deploymentState == "Retracted")
- {
- startAnimTime = 1f;
- animSpeed = 1f;
- }
- else
- {
- animSpeed = -1f;
- }
- anim[animationName].normalizedTime = startAnimTime;
- anim[animationName].speed = animSpeed;
- anim.Play(animationName);
- }
- #endregion
- #region GUI element changes
- Events["RaiseGear"].guiActiveUnfocused = guiActiveUnfocused;
- Events["RaiseGear"].unfocusedRange = unfocusedRange;
- Events["LowerGear"].guiActiveUnfocused = guiActiveUnfocused;
- Events["LowerGear"].unfocusedRange = unfocusedRange;
- Events["EnableMotorEvent"].guiActive = !motorEnabled;
- Events["DisableMotorEvent"].guiActive = motorEnabled;
- Events["brakesOnEvent"].guiActive = !brakesEngaged;
- Events["brakesOffEvent"].guiActive = brakesEngaged;
- Events["brakesOnEvent"].guiActiveUnfocused = guiActiveUnfocused;
- Events["brakesOffEvent"].guiActiveUnfocused = guiActiveUnfocused;
- if (debugMode)
- {
- Events["increaseFrictionEvent"].guiActive = true;
- Events["decreaseFrictionEvent"].guiActive = true;
- Events["suspensionGUIEvent"].guiActive = true;
- }
- #endregion
- }
- #endregion
- if (!usesIDdDrive)
- {
- Fields["gearDragMulti"].guiActiveEditor = false;
- Fields["gearDragMulti"].guiActive = false;
- }
- }
- public void Update()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (this.vessel == FlightGlobals.ActiveVessel && usesIDdDrive)
- {
- if (Input.GetKey(KeyCode.S) && brakesEngaged == false)
- {
- brakesEngaged = true;
- bWasDown = true;
- }
- if (!Input.GetKey(KeyCode.S) && brakesEngaged == true && bWasDown == true)
- {
- brakesEngaged = false;
- bWasDown = false;
- }
- }
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight)
- return;
- if (firstRun == true)
- {
- getICEdDrive = this.vessel.FindPartModulesImplementing<IDdDrive>().FirstOrDefault();
- getICEOutput = this.vessel.FindPartModulesImplementing<IDice>().FirstOrDefault();
- Transform[] affectDmgState = this.part.FindModelTransforms("runFlat");
- findKspEmitter = fxBoInstance.GetComponentsInChildren<KSPParticleEmitter>();
- if (affectDmgState != null && tireFlat == false)
- {
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = false;
- }
- }
- else
- {
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = true;
- }
- }
- origDrag = this.part.rigidbody.drag;
- firstRun = false;
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- origSFriction = wheelList.wheels[i].wheelCollider.sidewaysFriction.stiffness;
- origFFriction = wheelList.wheels[i].wheelCollider.forwardFriction.stiffness;
- }
- }
- if (fixOngoing == true && Time.time >= doneTime && tireFlat == true)
- {
- doneTime = 0f;
- fixOngoing = false;
- tireFlat = false;
- Transform[] affectDmgState = this.part.FindModelTransforms("runFlat");
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (affectDmgState != null)
- {
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = false;
- }
- }
- wheelList.wheels[i].wheelCollider.radius = wheelRadius;
- }
- }
- #region destroy bounds collider
- if (!boundsColliderRemoved)
- {
- if (boundsCollider != string.Empty)
- {
- Transform boundsTransform = part.FindModelTransform(boundsCollider);
- if (boundsTransform != null)
- {
- GameObject.Destroy(boundsTransform.gameObject);
- }
- }
- boundsColliderRemoved = true;
- }
- #endregion
- #region update deployment state
- if (anim != null)
- {
- if (!anim.isPlaying)
- {
- if (deploymentState == "Deploying")
- deploymentState = "Deployed";
- else if (deploymentState == "Retracting")
- deploymentState = "Retracted";
- }
- }
- #endregion
- #region update brake torque
- if (brakesEngaged)
- {
- if (hubDamage == true)
- {
- wheelList.brakeTorque = Mathf.Lerp(wheelList.brakeTorque, (brakeTorque * hubDrag), TimeWarp.deltaTime * brakeSpeed);
- }
- else
- {
- wheelList.brakeTorque = Mathf.Lerp(wheelList.brakeTorque, brakeTorque, TimeWarp.deltaTime * brakeSpeed);
- }
- }
- else
- {
- if (hubDamage == true)
- {
- wheelList.brakeTorque = wheelList.mass * hubDrag;
- }
- else
- {
- wheelList.brakeTorque = 0f;
- }
- }
- #endregion
- #region update spring power
- wheelList.updateSpring(suspSpring, suspDamp, suspRHeight);
- #endregion
- #region rotate wheel meshes
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].useRotation)
- {
- if (this.usesIDdDrive && this.motorEnabled && !getICEdDrive.inNeutral && wheelList.motorTorque != 0f)
- {
- rotation = getICEdDrive.rpmOutput * rotationAdjustment * Time.deltaTime;
- }
- else if (!this.usesIDdDrive || !this.motorEnabled || getICEdDrive.inNeutral || wheelList.motorTorque == 0f)
- {
- if (wheelList.wheels[i].wheelCollider.isGrounded)
- {
- rotation = wheelList.wheels[i].wheelCollider.rpm * rotationAdjustment * Time.deltaTime;
- if (reverseMotor)
- {
- rotation *= -1f;
- }
- }
- else
- {
- rotation = Mathf.SmoothStep(500f, 0.0f, 180f);
- }
- }
- if (!this.reverseMotor)
- {
- wheelList.wheels[i].wheelMesh.Rotate(new Vector3(0f, 0f, rotation));
- }
- else
- {
- wheelList.wheels[i].wheelMesh.Rotate(new Vector3(0f, 0f, -rotation));
- }
- }
- }
- #endregion
- #region update suspension
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].useSuspension)
- {
- RaycastHit raycastHit;
- WheelCollider wheelCollider = wheelList.wheels[i].wheelCollider;
- Transform suspensionParent = wheelList.wheels[i].suspensionParent;
- alterWheelCPos = part.FindModelTransform(altWheelLocP);
- if (alterWheelCPos != null)
- {
- useAltWLoc = true;
- }
- if (useAltWLoc == false || alterWheelCPos == null)
- {
- if (Physics.Raycast(wheelCollider.transform.position, -wheelCollider.transform.up, out raycastHit, wheelCollider.suspensionDistance + wheelCollider.radius))
- {
- suspensionParent.position = raycastHit.point + wheelCollider.transform.up * wheelCollider.radius;
- cornerLoad = raycastHit.distance;
- }
- else
- {
- suspensionParent.position = wheelCollider.transform.position - wheelCollider.transform.up * wheelCollider.suspensionDistance;
- cornerLoad = wheelCollider.suspensionDistance;
- }
- }
- if(useAltWLoc == true)
- {
- if (Physics.Raycast(alterWheelCPos.position, -alterWheelCPos.up, out raycastHit, wheelCollider.suspensionDistance + wheelCollider.radius))
- {
- suspensionParent.position = raycastHit.point + alterWheelCPos.up * wheelCollider.radius;
- cornerLoad = raycastHit.distance;
- }
- else
- {
- suspensionParent.position = alterWheelCPos.position - alterWheelCPos.up * wheelCollider.suspensionDistance;
- cornerLoad = wheelCollider.suspensionDistance;
- }
- }
- }
- }
- #endregion
- #region Active vessel code
- if (vessel.isActiveVessel && base.vessel.IsControllable)
- {
- #region collider disabling
- if (disableColliderWhenRetracted)
- {
- if (deploymentState == "Retracted")
- {
- wheelList.enabled = false;
- }
- else
- {
- wheelList.enabled = true;
- }
- }
- #endregion
- #region update motors
- if (hasMotor && motorEnabled && deploymentState == "Deployed" && !usesIDdDrive)
- {
- float speedModifier = Mathf.Max(0f, -(((float)vessel.horizontalSrfSpeed - maxSpeed) / maxSpeed));
- float throttleInput = vessel.ctrlState.wheelThrottle * speedModifier;
- if (reverseMotor == true)
- throttleInput *= -1;
- double resourceConsumed = (double)Mathf.Abs(resourceConsumptionRate * throttleInput) * (double)TimeWarp.deltaTime;
- if (!CheatOptions.InfiniteFuel)
- {
- double receivedResource = base.part.RequestResource(resourceName, resourceConsumed);
- if (resourceConsumed > 0f)
- {
- double resouceReceivedNormalized = receivedResource / resourceConsumed;
- throttleInput *= Mathf.Clamp((float)resouceReceivedNormalized, 0f, 1f);
- }
- }
- if (throttleInput < 0f) throttleInput *= 0.3f;
- wheelList.motorTorque = throttleInput * motorTorque;
- }
- else if (usesIDdDrive == true && deploymentState == "Deployed" && motorEnabled)
- {
- if (getICEOutput != null && getICEdDrive != null)
- {
- float driveDirection = 1f;
- float motorSetDirection = 1f;
- if (reverseMotor == true) motorSetDirection *= -1;
- if (getICEdDrive.inReverse) driveDirection *= -1;
- float finalPower = motorSetDirection * (driveDirection * ((getICEOutput.lastCylForce * FlightInputHandler.state.mainThrottle) * getICEdDrive.gearedForceMulti));
- if (getICEdDrive.coupledICEOutput > 0f)
- {
- finalPower = motorSetDirection * (driveDirection * ((getICEdDrive.coupledICEOutput * FlightInputHandler.state.mainThrottle) * getICEdDrive.gearedForceMulti));
- }
- gWheelNum = 0;
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].wheelCollider.isGrounded)
- {
- gWheelNum += 1;
- }
- }
- if (this.vessel.rb_velocity.magnitude < ((this.wheelRadius * 2f) * 3.14f) * (getICEdDrive.rpmOutput / 60f) && getICEdDrive.currentGear != 0 && getICEOutput.currentRPM > 0f)
- {
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].wheelCollider.isGrounded && gWheelNum > 0)
- {
- float flatTMulti = 1f;
- if (tireFlat == true)
- {
- flatTMulti = 0.65f;
- }
- if (isDestroyed == true)
- {
- flatTMulti = 0.01f;
- }
- float newTorque = Mathf.Lerp(wheelList.motorTorque, ((finalPower / gWheelNum) * flatTMulti), 0.125f);
- wheelList.motorTorque = newTorque;
- this.rigidbody.drag = origDrag;
- }
- else wheelList.motorTorque = 0f;
- }
- }
- else
- {
- wheelList.motorTorque = 0f;
- this.rigidbody.drag = origDrag * (getICEdDrive.gearedForceMulti * gearDragMulti);
- }
- }
- else wheelList.motorTorque = 0f;
- }
- else
- {
- wheelList.motorTorque = 0f;
- }
- #endregion
- #region update drag
- if (deploymentState == "Deployed")
- {
- part.minimum_drag = deployedDrag;
- part.maximum_drag = deployedDrag;
- }
- else
- {
- part.minimum_drag = 0f;
- part.maximum_drag = 0f;
- }
- #endregion
- #endregion
- if (usesIDdDrive == true)
- {
- #region drifting TEST
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (percentGripMod < 1f)
- {
- percentGripMod += 0.0035f;
- if (percentGripMod < 0.64f)
- {
- setOnce = false;
- }
- else setOnce = true;
- }
- if (percentGripMod > 1f) percentGripMod = 1f;
- if (this.vessel.rb_velocity.magnitude > (((wheelRadius * 0.5f) * wheelWidth) * 150f) && cornerLoad < origCLoad && setOnce == true)//compressing - lose grip... contrary to logic!
- {
- percentGripMod = (cornerLoad / origCLoad) * 0.225f;
- setOnce = false;
- }
- origCLoad = cornerLoad;
- if (wheelList.wheels[i].wheelCollider.isGrounded)
- {
- sideSlipMod = ((wheelRadius * 0.5f) * wheelWidth) * percentGripMod;
- forwardSlipMod = (wheelRadius * 0.5f) * wheelWidth;
- if (tireFlat == true)
- {
- sideSlipMod = ((wheelRadius * 0.5f) * wheelWidth) * 0.5f;
- soundLoop.audio.Stop();
- }
- if (getICEdDrive.coupledICEOutput > 0f && motorEnabled && !getICEdDrive.inNeutral && getICEOutput.runState == "Running" || getICEdDrive.coupledICEOutput > 0f && motorEnabled && !getICEdDrive.inNeutral && getICEOutput.runState == "Overheated")
- {
- float useVelocity = this.part.vessel.rb_velocity.magnitude + 1f;
- if (reverseMotor == false)
- {
- if (getICEdDrive.rpmOutput > wheelList.wheels[i].wheelCollider.rpm)
- {
- if (getICEdDrive.rpmOutput > wheelList.wheels[i].wheelCollider.rpm * 5f && FlightInputHandler.state.mainThrottle > 0.25f)
- {
- if (soundLoop.audio.isPlaying == false)
- {
- soundLoop.audio.Play();
- }
- }
- else if (getICEdDrive.rpmOutput < wheelList.wheels[i].wheelCollider.rpm * 4f || FlightInputHandler.state.mainThrottle <= 0.25f && this.part.vessel.angularMomentum.magnitude < 5f)
- {
- fxBoInstance.SetActive(false);
- if (soundLoop.audio.isPlaying == true)
- {
- soundLoop.audio.Stop();
- }
- }
- if (getICEdDrive.rpmOutput > wheelList.wheels[i].wheelCollider.rpm * 10f)
- {
- fxBoInstance.SetActive(true);
- }
- alterSlipMod = (useVelocity / getICEdDrive.gearedForceMulti) * (1.6f - FlightInputHandler.state.mainThrottle);
- }
- else if (getICEdDrive.rpmOutput <= wheelList.wheels[i].wheelCollider.rpm * 3f)
- {
- soundLoop.audio.Stop();
- fxBoInstance.SetActive(false);
- alterSlipMod = 1.6f;
- }
- }
- else
- {
- if (getICEdDrive.rpmOutput > wheelList.wheels[i].wheelCollider.rpm * -1f)
- {
- if (getICEdDrive.rpmOutput > wheelList.wheels[i].wheelCollider.rpm * -5f && FlightInputHandler.state.mainThrottle > 0.25F)
- {
- if (soundLoop.audio.isPlaying == false)
- {
- soundLoop.audio.Play();
- }
- }
- else if (getICEdDrive.rpmOutput < wheelList.wheels[i].wheelCollider.rpm * -4f || FlightInputHandler.state.mainThrottle <= 0.25F && this.part.vessel.angularMomentum.magnitude < 5f)
- {
- fxBoInstance.SetActive(false);
- if (soundLoop.audio.isPlaying == true)
- {
- soundLoop.audio.Stop();
- }
- }
- if (getICEdDrive.rpmOutput > wheelList.wheels[i].wheelCollider.rpm * -10f)
- {
- fxBoInstance.SetActive(true);
- }
- alterSlipMod = (useVelocity / getICEdDrive.gearedForceMulti) * (1.6f - FlightInputHandler.state.mainThrottle);
- }
- else if (getICEdDrive.rpmOutput <= wheelList.wheels[i].wheelCollider.rpm * -3f)
- {
- soundLoop.audio.Stop();
- fxBoInstance.SetActive(false);
- alterSlipMod = 1.6f;
- }
- }
- }
- else
- {
- soundLoop.audio.Stop();
- fxBoInstance.SetActive(false);
- alterSlipMod = 1.6f;
- }
- vSlipCurve = AnimationCurve.Linear(0.001f, 5f, 140f, 0.0000001f);
- vSlipCurve.AddKey(1f, 3.25f);
- vSlipCurve.AddKey(3f, 1.9f);
- vSlipCurve.AddKey(9f, 1.5f);
- vSlipCurve.AddKey(18f, 0.9f);
- vSlipCurve.AddKey(36f, 0.4f);
- vSlipCurve.AddKey(80f, 0.09f);
- vSlipCurve.AddKey(120f, 0.0185f);
- float vSlipCResult = vSlipCurve.Evaluate(this.part.vessel.rb_velocity.magnitude);
- aMSlipCurve = AnimationCurve.Linear(0.1f, 4f, 12f, 0.0000001f);
- aMSlipCurve.AddKey(1f, 2.48f);
- aMSlipCurve.AddKey(2f, 1.115f);
- aMSlipCurve.AddKey(3f, 0.34f);
- aMSlipCurve.AddKey(5f, 0.172f);
- aMSlipCurve.AddKey(7f, 0.0855f);
- aMSlipCurve.AddKey(9f, 0.0425f);
- aMSlipCurve.AddKey(10f, 0.00785f);
- aMSlipCurve.AddKey(11f, 0.001185f);
- float correctAM = this.part.vessel.angularMomentum.magnitude;
- if (correctAM <= 0.1f) correctAM = 0.1f;
- if (correctAM > 12f) correctAM = 12f;
- float aMSlipCResult = aMSlipCurve.Evaluate(correctAM);
- if (getICEdDrive != null)
- {
- if (getICEdDrive.lsdEnabled == true)
- {
- alterSlipMod *= (1f + getICEdDrive.limitedSlip);
- }
- }
- velocitySlipMod = Mathf.SmoothStep(velocitySlipMod, vSlipCResult * aMSlipCResult, 0.1f);
- WheelFrictionCurve newSFriction = new WheelFrictionCurve();
- newSFriction.extremumSlip = sidewaysExtremumSlip;
- newSFriction.extremumValue = sidewaysExtremumValue;
- newSFriction.asymptoteSlip = sidewaysAsymptoteSlip;
- newSFriction.asymptoteValue = sidewaysAsymptoteValue;
- newSFriction.stiffness = (origSFriction * (velocitySlipMod * alterSlipMod) * (sideSlipMod / (((float)this.part.vessel.geeForce + 0.1f) * 9f)));
- wheelList.wheels[i].wheelCollider.sidewaysFriction = newSFriction;
- WheelFrictionCurve newFFriction = new WheelFrictionCurve();
- newFFriction.extremumSlip = forwardsExtremumSlip;
- newFFriction.extremumValue = forwardsExtremumValue;
- newFFriction.asymptoteSlip = forwardsAsymptoteSlip;
- newFFriction.asymptoteValue = forwardsAsymptoteValue;
- newFFriction.stiffness = (origFFriction * (velocitySlipMod * alterSlipMod) * (forwardSlipMod / (((float)this.part.vessel.geeForce + 0.001f) * 0.85f)));
- wheelList.wheels[i].wheelCollider.forwardFriction = newFFriction;
- }
- else
- {
- sideSlipMod = 0.0001f;
- soundLoop.audio.Stop();
- fxBoInstance.SetActive(false);
- WheelFrictionCurve newSFriction = new WheelFrictionCurve();
- newSFriction.extremumSlip = sidewaysExtremumSlip;
- newSFriction.extremumValue = sidewaysExtremumValue;
- newSFriction.asymptoteSlip = sidewaysAsymptoteSlip;
- newSFriction.asymptoteValue = sidewaysAsymptoteValue;
- newSFriction.stiffness = Mathf.SmoothStep(origSFriction, sideSlipMod, 0.05f);
- wheelList.wheels[i].wheelCollider.sidewaysFriction = newSFriction;
- WheelFrictionCurve newFFriction = new WheelFrictionCurve();
- newFFriction.extremumSlip = sidewaysExtremumSlip;
- newFFriction.extremumValue = sidewaysExtremumValue;
- newFFriction.asymptoteSlip = sidewaysAsymptoteSlip;
- newFFriction.asymptoteValue = sidewaysAsymptoteValue;
- newFFriction.stiffness = Mathf.SmoothStep(origFFriction, sideSlipMod, 0.05f);
- wheelList.wheels[i].wheelCollider.forwardFriction = newFFriction;
- }
- }
- #endregion
- }
- if (tireFlat == true)
- {
- Transform[] affectDmgState = this.part.FindModelTransforms("runFlat");
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].wheelCollider.isGrounded)
- {
- if (affectDmgState != null)
- {
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = true;
- }
- }
- }
- else
- {
- if (affectDmgState != null)
- {
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = false;
- }
- }
- }
- }
- }
- }
- }
- public void ApplyDamage(float damageState)
- {
- print("Inside ApplyDamage for ICE Wheel!");
- if (damageState < 0.5f)
- {
- float specialDamage = (float)rndNumber.rndRoll(0, 100);
- if (specialDamage < 50f)
- {
- float doDamage = (float)rndNumber.rndRoll(0, 100);
- if (doDamage < 75f && tireFlat != true)
- {
- Transform[] affectDmgState = this.part.FindModelTransforms("runFlat");
- if (affectDmgState != null)
- {
- tireFlat = true;
- Events["fixTire"].active = true;
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = true;
- }
- }
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].wheelCollider.isGrounded)
- {
- wheelList.wheels[i].wheelCollider.radius = wheelRadius * 0.85f;
- }
- }
- ScreenMessages.PostScreenMessage(new ScreenMessage("A flat tire!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (doDamage <= 100f && doDamage >= 75f && hubDamage == false)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("What is that horrible sound?", 3f, ScreenMessageStyle.UPPER_CENTER));
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- hubDamage = true;
- }
- }
- }
- if (damageState == 0.01f) //0.01 is the lowest sendmessage will use, consider this 0.
- {
- Transform[] affectDmgState = this.part.FindModelTransforms("runFlat");
- if (affectDmgState != null)
- {
- tireFlat = false;
- canFixFlat = false;
- isDestroyed = true;
- hubDamage = true;
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = false;
- }
- }
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- if (wheelList.wheels[i].wheelCollider.isGrounded)
- {
- wheelList.wheels[i].wheelCollider.radius = wheelRadius * 0.7f;
- }
- }
- }
- }
- if (damageState == 1f)
- {
- Transform[] affectDmgState = this.part.FindModelTransforms("runFlat");
- if (affectDmgState != null)
- {
- foreach (Transform tD in affectDmgState)
- {
- tD.GetComponent<MeshRenderer>().enabled = false;
- }
- tireFlat = false;
- }
- for (int i = 0; i < wheelList.wheels.Count; i++)
- {
- hubDamage = false;
- isDestroyed = false;
- canFixFlat = true;
- }
- }
- }
- }
- class WheelClass
- {
- public WheelCollider wheelCollider;
- public Transform wheelMesh;
- public Transform suspensionParent;
- public bool useRotation = false;
- public bool useSuspension = false;
- public WheelClass(WheelCollider _wheelCollider, Transform _wheelMesh, Transform _suspensionParent)
- {
- wheelCollider = _wheelCollider;
- wheelMesh = _wheelMesh;
- suspensionParent = _suspensionParent;
- }
- public WheelClass(WheelCollider _wheelCollider)
- {
- wheelCollider = _wheelCollider;
- useRotation = false;
- useSuspension = false;
- }
- }
- class WheelList
- {
- public List<WheelClass> wheels;
- private bool _enabled = false;
- private float _brakeTorque = 0f;
- private float _motorTorque = 0f;
- private float _radius = 0.25f;
- private float _suspensionDistance = 0.025f;
- private float _mass = 0.1f;
- public float forwardStiffness = 10f;
- public float forwardsExtremumSlip = 1.0f;
- public float forwardsExtremumValue = 20000.0f;
- public float forwardsAsymptoteSlip = 2.0f;
- public float forwardsAsymptoteValue = 10000.0f;
- public float sidewaysStiffness = 1.0f;
- public float sidewaysExtremumSlip = 1.0f;
- public float sidewaysExtremumValue = 20000.0f;
- public float sidewaysAsymptoteSlip = 2.0f;
- public float sidewaysAsymptoteValue = 10000.0f;
- public void Create(List<WheelCollider> colliders, List<Transform> wheelMeshes, List<Transform> suspensionParents)
- {
- wheels = new List<WheelClass>();
- for (int i = 0; i < colliders.Count; i++)
- {
- wheels.Add(new WheelClass(colliders[i]));
- if (i < wheelMeshes.Count)
- {
- wheels[i].wheelMesh = wheelMeshes[i];
- wheels[i].useRotation = true;
- }
- if (i < suspensionParents.Count)
- {
- wheels[i].suspensionParent = suspensionParents[i];
- wheels[i].useSuspension = true;
- }
- }
- }
- public void Create(WheelCollider collider, Transform wheelMesh, Transform suspensionParent)
- {
- wheels = new List<WheelClass>();
- wheels.Add(new WheelClass(collider, wheelMesh, suspensionParent));
- }
- public bool enabled
- {
- get
- {
- return _enabled;
- }
- set
- {
- _enabled = value;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.enabled = value;
- }
- }
- }
- public float brakeTorque
- {
- get
- {
- return _brakeTorque;
- }
- set
- {
- _brakeTorque = value;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.brakeTorque = value;
- }
- }
- }
- public float motorTorque
- {
- get
- {
- return _motorTorque;
- }
- set
- {
- _motorTorque = value;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.motorTorque = value;
- }
- }
- }
- public void updateSpring(float spring, float damper, float targetPosition)
- {
- JointSpring jointSpring = new JointSpring();
- jointSpring.spring = spring;
- jointSpring.damper = damper;
- jointSpring.targetPosition = targetPosition;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.suspensionSpring = jointSpring;
- }
- }
- public float suspensionDistance
- {
- get
- {
- return _suspensionDistance;
- }
- set
- {
- _suspensionDistance = value;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.suspensionDistance = value;
- }
- }
- }
- public float mass
- {
- get
- {
- return _mass;
- }
- set
- {
- _mass = value;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.mass = value;
- }
- }
- }
- public float radius
- {
- get
- {
- return _radius;
- }
- set
- {
- _radius = value;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.radius = value;
- }
- }
- }
- public void updateWheelFriction()
- {
- WheelFrictionCurve forwardFriction = new WheelFrictionCurve();
- forwardFriction.extremumSlip = forwardsExtremumSlip;
- forwardFriction.extremumValue = forwardsExtremumValue;
- forwardFriction.asymptoteSlip = forwardsAsymptoteSlip;
- forwardFriction.asymptoteValue = forwardsAsymptoteValue;
- forwardFriction.stiffness = forwardStiffness;
- WheelFrictionCurve sidewaysFriction = new WheelFrictionCurve();
- sidewaysFriction.extremumSlip = sidewaysExtremumSlip;
- sidewaysFriction.extremumValue = sidewaysExtremumValue;
- sidewaysFriction.asymptoteSlip = sidewaysAsymptoteSlip;
- sidewaysFriction.asymptoteValue = sidewaysAsymptoteValue;
- sidewaysFriction.stiffness = sidewaysStiffness;
- for (int i = 0; i < wheels.Count; i++)
- {
- wheels[i].wheelCollider.forwardFriction = forwardFriction;
- wheels[i].wheelCollider.sidewaysFriction = sidewaysFriction;
- }
- }
- }
- //******************************************
- public class aircraftParkDist : PartModule
- {
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Park Dist: "), UI_FloatRange(minValue = 0f, maxValue = 1.2f, stepIncrement = 0.1f)]
- public float dockDistance = 0.9f;
- private bool doItOnce = true;
- public Transform affectClawNode;
- public void FixedUpdate()
- {
- if (doItOnce == true)
- {
- try
- {
- affectClawNode = this.part.FindModelTransform("clawLoc");
- doItOnce = false;
- }
- catch
- {
- print("Problem locating clawLoc!");
- }
- }
- if (affectClawNode != null)
- {
- affectClawNode.localPosition = new Vector3(-dockDistance, 0f, 0f);
- }
- }
- }
- //*************************************
- public class IDpartTurner : PartModule
- {
- [KSPField]
- public string targetPartObject = "turnEmpty";
- [KSPField]
- public float rotationDirectionX = 0f;
- [KSPField]
- public float rotationDirectionY = 0f;
- [KSPField]
- public float rotationDirectionZ = 1f;
- [KSPField]
- public float defaultRotationX = 0f;
- [KSPField]
- public float defaultRotationY = 0f;
- [KSPField]
- public float defaultRotationZ = 0f;
- [KSPField(guiActive = false, guiActiveEditor = true, guiName = "Steering Multiplier", isPersistant = true)]
- public float steerMultiplier = 10f;
- [KSPField]
- public float steerMaxSpeed = 18f;
- [KSPField]
- public bool speedAdjustedSteering = true;
- [KSPField]
- public float speedAdjustedSteeringMinimumMultiplier = 0.1f;
- [KSPField(guiActive = true, guiActiveEditor = true, guiName = "Steering", isPersistant = true)]
- public bool steeringEnabled = false;
- [KSPField(guiActive=false, guiName="use QE, not AD", isPersistant=true)]
- public bool altInputModeEnabled = false;
- [KSPField(guiActive = true, guiActiveEditor = true, guiName = "Reverse Steering", isPersistant = true)]
- public bool reversedInput = false;
- [KSPField(guiActive = false, guiName = "Ignore Trim", isPersistant = true)]
- public bool ignoreTrim = true;
- [KSPField]
- public bool useWheelSteeringAxis = true;
- private Vector3 currentTrim = new Vector3(0,0,0);
- private Vector3 currentRotation = new Vector3(0, 0, 0);
- private Vector3 steeringInput;
- private Transform partTransform;
- [KSPAction("Toggle Steering")]
- public void toggleSteeringAction(KSPActionParam param)
- {
- toggleSteering();
- }
- [KSPAction("Invert Steering")]
- public void toggleInvertAction(KSPActionParam param)
- {
- reversedInput = !reversedInput;
- }
- [KSPEvent(name = "toggleSteering", active = true, guiActive = false, guiActiveEditor = true, guiName = "Toggle Steering")]
- public void toggleSteering()
- {
- steeringEnabled = !steeringEnabled;
- }
- [KSPEvent(name = "toggleAltInputMode", active = false, guiActive = false, guiName = "QE or AD to steer")]
- public void toggleAltInputMode()
- {
- altInputModeEnabled = !altInputModeEnabled;
- }
- [KSPEvent(name = "toggleIgnoreTrim", active = false, guiActive = false, guiName = "Toggle Ignore trim")]
- public void toggleIgnoreTrim()
- {
- ignoreTrim = !ignoreTrim;
- }
- [KSPEvent(name = "toggleReverseInput", active = true, guiActive = false, guiActiveEditor = true, guiName = "Toggle Reverse Steering")]
- public void toggleReverseInput()
- {
- reversedInput = !reversedInput;
- }
- [KSPEvent(name = "increaseSteering", active = true, guiActive = false, guiActiveEditor = true, guiName = "Increase Steering")]
- public void increaseSteering()
- {
- steerMultiplier += 1f;
- if (steerMultiplier > 90f) steerMultiplier = 90f;
- }
- [KSPEvent(name = "decreaseSteering", active = true, guiActive = false, guiActiveEditor = true, guiName = "Decrease Steering")]
- public void decreaseSteering()
- {
- steerMultiplier -= 1;
- if (steerMultiplier < 1f) steerMultiplier = 1f;
- }
- [KSPEvent(name = "ToggleSpeedAdjustedSteering", active = true, guiActive = false, guiActiveEditor = true, guiName = "Dynamic Steering")]
- public void toggleSpeedAdjustedSteeringEvent()
- {
- speedAdjustedSteering = !speedAdjustedSteering;
- }
- public void steerPart(float direction)
- {
- float steerModifier = 1f;
- if (speedAdjustedSteering)
- {
- steerModifier = Mathf.Max(speedAdjustedSteeringMinimumMultiplier, -(((float)vessel.horizontalSrfSpeed - steerMaxSpeed) / steerMaxSpeed));
- }
- currentRotation.x = steerMultiplier * rotationDirectionX * direction * steerModifier;
- currentRotation.y = steerMultiplier * rotationDirectionY * direction * steerModifier;
- currentRotation.z = steerMultiplier * rotationDirectionZ * direction * steerModifier;
- }
- private void setPartRotation()
- {
- if (partTransform != null)
- partTransform.localRotation = Quaternion.Euler(currentRotation);
- }
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- partTransform = part.FindModelTransform(targetPartObject);
- if (useWheelSteeringAxis)
- {
- Events["toggleIgnoreTrim"].guiActive = false;
- Events["toggleAltInputMode"].guiActive = false;
- Fields["altInputModeEnabled"].guiActive = false;
- Fields["ignoreTrim"].guiActive = false;
- }
- }
- public override void OnUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight || !vessel.isActiveVessel) return;
- FlightCtrlState ctrl = vessel.ctrlState;
- int reverseModifier = 1;
- if (useWheelSteeringAxis)
- {
- steeringInput.x = vessel.ctrlState.wheelSteer + vessel.ctrlState.wheelSteerTrim;
- }
- else
- {
- if (altInputModeEnabled)
- {
- steeringInput.x = ctrl.roll;
- if (ignoreTrim) steeringInput.x -= ctrl.rollTrim;
- }
- else
- {
- steeringInput.x = ctrl.yaw;
- if (ignoreTrim) steeringInput.x -= ctrl.yawTrim;
- }
- }
- if (reversedInput)
- {
- reverseModifier = -1;
- }
- if (steeringEnabled)
- {
- steerPart(steeringInput.x * reverseModifier);
- }
- else steerPart(0);
- setPartRotation();
- }
- }
- //***************************************
- public class IDice : PartModule
- {
- //ID-ICE InfiniteDice Internal Combustion Engine - Module for KSP. Mod, code, models, textures are shared under
- //Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - You are free to:Share — copy and redistribute the material in any medium or format - Ypu can modify files for your personal use.
- //If you remix, transform, or build upon the material, you may not distribute the modified material. You may not use the material for commercial purposes.
- //A note on the license - I have dozens of hours in this and other mods, which I share out to the community for no fees. Id you like the mod please share your thoughts/images/videos on the KSP forum thread!
- //Thanks for using this mod.
- //ID ICE is not perfect! I don't claim this is a totally realistic simulation of how a real engine works. My overall goal was to experiment with making an alternative engine module for KSP.
- //Secondly to support and inspire the community to take more advantage of EVA activities. Have fun!
- [KSPField]
- public int numOfCyls = 1; // how many cylinders does the engine have, each cylinder produces a fraction of the enginePower.
- [KSPField]
- public float engineDisplacement = 17.3f; // in litres - not in use yet. to convert to cubic inches * 61.0237
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Performance Multi"), UI_FloatRange(minValue = 5f, maxValue = 20f, stepIncrement = 0.5f)]
- public float enginePerformanceMulti = 10f; // total engine power rating - the power it generates will NOT be equal to this but is only based on this.
- [KSPField(isPersistant = true)]
- public float origEngPerformance = 0f;
- [KSPField]
- public int camTime = 10; // the degrees of one rotation that the cylinder produces power numOfCyls * camTime should NOT EXCEED 360!!!
- [KSPField]
- public float engineRedline = 4500f; // the max permitted speed without incurring heat and wear losses
- [KSPField]
- public float engineIdleSpeed = 600f; // the speed the engine must be turning in order to maintain a run state, running below this speed will increase the chance of stall.
- [KSPField]
- public float engineHeatup = 1f; //1 is normal... some smaller engines need a much higher multiplier
- [KSPField]
- public string resourceType = "LiquidFuel"; // the fuel the engine runs on
- [KSPField(guiActive = true, guiName = "RPM: ")]
- public float currentRPM = 0f;
- [KSPField(guiActive = true, isPersistant = true)]
- public bool ctrlEngine = true;
- [KSPField]
- public bool coupleOutput = false;
- // Snjo can get/set to this for the throttle gui********************************************************************************************MULTI THROTTLE STUFF********
- public float throttleActual;// this is either the KSP throttle or the multi-gui throttle see checkThrottle()
- [KSPField(isPersistant = true, guiActiveEditor = false, guiActive = true, guiName = "Engine Throttle: "), UI_FloatRange(minValue = 0f, maxValue = 1f, stepIncrement = 0.1f)]
- public float guiThrottle = 0f;
- public float lastGoodThrottle = 0f; // to hold the last throttle setting when pilot leaves plane... why? just because!
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Gui Throttle"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool useMultiThrottle = false; // change to true in cfg to enable snjos multi-throttle gui controls.
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "W Throttle"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool useWThrottle = false; // change to true in cfg to enable W tap throttle.
- //********************************************************************************************************************************************END MULTI THROTTLE********
- public float ignitionTimer = 0.01f;
- public float ignCooldown = 0.01f;
- public float failureTimer = 30f;
- public float failureCooldown = 30f;
- public float animateTimer = 1f;
- public float animateCooldown = 1f;
- public bool fixOngoing = false;
- public float doneTime = 0f;
- public float startTime = 0f;
- public float fixTime = 0f;
- public string jobName = "nil";
- public bool takeOilOnce = false;
- public IDdDrive getICEdDrive;
- public float idleForceLoss = 0.1f;
- public int atRotation = 0; // what is the current rotation of the engine crank? determines where power and idle force happens
- public int chokeSet = 0; //0 none, 1 half, 2 full... //implement for r2.
- public bool starterOn = false;
- public float starterCond = 100f;
- public bool fuelOn = false;
- public bool elecOn = false;
- public bool carbHeat = false; //implement for r2
- public float carbIce = 1f; // 0 to 1 : 1 being clear of ice and no power loss. The floor for this is 0.5f
- public bool dmgOilLeak = false;
- public bool dmgMissFire = false;
- public bool dmgFuelCutout = false;
- public bool dmgOutOfWhack = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Prop Pitch: "), UI_FloatRange(minValue = -1f, maxValue = 1f, stepIncrement = 1f)]
- public float propPitch = 1f; // 1 is 100% and is normal, 0 is neutral, -1 is reverse.
- public float pitchModifier = 1f;
- public bool togglePitch = false;
- [KSPField]
- public bool remoteCharger = false; // does it charge batteries within a set distance?
- public float remChargeDist = 0f;
- public bool madeCharge = false;
- [KSPField]
- public bool variPitch = false;
- [KSPField]
- public string animatedPart = "none";
- [KSPField]
- public string sfxEngineDrone = "IDiCEr1/Sounds/IDiceE4"; //constant sound loop
- [KSPField]
- public string sfxEngineBackF = "IDiCEr1/Sounds/IDiceBf1"; //constant sound loop
- [KSPField]
- public string sfxEngineGroup = "IDiCEr1/Sounds/IDiceE2"; //idle sound loop
- [KSPField]
- public string sfxEngineStart = "IDiCEr1/Sounds/IDiceStart"; //start sound one time
- [KSPField]
- public string sfxSupercharger = "IDiCEr1/Sounds/IDSuperC"; //start sound one time
- [KSPField]
- public string sfxFail = "IDiCEr1/Sounds/IDiceFail"; //spun bearing sound
- public float propScalePower = 0f;
- public float coldLoss = 0f;
- [KSPField(isPersistant = true, guiActive = true, guiName = "State: ")]
- public string runState = "Off"; // Off, Starting, Stalled, Running, Overheated, Seized, Dead
- public float lastCylForce;
- public int lastCylToFire;
- [KSPField(isPersistant = true, guiActive = false, guiName = "Ignition: ")]
- public float sparkEff = 1f; // 1 is new, as it gets used this will diminish till finally the engine will run like crap
- [KSPField(isPersistant = true, guiActive = false, guiName = "Air Filter: ")]
- public float airEff = 1f; // 1 is new, as it gets used this will diminish till finally the engine will run like crap
- public float wearRate = 0.0001f; // this is the overall wear multiplier.
- [KSPField]
- public float fuelAirMix = 0.066666f; // rate at which the engine will consume fuel enter Ratio....
- public float actualAirDensity;
- public float airNeeded; // formula will be CubicInches * current rpm * Efficiency (airfilter + atmospheric density/2) / 3456 == cubic feet per minute so * by 0.000471947443 for cubicM/sec...
- [KSPField(isPersistant = true, guiActive = true, guiName = "Oil Level: ")]
- public float oilLevel = 100f; //%
- [KSPField(isPersistant = true, guiActive = false, guiName = "Oil Condition: ")]
- public float oilCond = 100f; //%
- [KSPField]
- public float oilCapacity = 50f; //litres
- [KSPField(guiActive = true, guiName = "Oil Temp: ")]
- public float oilTemp = 0f; // this will be ambient air temp when off and will cool to this.
- public float oilMaxTemp = 260f;// celcius; after this chance of oilCond loss is higher.
- public float carbTemp = 30f; // this will be ambient air temp.
- public float maxEngTemp = 200f; //celcius
- [KSPField]
- public bool airCooled = true;
- [KSPField]
- public float coolantCapacity = 10f; //litres
- public float coolantTemp = 0f; //litres
- public float engTemp = 0f; //this will be ambient air temp when off. and will cool to this
- public float overHeatMod = 1.0125f; // heat and wear rates are increased!
- public float coolingEff = 0.025f; //% loss of heat when operating under max rpm and with at least 50% oil level
- public int secureRandom; // storage for a random number.
- public List<IDliqCool> getAllLCool = new List<IDliqCool>();
- public Transform iceForceTransform;
- public Transform propellerLocation;
- public Transform[] exh;
- public Vector3 thrustDirection;
- public GameObject exhaustFX1;
- public GameObject oilBurningFX;
- public Light lightOne;
- public GameObject oilBurnTrailFX;
- public FXGroup soundGroup, soundStart, soundFail, soundDrone, soundSuperC, soundBackF;
- private Transform animateTransform;
- private Transform animateDefaultTransform;
- private bool firstRun = true;
- [KSPField(guiActive = false, isPersistant = true)]
- public bool doItOnce = true;
- #region Export Direct Drive
- [KSPField]
- public bool hasDirectOutput = false;
- #endregion
- #region Superchargers
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Supercharged"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool isSupercharged = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "TwoStage"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool isTwoStageAuto = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Low Boost"), UI_FloatRange(minValue = 1.05f, maxValue = 1.7f, stepIncrement = 0.05f)]
- public float boostLowMultiplier = 1.1f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "High Boost"), UI_FloatRange(minValue = 1.1f, maxValue = 1.7f, stepIncrement = 0.05f)]
- public float boostHighMultiplier = 1.45f;
- [KSPField]
- public double twoStageTripAlt = 3000f;
- public float currentBoostMulti = 1.1f;
- #endregion
- #region Experimental Thrust Averaging
- public Transform iceAvgThrustPosition;
- [KSPField]
- public bool useThrustAveraging = false;
- public Transform actualThrustPosition;
- #endregion
- #region KerbalStuff
- public Kerbal callKerbalStats;
- public KerbalEVA findKerbal;
- public string lastKerbalName;
- public float ourKerbalsStupid = 0f;
- public bool ourKerbalIsBadass = false;
- public float ourKerbalCourage = 0f;
- #endregion
- public bool checkOnce = true;
- [KSPEvent(guiName = "Toggle Prop Pitch", guiActive = false, guiActiveUnfocused = false, unfocusedRange = 5f)]
- public void setPitch()
- {
- if (variPitch != true)
- {
- togglePitch = true;
- }
- }
- [KSPEvent(name = "autoIgnition", active = true, guiActive = true, guiName = "Auto Start")]
- public void letsAutoStart()
- {
- if (ctrlEngine == true)
- {
- if (elecOn == false)
- {
- if (sparkEff > 0f)
- {
- elecOn = true;
- print("Electricals On!");
- }
- else if (sparkEff <= 0f)
- {
- sparkEff = 0f;
- elecOn = false;
- print("Electrical needs fixing... cleaning time!");
- }
- }
- if (fuelOn == false)
- {
- if (sparkEff > 0f)
- {
- fuelOn = true;
- print("Fuel System On!");
- }
- else if (sparkEff <= 0f)
- {
- print("Plugs are Fouled, clean them!");
- }
- }
- if (starterOn == false)
- {
- if (starterCond >= 1f && elecOn == true && runState != "Seized" && runState != "Dead")
- {
- if (runState == "Off" || runState == "Stalled")
- {
- soundStart.audio.Play();
- starterOn = true;
- print("Starter Engaged!");
- }
- else if (runState == "Running" || runState == "Overheated" || runState == "Starting")
- {
- starterCond = starterCond - (UnityEngine.Random.Range(1f, 5f));
- }
- }
- else if (starterCond < 1f || elecOn == false)
- {
- print("Starter must be damaged, or Electric Power is off!");
- }
- }
- }
- }
- [KSPEvent(name = "controlENG", active = true, guiActive = true, guiName = "Control Engine")]
- public void letsControlEngine()
- {
- if (ctrlEngine == false)
- {
- ctrlEngine = true;
- }
- else if (ctrlEngine == true)
- {
- ctrlEngine = false;
- }
- }
- [KSPEvent(name = "shutdownENG", active = true, guiActive = true, guiName = "Shutdown Engine")]
- public void letsShutdownEngine()
- {
- if (elecOn == true)
- {
- elecOn = false;
- fuelOn = false;
- runState = "Off";
- }
- }
- [KSPEvent(name = "toggleThrustAvg", active = true, guiActive = false, guiName = "Average Thrust Position")]
- public void letsAverageThrust()
- {
- if (useThrustAveraging == false)
- {
- print("Thrust Averaging On");
- useThrustAveraging = true;
- }
- else if (useThrustAveraging == true)
- {
- print("Thrust Averaging Off");
- useThrustAveraging = false;
- }
- }
- [KSPEvent(name = "toggleCarbHeat", active = true, guiActive = false, guiName = "Carb Heat")]
- public void letsHeatCarbs()
- {
- if (carbHeat == false)
- {
- print("Carb Heat On");
- carbHeat = true;
- }
- else if (carbHeat == true)
- {
- print("Carb Heat Off");
- carbHeat = false;
- }
- }
- [KSPAction("Auto Start Engine")]
- public void doAutoStartEngine(KSPActionParam param)
- {
- letsAutoStart();
- }
- #region EVA Repair/Inspection Options
- [KSPEvent(active = true, guiName = "Inspect Engine", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 4f)]
- public void inspectEngine()
- {
- if (fixOngoing == false)
- {
- jobName = "inspect";
- fixTime = 15 * (1f + ourKerbalsStupid);
- startTime = Time.time;
- print(startTime + " is the time the job started.");
- ScreenMessages.PostScreenMessage(new ScreenMessage("Okay now... let me have a look!", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- doneTime = fixTime + startTime;
- }
- }
- [KSPEvent(active = true, guiName = "Clean Filters", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 4f)]
- public void fixFilters()
- {
- if (fixOngoing == false)
- {
- jobName = "airfilter";
- fixTime = 10f * (1f + ourKerbalsStupid);
- startTime = Time.time;
- print(startTime + " is the time the job started.");
- ScreenMessages.PostScreenMessage(new ScreenMessage("It will take me a few moments to fix the filter...", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- doneTime = fixTime + startTime;
- }
- }
- [KSPEvent(active = true, guiName = "Clean Electrical", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 4f)]
- public void fixElec()
- {
- if (fixOngoing == false)
- {
- jobName = "electrical";
- fixTime = 15f * (1f + ourKerbalsStupid);
- startTime = Time.time;
- print(startTime + " is the time the job started.");
- ScreenMessages.PostScreenMessage(new ScreenMessage("Hopefully I won't get a shock working on this electrical system...", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- doneTime = fixTime + startTime;
- }
- }
- [KSPEvent(active = true, guiName = "Change Oil", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 4f)]
- public void fixOil()
- {
- if (fixOngoing == false)
- {
- jobName = "oilservice";
- fixTime = 20f * (1f + ourKerbalsStupid);
- startTime = Time.time;
- print(startTime + " is the time the job started.");
- ScreenMessages.PostScreenMessage(new ScreenMessage("Why do I get stuck changing this oil?...", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- takeOilOnce = true;
- doneTime = fixTime + startTime;
- }
- }
- [KSPEvent(active = true, guiName = "Fix Engine", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 4f)]
- public void fixState()
- {
- if (fixOngoing == false)
- {
- jobName = "engine";
- fixTime = 45f * (1f + ourKerbalsStupid);
- startTime = Time.time;
- print(startTime + " is the time the job started.");
- ScreenMessages.PostScreenMessage(new ScreenMessage("This might take a while! Please be patient! ...and quiet!...", fixTime, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = true;
- takeOilOnce = true;
- doneTime = fixTime + startTime;
- }
- }
- #endregion
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- propellerLocation = base.part.FindModelTransform("propeller");
- iceForceTransform = base.part.FindModelTransform("thrustTransform");
- actualThrustPosition = iceForceTransform;
- iceAvgThrustPosition = iceForceTransform;
- #region find cylinder exhaust ports
- try
- {
- exh = base.part.FindModelTransforms("exh");
- }
- catch
- {
- print("Problem locating exhausts");
- }
- if (exh.Count() > 0)
- {
- print("Found " + exh.Count() + " Exhaust Ports");
- }
- #endregion
- #region visualFX
- if (exhaustFX1 == null || exhaustFX1.activeInHierarchy == false)
- {
- try
- {
- exhaustFX1 = GameDatabase.Instance.GetModel("IDiCEr1/Effects/ExhaustFX/model");
- }
- catch
- {
- print("Problem locating exhFX");
- }
- if (exhaustFX1 != null)
- {
- exhaustFX1.SetActive(false);
- exhaustFX1.transform.position = this.part.transform.position;
- exhaustFX1.transform.parent = this.part.transform;
- exhaustFX1.gameObject.layer = 0;
- }
- }
- oilBurningFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_smokeTrail_medium"));
- oilBurningFX.particleEmitter.emit = false;
- oilBurningFX.transform.parent = this.part.transform;
- oilBurningFX.transform.localPosition = new Vector3(0, 0, 1.25f);
- oilBurningFX.transform.localRotation = this.part.transform.rotation;
- oilBurningFX.particleEmitter.useWorldSpace = false;
- oilBurningFX.particleEmitter.minSize = 0.85f;
- oilBurningFX.particleEmitter.maxSize = 1.3f;
- oilBurningFX.particleEmitter.localVelocity = new Vector3(0, 0, 2f);
- oilBurningFX.particleEmitter.minEnergy = 0.35f;
- oilBurningFX.particleEmitter.maxEnergy = 0.65f;
- oilBurningFX.particleEmitter.minEmission = 120f;
- oilBurningFX.particleEmitter.angularVelocity = 0.0f;
- oilBurningFX.particleEmitter.rndRotation = false;
- oilBurningFX.particleEmitter.rndAngularVelocity = 0f;
- oilBurningFX.particleEmitter.rndVelocity = new Vector3(0, 0, 0);
- lightOne = oilBurningFX.AddComponent<Light>();
- lightOne.color = Color.red;
- lightOne.type = LightType.Point;
- lightOne.range = 1.25f;
- lightOne.enabled = false;
- oilBurnTrailFX = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_smokeTrail_light"));
- oilBurnTrailFX.particleEmitter.emit = false;
- oilBurnTrailFX.transform.parent = propellerLocation;
- oilBurnTrailFX.transform.localPosition = new Vector3(0, 0, 0.2f);
- oilBurnTrailFX.transform.localRotation = propellerLocation.rotation;
- oilBurnTrailFX.particleEmitter.useWorldSpace = true;
- oilBurnTrailFX.particleEmitter.minSize = 1f;
- oilBurnTrailFX.particleEmitter.maxSize = 6f;
- oilBurnTrailFX.particleEmitter.localVelocity = new Vector3(0, 0, 1.5f);
- oilBurnTrailFX.particleEmitter.maxEnergy = 10f;
- oilBurnTrailFX.particleEmitter.minEmission = 3000f;
- oilBurnTrailFX.particleEmitter.angularVelocity = 0.01f;
- oilBurnTrailFX.particleEmitter.rndRotation = false;
- #endregion
- #region Sound FX
- soundDrone.audio = gameObject.AddComponent<AudioSource>();
- soundGroup.audio = gameObject.AddComponent<AudioSource>();
- soundStart.audio = gameObject.AddComponent<AudioSource>();
- soundFail.audio = gameObject.AddComponent<AudioSource>();
- soundSuperC.audio = gameObject.AddComponent<AudioSource>();
- soundBackF.audio = gameObject.AddComponent<AudioSource>();
- if (soundDrone.audio != null)
- {
- soundDrone.audio.volume = GameSettings.SHIP_VOLUME;
- soundDrone.audio.rolloffMode = AudioRolloffMode.Linear;
- soundDrone.audio.dopplerLevel = 0f;
- soundDrone.audio.panLevel = 1f;
- soundDrone.audio.clip = GameDatabase.Instance.GetAudioClip(sfxEngineDrone);
- soundDrone.audio.loop = true;
- soundDrone.audio.playOnAwake = false;
- soundDrone.audio.priority = 1;
- }
- if (soundGroup.audio != null)
- {
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME * 0.25f;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip(sfxEngineGroup);
- soundGroup.audio.loop = true;
- soundGroup.audio.playOnAwake = false;
- soundGroup.audio.priority = 2;
- }
- if (soundStart.audio != null)
- {
- soundStart.audio.volume = GameSettings.SHIP_VOLUME;
- soundStart.audio.rolloffMode = AudioRolloffMode.Linear;
- soundStart.audio.dopplerLevel = 0f;
- soundStart.audio.panLevel = 1f;
- soundStart.audio.clip = GameDatabase.Instance.GetAudioClip(sfxEngineStart);
- soundStart.audio.loop = false;
- soundStart.audio.playOnAwake = false;
- soundStart.audio.priority = 3;
- }
- if (soundFail.audio != null)
- {
- soundFail.audio.volume = GameSettings.SHIP_VOLUME * 0.025f;
- soundFail.audio.rolloffMode = AudioRolloffMode.Linear;
- soundFail.audio.dopplerLevel = 0f;
- soundFail.audio.panLevel = 1f;
- soundFail.audio.clip = GameDatabase.Instance.GetAudioClip(sfxFail);
- soundFail.audio.loop = true;
- soundFail.audio.playOnAwake = false;
- soundFail.audio.priority = 5;
- }
- if (soundSuperC.audio != null)
- {
- soundSuperC.audio.volume = GameSettings.SHIP_VOLUME;
- soundSuperC.audio.rolloffMode = AudioRolloffMode.Linear;
- soundSuperC.audio.dopplerLevel = 0f;
- soundSuperC.audio.panLevel = 1f;
- soundSuperC.audio.clip = GameDatabase.Instance.GetAudioClip(sfxSupercharger);
- soundSuperC.audio.loop = true;
- soundSuperC.audio.playOnAwake = false;
- soundSuperC.audio.priority = 4;
- }
- if (soundBackF.audio != null)
- {
- soundBackF.audio.volume = GameSettings.SHIP_VOLUME;
- soundBackF.audio.rolloffMode = AudioRolloffMode.Linear;
- soundBackF.audio.dopplerLevel = 0f;
- soundBackF.audio.panLevel = 1f;
- soundBackF.audio.clip = GameDatabase.Instance.GetAudioClip(sfxEngineBackF);
- soundBackF.audio.loop = false;
- soundBackF.audio.playOnAwake = false;
- soundBackF.audio.priority = 5;
- }
- #endregion
- }
- public void Update()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (this.vessel == FlightGlobals.ActiveVessel && ctrlEngine == true)
- {
- if (hasDirectOutput == true && useMultiThrottle == false && useWThrottle == true)
- {
- float throttlePos = FlightInputHandler.state.mainThrottle;
- if (FlightInputHandler.state.mainThrottle < 0.1f)
- {
- FlightInputHandler.state.mainThrottle = throttlePos += 0.125f * Time.deltaTime;
- }
- if (Input.GetKey(KeyCode.W) && FlightInputHandler.state.mainThrottle < guiThrottle)
- {
- FlightInputHandler.state.mainThrottle = throttlePos += 0.125f * Time.deltaTime;
- }
- else if (!Input.GetKey(KeyCode.W) && FlightInputHandler.state.mainThrottle > 0.1f)
- {
- FlightInputHandler.state.mainThrottle = throttlePos -= 0.1f * Time.deltaTime;
- }
- if (Input.GetKey(KeyCode.S) && FlightInputHandler.state.mainThrottle > 0.1f)
- {
- FlightInputHandler.state.mainThrottle = throttlePos -= 0.25f * Time.deltaTime;
- }
- if (Input.GetKeyDown(KeyCode.LeftControl) && useWThrottle == true)
- {
- useWThrottle = false;
- }
- }
- #region Toggle pitch
- if (togglePitch == true && variPitch == false)
- {
- if (propPitch == 1f && togglePitch == true)
- {
- propPitch = -1f;
- togglePitch = false;
- pitchModifier = 1f;
- }
- if (propPitch == -1f && togglePitch == true)
- {
- propPitch = 0f;
- togglePitch = false;
- pitchModifier = 1f;
- }
- if (propPitch == 0f && togglePitch == true)
- {
- propPitch = 1f;
- togglePitch = false;
- pitchModifier = 1f;
- }
- }
- else if(togglePitch == false && variPitch == true)
- {
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.KeypadPlus))
- {
- if (propPitch < 1f)
- {
- propPitch = propPitch + 0.1f;
- pitchModifier = propPitch;
- }
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.KeypadMinus))
- {
- if (propPitch > -1f)
- {
- propPitch = propPitch - 0.1f;
- pitchModifier = propPitch;
- }
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.KeypadDivide))
- {
- if (propPitch != 0f)
- {
- propPitch = 0f;
- pitchModifier = 1f;
- }
- }
- }
- #endregion
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.S))
- {
- if (starterOn == false)
- {
- if (starterCond >= 1f && elecOn == true && runState != "Seized" && runState != "Dead")
- {
- if (runState == "Off" || runState == "Stalled")
- {
- soundStart.audio.Play();
- starterOn = true;
- print("Starter Engaged!");
- }
- else if (runState == "Running" || runState == "Overheated" || runState == "Starting")
- {
- starterCond = starterCond - (UnityEngine.Random.Range(1f, 5f)); //damage the starter!
- }
- }
- else if (starterCond < 1f || elecOn == false)
- {
- print("Starter must be damaged, or Electric Power is off!");
- }
- }
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.F))
- {
- if (fuelOn == false)
- {
- if (sparkEff > 0f)
- {
- fuelOn = true;
- print("Fuel System On!");
- }
- else if (sparkEff <= 0f)
- {
- print("Plugs are Fouled, clean them!");
- }
- }
- else if (fuelOn == true)
- {
- fuelOn = false;
- }
- }
- if (Input.GetKey(KeyCode.RightShift) && Input.GetKeyDown(KeyCode.E))
- {
- if (elecOn == false)
- {
- if (sparkEff > 0f)
- {
- elecOn = true;
- print("Electricals On!");
- }
- else if (sparkEff <= 0f)
- {
- sparkEff = 0f;
- elecOn = false;
- print("Electrical needs fixing... cleaning time!");
- }
- }
- else if (elecOn == true)
- {
- elecOn = false;
- }
- }
- }
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsEditor)
- {
- if (hasDirectOutput == false)
- {
- Fields["useWThrottle"].guiActiveEditor = false;
- }
- }
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (doItOnce == true)
- {
- origEngPerformance = enginePerformanceMulti;
- doItOnce = false;
- }
- if (firstRun == true)
- {
- if (animatedPart != "none")
- {
- print("Running the animatePart ICE code");
- animateTransform = part.FindModelTransform(animatedPart);
- if (animateTransform != null)
- {
- animateDefaultTransform = new GameObject().transform;
- animateDefaultTransform.localRotation = animateTransform.localRotation;
- animateDefaultTransform.localPosition = animateTransform.localPosition;
- print("animatePart found and set!");
- }
- getICEdDrive = this.vessel.FindPartModulesImplementing<IDdDrive>().FirstOrDefault();
- }
- if (hasDirectOutput == false)
- {
- Fields["useWThrottle"].guiActive = false;
- }
- getAllLCool = this.vessel.FindPartModulesImplementing<IDliqCool>();
- firstRun = false;
- }
- if (dmgOutOfWhack == true)
- {
- persistantRunRough();
- }
- #region Experimental Thrust Averaging
- actualThrustPosition.position = iceForceTransform.position;
- actualThrustPosition.rotation = iceForceTransform.rotation;
- if (useThrustAveraging == true)
- {
- iceAvgThrustPosition.position = Vector3.Lerp(this.vessel.transform.position, iceForceTransform.position, 0.0000000001f);
- }
- #endregion
- #region Random Failure Call
- failureTimer -= Time.deltaTime;
- if (failureTimer <= 0 && FlightGlobals.ActiveVessel == this.vessel)
- {
- failureTimer = failureCooldown;
- checkRandomFailure();
- }
- #endregion
- if (lightOne.enabled == true)
- {
- int randFlicker = rndNumber.rndRoll(1, 101);
- float randIntensity = (float)rndNumber.rndRoll(1, 3);
- if (randFlicker <= 18)
- {
- lightOne.intensity = randIntensity;
- }
- else lightOne.intensity = 0f;
- }
- if (FlightGlobals.ActiveVessel.isEVA == true)
- {
- ProtoCrewMember getStats = FlightGlobals.ActiveVessel.GetVesselCrew().FirstOrDefault();
- if (lastKerbalName != getStats.name) // only update stats if the kerbal isn't the same as the last kerbal we checked.
- {
- checkKerbal();
- }
- }
- #region INSPECTION CHECK
- if (fixOngoing == true && doneTime < Time.time && jobName == "inspect")
- {
- print("Job completed in... " + fixTime + " seconds, at" + Time.time);
- fixOngoing = false;
- jobName = "nil";
- float messageDisplayTime = 10f;
- int checkNumSystems = 3;
- bool check1 = false;
- bool check2 = false;
- bool check3 = false;
- for (int i = 0; i < checkNumSystems; i++)
- {
- if (i == 0) check1 = true;
- if (i == 1) check2 = true;
- if (i == 2) check3 = true;
- float randomInspect = (float)rndNumber.rndDouble();
- float inspectRating = 1f;
- float kerbalSmart = 1f - ourKerbalsStupid;
- if (randomInspect <= ((inspectRating + kerbalSmart) / 2) && check1 == true) //******************AIRFILTER
- {
- print("We made the inspection roll!");
- if (airEff >= 0.9f) ScreenMessages.PostScreenMessage(new ScreenMessage("Air Filter looks brand new!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (airEff >= 0.5f && airEff < 0.9f) ScreenMessages.PostScreenMessage(new ScreenMessage("Air Filter is used but still good!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (airEff > 0.25f && airEff < 0.5f) ScreenMessages.PostScreenMessage(new ScreenMessage("Air Filter is dirty! I wouldn't fly around the block with that thing.", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (airEff <= 0.2f) ScreenMessages.PostScreenMessage(new ScreenMessage("This is not an air filter, it's totally destroyed!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- check1 = false;
- }
- else if (randomInspect > ((inspectRating + kerbalSmart) / 2) && check1 == true)
- {
- print("Kerbal makes mistake doing inspection!"); // AIR filter Inspection could be right could be wrong who knows!
- float randomBS = UnityEngine.Random.Range(0f, 4f);
- if (randomBS <= 1f) ScreenMessages.PostScreenMessage(new ScreenMessage("Air Filter looks brand new!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 2f && randomBS > 1f) ScreenMessages.PostScreenMessage(new ScreenMessage("Air Filter is used but still good!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 3f && randomBS > 2f) ScreenMessages.PostScreenMessage(new ScreenMessage("Air Filter is dirty! I wouldn't fly around the block with that thing.", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 4f && randomBS > 3f) ScreenMessages.PostScreenMessage(new ScreenMessage("This is not an air filter, it's totally destroyed!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- check1 = false;
- }
- if (randomInspect <= ((inspectRating + kerbalSmart) / 2) && check2 == true) //*******************OIL CONDITION
- {
- print("We made the inspection roll!");
- if (oilCond >= 0.9f) ScreenMessages.PostScreenMessage(new ScreenMessage("Oil looks great, liquid gold!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (oilCond >= 0.5f && oilCond < 0.9f) ScreenMessages.PostScreenMessage(new ScreenMessage("This oil is brown, still smells good!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (oilCond >= 0.25f && oilCond < 0.5f) ScreenMessages.PostScreenMessage(new ScreenMessage("This oil is very used, but still might last a little while longer", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (oilCond > 0f && oilCond < 0.25f) ScreenMessages.PostScreenMessage(new ScreenMessage("Yuk! This oil is totally burnt, Change immediately!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (oilCond == 0f) ScreenMessages.PostScreenMessage(new ScreenMessage("The oil that is left is burned all into the engine, what a mess!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- check2 = false;
- }
- else if (randomInspect > ((inspectRating + kerbalSmart) / 2) && check2 == true)
- {
- print("Kerbal makes mistake doing inspection!"); // OIL INSPECTION could be right could be wrong who knows!
- float randomBS = UnityEngine.Random.Range(0f, 5f);
- if (runState == "Seized" || runState == "Dead") randomBS = 5f;
- if (randomBS <= 1f) ScreenMessages.PostScreenMessage(new ScreenMessage("Oil looks great, liquid gold!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 2f && randomBS > 1f) ScreenMessages.PostScreenMessage(new ScreenMessage("This oil is brown, still smells good!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 3f && randomBS > 2f) ScreenMessages.PostScreenMessage(new ScreenMessage("This oil is very used, but still might last a little while longer", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 4f && randomBS > 3f) ScreenMessages.PostScreenMessage(new ScreenMessage("Yuk! This oil is totally burnt, Change immediately!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 5f && randomBS > 4f) ScreenMessages.PostScreenMessage(new ScreenMessage("The oil that is left is burned all into the engine, what a mess!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- check2 = false;
- }
- if (randomInspect <= ((inspectRating + kerbalSmart) / 2) && check3 == true) //************************ ELECTRICAL
- {
- print("We made the inspection roll!");
- if (sparkEff >= 0.9f) ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical contacts look clean!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (sparkEff >= 0.5f && sparkEff < 0.9f) ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical contacts look normal, keep an eye on it!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (sparkEff >= 0.25f && sparkEff < 0.5f) ScreenMessages.PostScreenMessage(new ScreenMessage("These Electrical systems look dirty and worn, they might last for a while", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (sparkEff > 0.0f && sparkEff < 0.25f) ScreenMessages.PostScreenMessage(new ScreenMessage("Contact points are nearly gone, the whole thing looks barely functional!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (sparkEff == 0f) ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical system is fried! Needs total overhaul...", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- check3 = false;
- }
- else if (randomInspect > ((inspectRating + kerbalSmart) / 2) && check3 == true)
- {
- print("Kerbal makes mistake doing inspection!"); // could be right could be wrong who knows!
- float randomBS = UnityEngine.Random.Range(0f, 5f);
- if (randomBS <= 1f) ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical contacts look clean!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 2f && randomBS > 1f) ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical contacts look normal, keep an eye on it!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 3f && randomBS > 2f) ScreenMessages.PostScreenMessage(new ScreenMessage("These Electrical systems look dirty and worn, they might last for a while", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 4f && randomBS > 3f) ScreenMessages.PostScreenMessage(new ScreenMessage("Contact points are nearly gone, the whole thing looks barely functional!", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (randomBS <= 5f && randomBS > 4f) ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical system is fried! Needs total overhaul...", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- check3 = false;
- }
- if (runState == "Seized") ScreenMessages.PostScreenMessage(new ScreenMessage("This engine is seized! It won't start until it's repaired.", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- if (runState == "Dead") ScreenMessages.PostScreenMessage(new ScreenMessage("This engine is dead! It can't be fixed.", messageDisplayTime, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- #endregion
- #region FIXING TIME CHECK & JOB COMPLETION
- if (fixOngoing == true && doneTime > Time.time && (this.part.transform.position.magnitude - FlightGlobals.ActiveVessel.transform.position.magnitude) > 4f || fixOngoing == true && doneTime > Time.time && FlightGlobals.ActiveVessel.isEVA == false)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("You botched the job! Please stay within 4m of the engine, do not switch away or enter a vessel.", 10f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- }
- if (fixOngoing == true && doneTime < Time.time && jobName == "airfilter")
- {
- print("Job completed in... " + fixTime + " seconds, at" + Time.time);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Air filter is fixed!", 10f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- if (airEff < 1f)
- {
- airEff = (1f * (1f - ourKerbalsStupid) + 1f) * 0.5f; //the most a kerbal can restore this is directly related to how smart he is!
- print("Airfilter condition is now... " + airEff);
- }
- }
- if (fixOngoing == true && doneTime < Time.time && jobName == "electrical")
- {
- print("Job completed in... " + fixTime + " seconds, at" + Time.time);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Electrical systems look much better now!", 10f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- if (sparkEff < 1f)
- {
- sparkEff = (1f * (1f - ourKerbalsStupid) + 1f) * 0.5f;
- print("Electrical System condition is now... " + sparkEff);
- }
- }
- if (fixOngoing == true && doneTime < Time.time && jobName == "oilservice")
- {
- fixOngoing = false;
- jobName = "nil";
- if (oilCond < 100f || oilLevel < 100f || dmgOilLeak == true)
- {
- print("Inside the condition...");
- List<Collider> nearestColliders = new List<Collider>(Physics.OverlapSphere(iceForceTransform.position, 40f));
- foreach (Collider col in nearestColliders)
- {
- if (!col.attachedRigidbody)
- {
- continue;
- }
- Part p = col.attachedRigidbody.GetComponent<Part>();
- if (!p)
- {
- continue;
- }
- print("check3");
- PartResourceList resourceList = p.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "KobilOne")
- {
- print("Found a part with oil!");
- if (resource.amount < oilCapacity)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Oil Station has insufficient oil, can't finish this job!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- else if (resource.amount >= oilCapacity)
- {
- if (takeOilOnce == true)
- {
- resource.amount = resource.amount - oilCapacity;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Oil is changed and seals are fixed! Note: Source has " + resource.amount + " oil remaining", 10f, ScreenMessageStyle.UPPER_CENTER));
- print("Job completed in... " + fixTime + " seconds, at" + Time.time);
- oilCond = 1f;
- oilLevel = 100f;
- dmgOilLeak = false;
- dmgOutOfWhack = false;
- takeOilOnce = false;
- oilBurningFX.particleEmitter.emit = false;
- lightOne.enabled = false;
- }
- }
- }
- }
- }
- }
- else print("No Condition met... " + oilCond);
- }
- if (fixOngoing == true && doneTime < Time.time && jobName == "engine")
- {
- if (runState == "Seized")
- {
- print("Inside the condition...");
- List<Collider> nearestColliders = new List<Collider>(Physics.OverlapSphere(iceForceTransform.position, 40f));
- foreach (Collider col in nearestColliders)
- {
- if (!col.attachedRigidbody)
- {
- continue;
- }
- Part p = col.attachedRigidbody.GetComponent<Part>();
- if (!p)
- {
- continue;
- }
- PartResourceList resourceList = p.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "SpareParts")
- {
- print("Found a part with SpareParts!");
- if (resource.amount < 0.25)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Can't find enough SpareParts within 40m, can't finish this job!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- else if (resource.amount >= 0.25)
- {
- if (takeOilOnce == true)
- {
- resource.amount = resource.amount - 0.25;
- print("Job completed in... " + fixTime + " seconds, at" + Time.time);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine is restored, take it easy next time!", 10f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- takeOilOnce = false;
- runState = "Off";
- }
- }
- }
- }
- }
- }
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine is not damaged, do an oil change!", 5f, ScreenMessageStyle.UPPER_CENTER));
- fixOngoing = false;
- jobName = "nil";
- takeOilOnce = false;
- }
- #endregion
- if (dmgOilLeak == true) oilLeak();
- soundFail.audio.volume = (0.025f * GameSettings.SHIP_VOLUME);
- #region reset animated part if there is one...
- animateTimer -= Time.deltaTime;
- if (animateTimer <= 0)
- {
- animateTimer = (((1f - throttleActual) + 0.01f) * 0.1f);
- if (animateTransform != null)
- {
- animateTransform.localRotation = animateDefaultTransform.localRotation;
- animateTransform.localPosition = animateDefaultTransform.localPosition;
- }
- }
- #endregion
- if (checkOnce == true)
- {
- oilTemp = FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody);
- engTemp = FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody);
- checkOnce = false;
- }
- if (airCooled == true)
- {
- if (FlightGlobals.ActiveVessel.rb_velocity.magnitude >= 60f)
- {
- if (oilTemp > 160f)
- {
- coolingEff = 0.08f;
- }
- else coolingEff = 0.018f;
- }
- else if (FlightGlobals.ActiveVessel.rb_velocity.magnitude >= 20f)
- {
- if (oilTemp > 160f)
- {
- coolingEff = 0.065f;
- }
- else coolingEff = 0.0125f;
- }
- else if (FlightGlobals.ActiveVessel.rb_velocity.magnitude < 20f)
- {
- if (oilTemp > 160f)
- {
- coolingEff = 0.025f;
- }
- else coolingEff = 0.001f;
- }
- }
- else
- {
- coolingEff = 0.0f; //make air cooling useless
- if (getAllLCool != null && getAllLCool.Count() > 0)
- {
- coolantTemp = engTemp;
- this.part.temperature = coolantTemp;
- int[] allRads = new int[getAllLCool.Count];
- for (int i = 0; i < allRads.Length; i++)
- {
- getAllLCool[i].inputTemp = coolantTemp;
- if (getAllLCool[i].flapPos != 0f)
- {
- float percentAffected = (getAllLCool[i].flowRate / this.coolantCapacity) * 100f;
- float cooledPortionTemp = (((this.vessel.rigidbody.velocity.magnitude * getAllLCool[i].flapPos) * getAllLCool[i].radSize) * 0.01f) * coolantTemp;
- if (cooledPortionTemp == 0f) cooledPortionTemp = 1f; //0 meaning no cooling is done therefore multiply to cool by 1 to keep temp unchanged/uncooled.
- float finalReturnTemp = (coolantTemp * ((100f - percentAffected) * 0.01f)) + (cooledPortionTemp * (percentAffected * 0.01f));
- engTemp = finalReturnTemp;
- coolantTemp = finalReturnTemp;
- }
- }
- }
- }
- if (runState == "Off")
- {
- soundDrone.audio.Stop();
- soundGroup.audio.Stop();
- soundFail.audio.Stop();
- soundSuperC.audio.Stop();
- currentRPM = Mathf.Lerp(currentRPM, 0f, 1f);
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - coolingEff;
- oilTemp = engTemp;
- }
- if (exhaustFX1 != null)
- {
- exhaustFX1.SetActive(false);
- }
- }
- if (runState == "Off" && fuelOn == true && elecOn == true && starterOn == true && runState != "Seized" && runState != "Dead" || runState == "Stalled" && fuelOn == true && elecOn == true && starterOn == true && runState != "Seized" && runState != "Dead")
- {
- print("Starting Engine!");
- runState = "Starting";
- }
- if (runState == "Starting" && fuelOn == true && elecOn == true && starterOn == true && runState != "Seized" && runState != "Dead")
- {
- starterOn = false;
- currentRPM = engineIdleSpeed;
- createBackfire();
- float tempStartMod = (oilMaxTemp * 0.5f) / oilTemp ;
- if (tempStartMod > 25f) tempStartMod = 25f;
- if (tempStartMod < 0f) tempStartMod = 0f;
- float chanceToStart = (((100f - tempStartMod) * sparkEff) * airEff);//Try to start... airfilter & spark condition plays a role as well as how warm the engine oil is!
- float randStartRoll = (float)rndNumber.rndRoll(1, 101);
- if (randStartRoll < chanceToStart)
- {
- print("Engine Started!");
- runState = "Running";
- currentRPM = Mathf.Lerp(currentRPM, (throttleActual * (((engineRedline * Math.Abs(pitchModifier)) * 1.05f))) + (FlightGlobals.ActiveVessel.rb_velocity.magnitude * 3.25f), 0.3f); // begin the engine turning!!!
- }
- else runState = "Off";
- }
- #region Engine is Running or Running Overheated
- if (runState == "Running" && fuelOn == true && elecOn == true && starterOn == false || runState == "Overheated" && fuelOn == true && elecOn == true && starterOn == false)
- {
- checkThrottle();
- #region Supercharger Operations ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- if (isSupercharged == true)
- {
- if (this.vessel.altitude < twoStageTripAlt || isTwoStageAuto == false)
- {
- currentBoostMulti = boostLowMultiplier;
- if (soundSuperC.audio.isPlaying == false)
- {
- soundSuperC.audio.Play();
- }
- soundSuperC.audio.volume = (((boostLowMultiplier - 1f) * 1.35f) * GameSettings.SHIP_VOLUME) * throttleActual;
- //print("Stage one Active");
- }
- else if (this.vessel.altitude > twoStageTripAlt && isTwoStageAuto == true)
- {
- currentBoostMulti = boostHighMultiplier;
- if (soundSuperC.audio.isPlaying == false)
- {
- soundSuperC.audio.Play();
- }
- soundSuperC.audio.volume = (((boostHighMultiplier - 1f) * 1.4f) * GameSettings.SHIP_VOLUME) * throttleActual;
- //print("Stage two Active");
- }
- }
- else if (isSupercharged == false) currentBoostMulti = 1f; // no supercharger - no effect.
- actualAirDensity = (float)this.vessel.atmDensity * currentBoostMulti;
- if (actualAirDensity > 1f) actualAirDensity = 1f;
- #endregion
- #region Sound Event Code for RUNNING state.
- if (runState == "Running" || runState == "Overheated")
- {
- if (soundDrone.audio.isPlaying == false)
- {
- soundDrone.audio.Play();
- if (soundGroup.audio.isPlaying == true)
- {
- soundGroup.audio.Stop();
- }
- }
- soundDrone.audio.volume = (1f * GameSettings.SHIP_VOLUME) * throttleActual;
- soundGroup.audio.volume = (0.25f * GameSettings.SHIP_VOLUME) * throttleActual;
- if (hasDirectOutput == true && getICEdDrive!= null)
- {
- soundDrone.audio.pitch = ((getICEdDrive.rpmOutput + engineIdleSpeed) * 1f) / (engineRedline * 0.1f);
- }
- else
- {
- soundDrone.audio.pitch = ((((currentRPM * 0.5f) + ((float)FlightGlobals.ActiveVessel.rb_velocity.magnitude * 5f)) * 0.8f) / (engineRedline * 1.025f)) + 0.3f;
- if (soundDrone.audio.pitch > 4f) soundDrone.audio.pitch = 4f;
- }
- }
- #endregion
- float degPerSec = currentRPM * 6f;
- ignitionTimer -= Time.deltaTime;
- if (ignitionTimer <= 0)
- {
- ignitionTimer = ignCooldown;
- if(madeCharge == true) madeCharge = false;
- cylStats[] engineID = new cylStats[numOfCyls];
- for (int i = 0; i < engineID.Length; i++)
- {
- engineID[i] = new cylStats();
- engineID[i].iceCylNum = i;
- engineID[i].cylForceIdeal = (engineDisplacement * enginePerformanceMulti) / numOfCyls;
- engineID[i].addHeat = engineID[i].cylForceIdeal * 0.00075f;
- engineID[i].powerArcOn = (360 / numOfCyls) * i;
- engineID[i].powerArcOff = engineID[i].powerArcOn + camTime;
- if (engineID[i].powerArcOff > 360) engineID[i].powerArcOff = (engineID[i].powerArcOff - 360);
- engineID[i].useAirRate = ((((engineDisplacement * 61.0237f) * currentRPM) * ((1f - actualAirDensity) + 1f)) / 3456f) * 0.000471947443f;
- engineID[i].useFuelRate = (engineID[i].useAirRate * actualAirDensity) * fuelAirMix;
- engTemp += (engineID[i].addHeat * engineHeatup * ((throttleActual * 0.25f) + 1f)); // use engine reliable - heat buildup in weak engines
- oilTemp = engTemp;
- if (atRotation > engineID[i].powerArcOn && atRotation < engineID[i].powerArcOff && lastCylToFire != engineID[i].iceCylNum)//don't fire if it's not in it's firing location and don't fire if it's the same cylinder as last time.
- {
- #region Use Resources
- double resourceConsumed = (double)Mathf.Abs(engineID[i].useFuelRate) * (double)TimeWarp.deltaTime;
- if (!CheatOptions.InfiniteFuel)
- {
- double receivedResource = base.part.RequestResource(resourceType, resourceConsumed);
- if (receivedResource >= resourceConsumed - 0.0001d)
- {
- sparkEff = sparkEff - ((float)receivedResource + wearRate) * 0.00015f; // the more the fuel gets ignited in the engine the quicker the electrics get dirty.
- }
- else if (receivedResource < resourceConsumed)
- {
- print("Out of Fuel/Fuel Problem");
- runState = "Stalled";
- }
- double airConsumed = (double)Mathf.Abs(engineID[i].useAirRate * 25f) * (double)TimeWarp.deltaTime;
- double receivedAir = base.part.RequestResource("IntakeAir", airConsumed);
- if (receivedAir >= airConsumed - 0.001d)
- {
- float tuneModifier = 0.000015f;
- if (FlightGlobals.ActiveVessel.heightFromTerrain < 500.0d) tuneModifier = 0.000015f; // filter gets dirtier closer to the ground
- if (FlightGlobals.ActiveVessel.heightFromTerrain > 500.0d) tuneModifier = 0.0000035f;
- airEff = airEff - ((float)receivedAir + wearRate) * tuneModifier; // the more air that passes the filter the quicker it gets dirty.
- if (airEff <= 0.2f)
- {
- print("Air Filter Jammed! Clean Filter");
- runState = "Stalled";
- createBackfire();
- }
- }
- else if (receivedAir < airConsumed)
- {
- print("Out of Oxygen!");
- runState = "Stalled";
- createBackfire();
- }
- double elecConsumed = wearRate;
- double receivedElec = base.part.RequestResource("ElectricCharge", elecConsumed);
- }
- #endregion
- #region Prop Power and Direction
- if (propPitch > 0f && propPitch < 1f)
- {
- thrustDirection = -iceForceTransform.forward;
- propScalePower = (1f - propPitch) + 1f;
- }
- else if (propPitch == 1f)
- {
- thrustDirection = -iceForceTransform.forward;
- propScalePower = 1f;
- }
- else if (propPitch < 0f && propPitch > -1f)
- {
- thrustDirection = iceForceTransform.forward;
- propScalePower = (1f - Math.Abs(propPitch)) + 1f;
- }
- else if (propPitch == -1f)
- {
- thrustDirection = iceForceTransform.forward;
- propScalePower = 1f;
- }
- else if (propPitch == 0)
- {
- propScalePower = 0f;
- }
- #endregion
- if (useThrustAveraging == false)
- {
- base.rigidbody.AddForceAtPosition(thrustDirection * (((((((engineID[i].cylForceIdeal * sparkEff) * airEff) * throttleActual) * propScalePower) * coldLoss) * actualAirDensity) * currentBoostMulti), actualThrustPosition.position); // changed from iceForceTransform...
- }
- if (useThrustAveraging == true)
- {
- base.rigidbody.AddForceAtPosition(thrustDirection * (((((((engineID[i].cylForceIdeal * sparkEff) * airEff) * throttleActual) * propScalePower) * coldLoss) * actualAirDensity) * currentBoostMulti), iceAvgThrustPosition.position); // changed from iceForceTransform...
- }
- if (exhaustFX1 != null && exh[engineID[i].iceCylNum] != null)
- {
- exhaustFX1.SetActive(true);
- exhaustFX1.transform.position = exh[engineID[i].iceCylNum].position;
- exhaustFX1.transform.localRotation = exh[engineID[i].iceCylNum].localRotation;
- }
- #region Engine Idling Sound
- if (soundGroup.audio.isPlaying == false && runState == "Running" || soundGroup.audio.isPlaying == false && runState == "Overheated")
- {
- soundGroup.audio.volume = (0.25f * GameSettings.SHIP_VOLUME);
- soundGroup.audio.Play();
- }
- #endregion
- lastCylForce = engineID[i].cylForceIdeal;
- lastCylToFire = engineID[i].iceCylNum;
- #region CarbIce *********************************++++++++++++++++
- float carbHeated = 0f;
- if (carbHeat == true) carbHeated = oilTemp * 0.5f;
- carbTemp = (FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody) + carbHeated);
- if (carbTemp < 2.78f && carbTemp >= 0.0f)
- {
- carbIce -= 0.0005f;
- if (carbIce < 0.5f) carbIce = 0.5f;
- }
- else carbIce += 0.00001f; //Shouldn't de-ice itself without carb heat applied.
- if (carbHeat == true) carbIce += 0.00004f; // add this extra de-icing.
- if (carbIce > 1f) carbIce = 1f;
- #endregion
- #region generator ****************************************
- if (madeCharge == false) // just charge this vessels batteries
- {
- foreach (Part aPart in FlightGlobals.ActiveVessel.Parts)
- {
- PartResourceList resourceList = aPart.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "ElectricCharge" && madeCharge == false)
- {
- double chargeRate = (((float)engineDisplacement * 0.0025) * throttleActual) * (double)TimeWarp.deltaTime;
- if (remoteCharger == true) chargeRate = chargeRate * 7000.0;
- double receivedResource = base.part.RequestResource("ElectricCharge", -chargeRate);
- if (remoteCharger == false) madeCharge = true;
- #region RemoteCharger Only ********
- if (remoteCharger == true && madeCharge == false)
- {
- if (animateTransform != null)
- {
- animateTransform.localRotation = animateDefaultTransform.localRotation;
- animateTransform.Rotate(Vector3.forward * ((float)rndNumber.rndDouble() * throttleActual));
- animateTransform.Rotate(Vector3.left * ((float)rndNumber.rndDouble() * throttleActual));
- animateTransform.Rotate(Vector3.up * ((float)rndNumber.rndDouble() * throttleActual));
- animateTransform.localPosition = new Vector3(animateDefaultTransform.localPosition.x, animateDefaultTransform.localPosition.y * 1.005f, animateDefaultTransform.localPosition.z);
- }
- foreach (Vessel v in FlightGlobals.Vessels)
- {
- if (Vector3.Distance(v.transform.position, this.transform.position) < 40f)
- {
- foreach (Part rPart in v.Parts)
- {
- PartResourceList rresourceList = aPart.Resources;
- foreach (PartResource rresource in resourceList)
- {
- if (resource.resourceName == "ElectricCharge" && madeCharge == false)
- {
- resource.amount = resource.amount + (0.3d * throttleActual) * (double)TimeWarp.deltaTime;
- madeCharge = true;
- }
- }
- }
- }
- }
- }
- #endregion
- }
- }
- }
- }
- #endregion
- }
- else
- {
- if (useThrustAveraging == false)
- {
- base.rigidbody.AddForceAtPosition(thrustDirection * ((((((((engineID[i].cylForceIdeal * 0.15f) * sparkEff) * airEff) * throttleActual) * propScalePower) * coldLoss) * actualAirDensity) * currentBoostMulti), actualThrustPosition.position); // changed from iceForceTransform...
- }
- if (useThrustAveraging == true)
- {
- base.rigidbody.AddForceAtPosition(thrustDirection * ((((((((engineID[i].cylForceIdeal * 0.15f) * sparkEff) * airEff) * throttleActual) * propScalePower) * coldLoss) * actualAirDensity) * currentBoostMulti), iceAvgThrustPosition.position); // changed from iceForceTransform...
- }
- }
- atRotation = atRotation + (int)(degPerSec * 0.001f);
- if (atRotation > 360) atRotation = (atRotation - 360);
- if (currentRPM >= engineIdleSpeed)
- {
- currentRPM = Mathf.Lerp(currentRPM, (throttleActual * (((engineRedline * Math.Abs(pitchModifier)) * 1.05f))) + (FlightGlobals.ActiveVessel.rb_velocity.magnitude * 3.25f), 0.3f);
- #region Gearbox effect for Direct Drive only!!! ********************************
- if (hasDirectOutput == true)
- {
- if (animateTransform != null)
- {
- animateTransform.localRotation = animateDefaultTransform.localRotation;
- animateTransform.Rotate(Vector3.forward * ((float)rndNumber.rndDouble() * throttleActual));
- animateTransform.Rotate(Vector3.left * ((float)rndNumber.rndDouble() * throttleActual));
- animateTransform.Rotate(Vector3.up * ((float)rndNumber.rndDouble() * throttleActual));
- animateTransform.localPosition = new Vector3(animateDefaultTransform.localPosition.x, animateDefaultTransform.localPosition.y * 1.005f, animateDefaultTransform.localPosition.z);
- }
- currentRPM = Mathf.Lerp(currentRPM, (throttleActual * ((engineRedline * 1.05f))) + (FlightGlobals.ActiveVessel.rb_velocity.magnitude * 3.25f), 0.3f);
- }
- #endregion
- }
- if (currentRPM < engineIdleSpeed) // at the lowest throttle setting the engine slows to idle speed.
- {
- currentRPM = Mathf.Lerp(currentRPM, ((throttleActual + 0.03f) * (((engineRedline * Math.Abs(pitchModifier)) * 1.05f))) + (FlightGlobals.ActiveVessel.rb_velocity.magnitude * 3.25f), 0.3f);
- float randomStallCheck = rndNumber.rndRoll(1, 1001);
- if(randomStallCheck < 5f)
- {
- runState = "Stalled";
- //insert puttering sound later.
- }
- }
- }
- }
- }
- #endregion
- if (elecOn == false || fuelOn == false)
- {
- if (runState == "Running" || runState == "Overheated")
- {
- runState = "Off";
- currentRPM = Mathf.Lerp(currentRPM, 0f, 1f);
- soundSuperC.audio.Stop();
- soundDrone.audio.Stop();
- soundGroup.audio.Stop();
- soundFail.audio.Stop();
- oilBurningFX.particleEmitter.emit = false;
- lightOne.enabled = false;
- oilBurnTrailFX.particleEmitter.emit = false;
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - coolingEff;
- oilTemp = engTemp;
- }
- }
- }
- #region Cooling with Airflow on Air Cooled engines
- if (runState == "Running" || runState == "Overheated")
- {
- if (currentRPM > engineRedline && oilLevel > 50f) // normal overheat
- {
- this.part.SetHighlightColor(Color.red);
- this.part.SetHighlight(true);
- engTemp = engTemp * (overHeatMod * 0.9884f);
- oilTemp = Mathf.Lerp(oilTemp, engTemp, 1f);
- }
- else if (currentRPM > engineRedline && oilLevel < 50f) // worse condition
- {
- this.part.SetHighlightColor(Color.red);
- this.part.SetHighlight(true);
- engTemp = engTemp * (overHeatMod * 0.9885f + (wearRate * 10f));
- oilTemp = Mathf.Lerp(oilTemp, engTemp, 1f);
- }
- else if (currentRPM < engineRedline && oilLevel > 50f) // best condition
- {
- this.part.SetHighlightColor(Color.clear);
- this.part.SetHighlight(false);
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - coolingEff;
- oilTemp = engTemp;
- }
- }
- else if (currentRPM < engineRedline && oilLevel < 50f) // not ideal
- {
- this.part.SetHighlightColor(Color.clear);
- this.part.SetHighlight(false);
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - (coolingEff * 0.9f);
- oilTemp = engTemp;
- }
- }
- #endregion
- }
- if (oilTemp < 0f) oilTemp = 0f;
- if (engTemp < 0f) engTemp = 0f;
- if (engTemp > oilMaxTemp * 1.2f) engTemp = oilMaxTemp * 1.2f;
- if (engTemp > maxEngTemp && runState == "Running" || engTemp > maxEngTemp && runState == "Overheated")
- {
- if(oilTemp > oilMaxTemp)
- {
- if (oilCond > 0f)
- {
- oilCond = (oilCond - ((oilTemp - oilMaxTemp) * wearRate));
- if (oilCond < 0f) oilCond = 0f;
- runState = "Overheated";
- }
- if (oilCond <= 0f)
- {
- if (oilLevel > 0f)
- {
- if(soundFail.audio.isPlaying == false) soundFail.audio.Play();
- soundFail.audio.volume = 0.025f;
- oilBurningFX.particleEmitter.emit = true;
- lightOne.enabled = true;
- oilBurnTrailFX.particleEmitter.emit = true;
- oilLevel = oilLevel - (wearRate * (currentRPM * 0.05f));
- if (oilLevel < 0.1f) oilLevel = 0f;
- dmgOilLeak = true;
- }
- if (oilLevel <= 0f)
- {
- soundFail.audio.Stop();
- float deadEngChance = (float)rndNumber.rndRoll(1, 101);
- if (deadEngChance < 50f)
- {
- runState = "Seized";
- currentRPM = Mathf.Lerp(currentRPM, 0f, 5f);
- }
- else if (deadEngChance > 50f)
- {
- runState = "Dead";
- currentRPM = Mathf.Lerp(currentRPM, 0f, 5f);
- }
- }
- }
- }
- }
- if (oilTemp < oilMaxTemp && runState == "Overheated")
- {
- runState = "Running";
- }
- if (oilTemp < oilMaxTemp && oilTemp > (oilMaxTemp * 0.5f) && runState == "Running")
- {
- coldLoss = 1f;
- }
- if (oilTemp < oilMaxTemp && oilTemp < (oilMaxTemp * 0.25f) && runState == "Running")
- {
- coldLoss = 0.5f; //it will run worse if it's under 1/4 max oil temp .
- if (throttleActual > 0.25f)//running above this can cause backfires - causing premature wear on the electrical system.
- {
- float randomBackFireCheck = rndNumber.rndRoll(1, 1001);
- if (randomBackFireCheck < 4f)
- {
- dmgMissFire = true;
- missFire();
- }
- }
- if (currentRPM > engineRedline)
- {
- float randomBackFireCheck = rndNumber.rndRoll(1, 1001);
- if (randomBackFireCheck < 2f)
- {
- dmgMissFire = true;
- missFire();
- dmgOilLeak = true;
- }
- }
- }
- #region Engine Stalled, Seized or Dead
- if (runState == "Stalled")
- {
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - coolingEff;
- oilTemp = engTemp;
- }
- currentRPM = Mathf.Lerp(currentRPM, 0f, 1f);
- soundDrone.audio.Stop();
- soundGroup.audio.Stop();
- soundFail.audio.Stop();
- soundSuperC.audio.Stop();
- oilBurningFX.particleEmitter.emit = false;
- lightOne.enabled = false;
- oilBurnTrailFX.particleEmitter.emit = false;
- if (exhaustFX1 != null)
- {
- exhaustFX1.SetActive(false);
- }
- }
- if (runState == "Overheated") //is running and overheated - this is a running but damaged runState.
- {
- //print("Warning Engine Overheated!");
- }
- if (runState == "Seized")
- {
- soundDrone.audio.Stop();
- soundGroup.audio.Stop();
- soundFail.audio.Stop();
- soundSuperC.audio.Stop();
- oilBurningFX.particleEmitter.emit = false;
- lightOne.enabled = false;
- oilBurnTrailFX.particleEmitter.emit = false;
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - coolingEff;
- oilTemp = engTemp;
- }
- if (exhaustFX1 != null)
- {
- exhaustFX1.SetActive(false);
- }
- }
- if (runState == "Dead")
- {
- soundDrone.audio.Stop();
- soundGroup.audio.Stop();
- soundFail.audio.Stop();
- soundSuperC.audio.Stop();
- oilBurningFX.particleEmitter.emit = false;
- lightOne.enabled = false;
- oilBurnTrailFX.particleEmitter.emit = false;
- if (engTemp > FlightGlobals.getExternalTemperature((float)this.vessel.altitude, this.vessel.mainBody))
- {
- engTemp = engTemp - coolingEff;
- oilTemp = engTemp;
- }
- if (exhaustFX1 != null)
- {
- exhaustFX1.SetActive(false);
- }
- }
- #endregion
- }
- public void checkRandomFailure()
- {
- float randChangeToFail = (float)rndNumber.rndRoll(1, 1001);
- if (randChangeToFail <= 3f || runState == "Overheated" && randChangeToFail <= 6f) //while overheated the chance of a failure is 2x...
- {
- float failureChoose = (float)rndNumber.rndRoll(1, 31);
- if (failureChoose <= 10f)
- {
- dmgOilLeak = true;
- oilLeak();
- print("Oil Leaking!");
- }
- if (failureChoose > 10f && failureChoose <= 20f) missFire();
- if (failureChoose > 20f && failureChoose <= 30f) fuelCutout();
- }
- }
- public void oilLeak()
- {
- if (runState == "Running" && dmgOilLeak == true || runState == "Overheated" && dmgOilLeak == true)
- {
- oilLevel = oilLevel - (wearRate * (currentRPM * 0.02f));
- if (oilLevel < 0f) oilLevel = 0f;
- }
- }
- public void missFire()
- {
- if (runState == "Running" && dmgMissFire == true || runState == "Overheated" && dmgMissFire == true)
- {
- createBackfire();
- float randomWear = UnityEngine.Random.Range(0f, 1f);
- sparkEff = sparkEff - (randomWear * (wearRate * 100f));
- if (sparkEff < 0f) sparkEff = 0f;
- dmgMissFire = false;
- print("Missfire! Spark efficiency is now: " + sparkEff);
- }
- }
- public void fuelCutout()
- {
- if (runState == "Running" && dmgFuelCutout == true || runState == "Overheated" && dmgFuelCutout == true)
- {
- print("Fuel issue... Stalled!");
- runState = "Stalled";
- dmgFuelCutout = false;
- }
- }
- public void checkThrottle()
- {
- if (!this.vessel.isEVA && this.vessel == FlightGlobals.ActiveVessel)
- {
- if (useMultiThrottle == true && useWThrottle == false)
- {
- throttleActual = guiThrottle;
- }
- else throttleActual = FlightInputHandler.state.mainThrottle;
- lastGoodThrottle = throttleActual;
- }
- else if (this.vessel.isEVA || this.vessel != FlightGlobals.ActiveVessel)
- {
- throttleActual = lastGoodThrottle;
- }
- }
- public void checkKerbal()
- {
- ProtoCrewMember getStats = FlightGlobals.ActiveVessel.GetVesselCrew().FirstOrDefault();
- lastKerbalName = getStats.name;
- bool oneTime = true;
- foreach (ProtoCrewMember crewMember in this.vessel.GetVesselCrew())
- {
- if (lastKerbalName == crewMember.name && oneTime == true)
- {
- ourKerbalsStupid = crewMember.stupidity;
- ourKerbalIsBadass = crewMember.isBadass;
- ourKerbalCourage = crewMember.courage;
- string showKerStats = crewMember.name + " has a technicial rating of " + (1f - ourKerbalsStupid);
- ScreenMessages.PostScreenMessage(new ScreenMessage(showKerStats, 3f, ScreenMessageStyle.UPPER_CENTER));
- oneTime = false;
- }
- }
- }
- public void createBackfire()
- {
- GameObject fxBFInstance = new GameObject();
- try
- {
- fxBFInstance = GameDatabase.Instance.GetModel("IDiCEr1/Effects/BackfireFX/model");
- }
- catch
- {
- print("Problem locating BackfireFX");
- }
- if (fxBFInstance != null && exh != null)
- {
- if (soundBackF.audio.isPlaying == false) soundBackF.audio.Play();
- fxBFInstance.SetActive(true);
- fxBFInstance.transform.parent = this.part.transform;
- fxBFInstance.transform.position = exh[lastCylToFire].position; //current cylinder position
- fxBFInstance.transform.localRotation = exh[lastCylToFire].localRotation; //???
- Destroy(fxBFInstance, 2f);
- }
- }
- public void persistantRunRough()
- {
- float randomBackFireCheck = rndNumber.rndRoll(0, 100);
- if (randomBackFireCheck < 2f)
- {
- dmgMissFire = true;
- missFire();
- }
- }
- public void ApplyDamage(float damageState)
- {
- print("Inside ApplyDamage for ICE!");
- if (damageState < 1f)
- {
- float specialDamage = (float)rndNumber.rndRoll(0, 100);
- if (specialDamage < 50f)
- {
- float doDamage = (float)rndNumber.rndRoll(0, 100);
- if (doDamage < 40f)
- {
- wearRate = 0.0005f;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine doesn't sound right!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (doDamage < 60f && doDamage >= 40f)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine took damage and stalled! Try to restart it.", 3f, ScreenMessageStyle.UPPER_CENTER));
- runState = "Stalled";
- }
- if (doDamage < 70f && doDamage >= 60f)
- {
- dmgOilLeak = true;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Oil is leaking from the engine!", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- if (doDamage < 80f && doDamage >= 70f)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine sounds really rough! We should land!", 3f, ScreenMessageStyle.UPPER_CENTER));
- dmgOutOfWhack = true;
- }
- if (doDamage < 90f && doDamage >= 80f)
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine took a serious hit, I think something is wrong!", 3f, ScreenMessageStyle.UPPER_CENTER));
- enginePerformanceMulti *= (float)rndNumber.rndRoll(1, 100) * 0.01f;
- }
- if (doDamage == 100f && doDamage >= 90f)
- {
- //engineHeatup???
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine was hit, still sounds and looks okay...", 3f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- }
- if (damageState == 1f)//normal/fixed state.... reset all to normal
- {
- //range = origRange;
- //isJammed = false;
- }
- }
- }
- public class cylStats
- {
- public int iceCylNum;
- public int powerArcOn;
- public int powerArcOff;
- public float cylForceIdeal;
- public float useFuelRate;
- public float useAirRate;
- public float addHeat;
- }
- public class rndNumber
- {
- public static System.Random rnd = new System.Random();
- public static int rndRoll(int min, int max)
- {
- return rnd.Next(min, max);
- }
- public static System.Random rnd2 = new System.Random();
- public static double rndDouble()
- {
- return rnd2.NextDouble();
- }
- }
- public class IDliqCool : PartModule
- {
- [KSPField]
- public float radSize = 0.3f;
- [KSPField]
- public float thermoOpen = 170f;
- [KSPField]
- public float thermoClose = 155f;
- public float boilOver = 190f;
- [KSPField]
- public float flowRate = 0.2f;//LPS
- [KSPField(guiActive = true, guiName = "Open x100% ")]
- public float flapPos = 0f;//0 closed 1 full open
- public bool doItOnce = true;
- public bool hasRadFlap = true;
- public bool doChange = false;
- public float inputTemp = 0f;
- public Transform radFlap;
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (doItOnce == true)
- {
- try
- {
- radFlap = part.FindModelTransform("radFlap");
- }
- catch
- {
- Debug.Log("Can't find radFlap");
- hasRadFlap = false;
- }
- if (hasRadFlap == true)
- {
- radFlap.Rotate(0f, 0f, -90f);
- }
- doItOnce = false;
- }
- if (hasRadFlap == true && flapPos < 1f && inputTemp > thermoOpen)
- {
- flapPos += 0.01f;
- radFlap.Rotate(0f, 0f, +1f);
- }
- if (hasRadFlap == true && flapPos > 0f && inputTemp < thermoClose)
- {
- flapPos -= 0.01f;
- radFlap.Rotate(0f, 0f, -1f);
- }
- if (flapPos < 0f)
- {
- flapPos = 0f;
- }
- if (flapPos > 1f)
- {
- flapPos = 1f;
- }
- }
- }
- public class IDdDrive : PartModule
- {
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Forward Gears"), UI_FloatRange(minValue = 1f, maxValue = 6f, stepIncrement = 1f)]
- public float numOfGears = 5;//forward gears
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "First Ratio"), UI_FloatRange(minValue = 2.85f, maxValue = 3.85f, stepIncrement = 0.05f)]
- public float firstGear = 3.85f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Second Ratio"), UI_FloatRange(minValue = 1.8f, maxValue = 2.75f, stepIncrement = 0.05f)]
- public float secondGear = 2.2f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Third Ratio"), UI_FloatRange(minValue = 1.3f, maxValue = 1.85f, stepIncrement = 0.05f)]
- public float thirdGear = 1.4f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Fourth Ratio"), UI_FloatRange(minValue = 0.9f, maxValue = 1.45f, stepIncrement = 0.05f)]
- public float fourthGear = 1.0f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Fifth Ratio"), UI_FloatRange(minValue = 0.8f, maxValue = 1.2f, stepIncrement = 0.05f)]
- public float fifthGear = 0.81f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Sixth Ratio"), UI_FloatRange(minValue = 0.5f, maxValue = 0.85f, stepIncrement = 0.05f)]
- public float sixthGear = 0.78f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Rev. Ratio"), UI_FloatRange(minValue = 2.85f, maxValue = 3.85f, stepIncrement = 0.05f)]
- public float reverseGear = 3.70f;//ratio of gear
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Final Ratio"), UI_FloatRange(minValue = 2.7f, maxValue = 4.1f, stepIncrement = 0.1f)]
- public float finalDrive = 2.9f;// Differential ratio
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Slip Lock %"), UI_FloatRange(minValue = 0.1f, maxValue = 1.0f, stepIncrement = 0.1f)]
- public float limitedSlip = 0.1f;// Differential ratio
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "Slip Lock"), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool lsdEnabled = false;
- public bool inReverse = false;
- public bool inNeutral = true;
- public float gearedForceMulti = 0f;
- [KSPField]
- public float shiftTime = 0.125f;
- [KSPField]
- public float dragInGearMulti = 1f;
- [KSPField]
- public bool isDamaged = false;
- [KSPField(guiActiveEditor = false, guiActive = true, guiName = "RPM Out")]
- public float rpmOutput = 0.0f;
- [KSPField(guiActiveEditor = false, guiActive = true, guiName = "In Gear")]
- public int currentGear = 0;
- [KSPField(guiActiveEditor = false, guiActive = true, guiName = "RPM In")]
- public float inputRPM = 0.0f;
- public bool firstRun = true;
- public IDice getICEOutput;
- public List<IDice> getAllICE = new List<IDice>();
- public float coupledICEOutput = 0f;
- public float dmgMulti = 1f;
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- if (HighLogic.LoadedSceneIsFlight)
- {
- foreach (Part aPart in vessel.Parts)
- {
- foreach (PartModule aModule in aPart.Modules)
- {
- if (aModule is IDice)
- {
- IDice thisEngine = aModule.GetComponent<IDice>();
- getAllICE.Add(thisEngine);
- print("Added an engine");
- }
- }
- }
- }
- }
- public void Update()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (this.vessel == FlightGlobals.ActiveVessel)
- {
- if (Input.GetKeyDown(KeyCode.PageUp))
- {
- bool changeOnce = true;
- if (currentGear < numOfGears)
- {
- if (inReverse == false && changeOnce == true)
- {
- currentGear = currentGear + 1;
- print("Shifted into " + currentGear);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Shifted into " + currentGear, 2f, ScreenMessageStyle.UPPER_CENTER));
- changeOnce = false;
- if (FlightInputHandler.state.mainThrottle > 0.1f)
- {
- FlightInputHandler.state.mainThrottle *= 0.65f;
- if (FlightInputHandler.state.mainThrottle < 0.1f)
- {
- FlightInputHandler.state.mainThrottle = 0.1f;
- }
- }
- }
- if (inReverse == true && changeOnce == true)
- {
- inReverse = false;
- inNeutral = true;
- currentGear = 0;
- print("Shifted into Neutral");
- ScreenMessages.PostScreenMessage(new ScreenMessage("Neutral Selected", 4f, ScreenMessageStyle.UPPER_CENTER));
- changeOnce = false;
- }
- }
- }
- if (Input.GetKeyDown(KeyCode.PageDown))
- {
- bool changeOnce = true;
- if (currentGear > 1 && changeOnce == true)
- {
- currentGear = currentGear - 1;
- print("Shifted into " + currentGear);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Shifted back to " + currentGear, 2f, ScreenMessageStyle.UPPER_CENTER));
- changeOnce = false;
- if (FlightInputHandler.state.mainThrottle > 0.1f)
- {
- FlightInputHandler.state.mainThrottle *= 1.35f;
- if (FlightInputHandler.state.mainThrottle > 1f)
- {
- FlightInputHandler.state.mainThrottle = 1f;
- }
- }
- }
- if (currentGear == 1 && changeOnce == true)
- {
- currentGear = 0;
- inNeutral = true;
- print("Shifted into Neutral");
- ScreenMessages.PostScreenMessage(new ScreenMessage("Neutral Selected", 4f, ScreenMessageStyle.UPPER_CENTER));
- changeOnce = false;
- }
- if (currentGear == 0 && changeOnce == true)
- {
- currentGear = -1;
- inReverse = true;
- inNeutral = false;
- print("Shifted into Reverse");
- ScreenMessages.PostScreenMessage(new ScreenMessage("Reverse Gear Selected", 4f, ScreenMessageStyle.UPPER_CENTER));
- changeOnce = false;
- }
- }
- }
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- if (firstRun == true && this.vessel == FlightGlobals.ActiveVessel)
- {
- currentGear = 0;
- getICEOutput = this.vessel.FindPartModulesImplementing<IDice>().FirstOrDefault();
- firstRun = false;
- }
- if (getICEOutput != null)
- {
- coupledICEOutput = 0f;
- float collectInputRPM = 0f;
- for (int i = 0; i < getAllICE.Count; i++)
- {
- if (getAllICE[i].lastCylForce > 0f && getAllICE[i].coupleOutput == true)
- {
- coupledICEOutput += getAllICE[i].lastCylForce;
- collectInputRPM += getAllICE[i].currentRPM;
- }
- }
- inputRPM = collectInputRPM / (float)getAllICE.Count;
- if (inputRPM > 0.0f)
- {
- if (currentGear == 0) inNeutral = true;
- if (currentGear == 1)
- {
- inNeutral = false;
- gearedForceMulti = (firstGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM / firstGear) / finalDrive;
- }
- if (currentGear == 2)
- {
- inNeutral = false;
- gearedForceMulti = (secondGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM / secondGear) / finalDrive;
- }
- if (currentGear == 3)
- {
- inNeutral = false;
- gearedForceMulti = (thirdGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM / thirdGear) / finalDrive;
- }
- if (currentGear == 4)
- {
- inNeutral = false;
- gearedForceMulti = (fourthGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM / fourthGear) / finalDrive;
- }
- if (currentGear == 5)
- {
- inNeutral = false;
- gearedForceMulti = (fifthGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM / fifthGear) / finalDrive;
- }
- if (currentGear == 6)
- {
- inNeutral = false;
- gearedForceMulti = (sixthGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM / sixthGear) / finalDrive;
- }
- if (inNeutral == true)
- {
- currentGear = 0;
- gearedForceMulti = 0f;
- rpmOutput = rpmOutput * 0.9995f;
- }
- if (inReverse == true)
- {
- inNeutral = false;
- gearedForceMulti = (reverseGear * finalDrive) * dmgMulti;
- rpmOutput = (inputRPM * reverseGear) / finalDrive;
- }
- }
- if (isDamaged == true) rpmOutput = 0f;
- }
- }
- public void ApplyDamage(float damageState)
- {
- print("Inside ApplyDamage for ICE!");
- if (damageState < 1f)
- {
- dmgMulti = damageState;
- }
- if (damageState == 1f)
- {
- dmgMulti = damageState;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement