Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- [KSPAddon(KSPAddon.Startup.EditorAny, false)]
- public class biggerEditor : MonoBehaviour
- {
- public SPHCamera SPHcam;
- public VABCamera VABcam;
- void Start()
- {
- if (!HighLogic.LoadedSceneIsFlight)
- {
- Debug.Log("Checking main cam");
- //Debug.Log("assigning sphcam");
- SPHcam = Camera.main.GetComponent<SPHCamera>();
- //Debug.Log("altering sphcam / " + SPHcam.enabled);
- SPHcam.maxHeight = 300f;
- SPHcam.maxDisplaceX = 2000f;
- SPHcam.maxDisplaceZ = 2000f;
- //Debug.Log("assigning vabcam");
- VABcam = Camera.main.GetComponent<VABCamera>();
- //Debug.Log("altering vabcam / " + VABcam.enabled);
- VABcam.maxHeight = 2000f;
- EditorLogic[] elogic = (EditorLogic[])FindObjectsOfType(typeof(EditorLogic));
- Debug.Log("Found logic: " + elogic.Length);
- for (int i = 0; i < elogic.Length; i++)
- {
- Debug.Log(elogic[i].gameObject.name);
- Debug.Log("Bounds" + elogic[i].editorBounds.extents);
- elogic[i].editorBounds.extents = new Vector3(1000f, 200f, 1000f);
- }
- }
- }
- }
- //********************************************
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using UnityEngine;
- class otherBP : PartModule
- {
- [KSPField]
- public string partType = "none";
- [KSPField]
- public float invWaterOffset = 0f;
- public float crewTimer;
- public float crewCoolDown = 10f;
- public float crushTimer = 1f;
- public float crushCoolDown = 15f;
- //public double partAltitude;
- //public AudioSource hullStress;
- public FXGroup crushSound = null;
- void Start()
- {
- if (partType == "crewBunk")
- {
- Transform curtainTopClosed = this.part.FindModelTransform("curtainTopClosed");
- curtainTopClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- Transform curtainBottomClosed = this.part.FindModelTransform("curtainBottomClosed");
- curtainBottomClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- }
- if (!GameDatabase.Instance.ExistsAudioClip("BoatPartsR3/Sounds/subPressure")) return;
- //print("getting past the sound condition 1");
- crushSound.audio = gameObject.AddComponent<AudioSource>();
- if (crushSound.audio != null)
- {
- //print("getting past the sound condition 2");
- crushSound.audio.volume = GameSettings.SHIP_VOLUME;
- crushSound.audio.rolloffMode = AudioRolloffMode.Logarithmic;
- crushSound.audio.dopplerLevel = 0f;
- crushSound.audio.panLevel = 1f;
- crushSound.audio.clip = GameDatabase.Instance.GetAudioClip("BoatPartsR3/Sounds/subPressure");
- crushSound.audio.loop = false;
- crushSound.audio.playOnAwake = false;
- }
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- crewTimer -= Time.deltaTime; // we will limit how often this checks/changes drag.
- if (crewTimer <= 0f)
- {
- crewTimer = crewCoolDown;
- if (partType == "crewBunk")
- {
- if (this.part.protoModuleCrew.Count == 1)
- {
- //must be one guy in there sleeping in the top
- Transform curtainTopClosed = this.part.FindModelTransform("curtainTopClosed");
- curtainTopClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- Transform curtainTopOpen = this.part.FindModelTransform("curtainTopOpen");
- curtainTopOpen.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- Transform curtainBottomClosed = this.part.FindModelTransform("curtainBottomClosed");
- curtainBottomClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- Transform curtainBottomOpen = this.part.FindModelTransform("curtainBottomOpen");
- curtainBottomOpen.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- }
- else if (this.part.protoModuleCrew.Count == 2)
- {
- //must be two guys in there sleeping in both spots
- Transform curtainTopClosed = this.part.FindModelTransform("curtainTopClosed");
- curtainTopClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- Transform curtainTopOpen = this.part.FindModelTransform("curtainTopOpen");
- curtainTopOpen.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- Transform curtainBottomClosed = this.part.FindModelTransform("curtainBottomClosed");
- curtainBottomClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- Transform curtainBottomOpen = this.part.FindModelTransform("curtainBottomOpen");
- curtainBottomOpen.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- }
- else if (this.part.protoModuleCrew.Count == 0)
- {
- //all empty
- Transform curtainTopClosed = this.part.FindModelTransform("curtainTopClosed");
- curtainTopClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- Transform curtainTopOpen = this.part.FindModelTransform("curtainTopOpen");
- curtainTopOpen.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- Transform curtainBottomClosed = this.part.FindModelTransform("curtainBottomClosed");
- curtainBottomClosed.GetComponents<MeshRenderer>().FirstOrDefault().enabled = false;
- Transform curtainBottomOpen = this.part.FindModelTransform("curtainBottomOpen");
- curtainBottomOpen.GetComponents<MeshRenderer>().FirstOrDefault().enabled = true;
- }
- }
- }
- //if (partType == "invertedWater" || partType == "deepWater")
- //{
- // partAltitude = Vector3.Distance(this.part.collider.transform.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- // double cameraAltitude = Vector3.Distance(Camera.main.transform.position, FlightGlobals.ActiveVessel.mainBody.position) - (FlightGlobals.ActiveVessel.mainBody.Radius);
- // Vector3d thisWayUp = (this.vessel.rigidbody.position - this.vessel.mainBody.position).normalized;
- // float distToWater = ((float)this.vessel.altitude + invWaterOffset) * -1f; // try this without the reverser!
- // if (cameraAltitude < 0.0d && cameraAltitude > -550.0d && FlightGlobals.ActiveVessel == this.vessel)
- // {
- // Transform activateInvWater = this.part.FindModelTransform("invertWater");
- // Transform activateDeepWater = this.part.FindModelTransform("deepWater");
- // Vector3 invertWaterOffset = thisWayUp * distToWater; //new Vector3(distToWater, 0f, 0f);
- // activateInvWater.transform.position = this.part.transform.position + invertWaterOffset; //set posi for invertwat
- // activateInvWater.transform.LookAt(vessel.mainBody.position);
- // activateInvWater.gameObject.SetActive(true);
- // activateDeepWater.gameObject.SetActive(false);
- // RenderSettings.fog = true;
- // RenderSettings.fogColor = new Color(0, 0.1f, 0.25f, 0.75f);
- // RenderSettings.fogDensity = 0.0003f;
- // RenderSettings.fogStartDistance = 300f;
- // RenderSettings.fogEndDistance = 2500f;
- // RenderSettings.fogMode = FogMode.ExponentialSquared;
- // this.part.SetHighlightColor(Color.clear);
- // this.part.SetHighlight(false);
- // Camera.main.clearFlags = CameraClearFlags.Depth;
- // }
- // else if (cameraAltitude >= 0.0f)
- // {
- // Transform activateInvWater = this.part.FindModelTransform("invertWater");
- // activateInvWater.gameObject.SetActive(false);
- // Transform activateDeepvWater = this.part.FindModelTransform("deepWater");
- // activateDeepvWater.gameObject.SetActive(false);
- // RenderSettings.fog = false;
- // Camera.main.clearFlags = CameraClearFlags.Depth;
- // }
- //else if (cameraAltitude <= -550.0d && FlightGlobals.ActiveVessel == this.vessel && partAltitude <= -550.0d)
- //{
- // Transform activateInvWater = this.part.FindModelTransform("invertWater");
- // activateInvWater.gameObject.SetActive(false);
- // Transform activateDeepWater = this.part.FindModelTransform("deepWater");
- // activateDeepWater.gameObject.SetActive(true);
- // activateDeepWater.transform.position = this.part.transform.position; // set posi for deepWat
- // RenderSettings.fog = false;
- // RenderSettings.fogColor = Color.black;
- // RenderSettings.fogDensity = 0.005f;
- // RenderSettings.fogStartDistance = 300f;
- // RenderSettings.fogEndDistance = 400f;
- // RenderSettings.fogMode = FogMode.ExponentialSquared;
- // Camera.main.clearFlags = CameraClearFlags.Depth;
- // crushTimer -= Time.deltaTime; // we will limit how often this sounds the warning and later checks for damage.
- // if (crushTimer <= 0f)
- // {
- // crushTimer = crushCoolDown;
- // crushSound.audio.Play();
- // ScreenMessages.PostScreenMessage(new ScreenMessage("Exceeding Safe Hull Pressure", 2f, ScreenMessageStyle.UPPER_CENTER));
- // ScreenMessages.PostScreenMessage(new ScreenMessage("Estimated Depth " + Mathf.Round(distToWater) + " m", 4f, ScreenMessageStyle.UPPER_CENTER));
- // ScreenMessages.PostScreenMessage(new ScreenMessage("Rate of Climb " + Mathf.Round((float)this.vessel.verticalSpeed) + " m/s", 6f, ScreenMessageStyle.UPPER_CENTER));
- // }
- //}
- //}
- }
- }
- }
- //******************************************
- public class idFloatCode : PartModule
- {
- public Transform buoyancyLever;
- public Vector3 actionPoint = new Vector3(0f, 0f, 0f);
- public Vector3 actionPoint2 = new Vector3(0f, 0f, 0f);
- public Vector3 actionPoint3 = new Vector3(0f, 0f, 0f);
- public Vector3 actionPoint4 = new Vector3(0f, 0f, 0f);
- public Vector3 apLift, ap2Lift, ap3Lift, ap4Lift;
- public double actionPointAltitude, actionPoint2Altitude, actionPoint3Altitude, actionPoint4Altitude; // new!
- public double hullBottom = 0.0, hullDraught = 0.0;
- [KSPField(guiActive = false, isPersistant = true)]
- public float hullYSize = 0f;
- [KSPField]
- public bool colDetect = false; // off by default. Set in CFG.
- public float gravityForce = 9.8f;
- public double partAltitude = 0.0d;
- [KSPField(guiActive = false, isPersistant = true)]
- public float manualDisplacementVolume = 0f; //alternate volume method.
- [KSPField]
- public float manualHullYSize = 0f;// alternate Y size method.
- public float floatMulti = 0.425f; // or no mulitplier!
- public float returnToDrag = 0f;
- [KSPField]
- public float floatPowerScale = 1f;//lower for larger ship parts...
- [KSPField(guiActive = false, isPersistant = true)]
- public float objVolume;
- [KSPField(guiActive = false, isPersistant = true)]
- public float restoreToVolume;
- public bool wasInWater = false;
- public float lastHitTime = 0f;
- public float waterImpactTolerance = 1.75f;
- public bool hullFractured = false;// this is temporary and only affects a floating part - is it sunk?
- public float hullExplosionResistance = 150f;// this is the impact speed required for the sink check...
- public float impactMass = 0f, collisionForce = 0f;
- public float startDragTimer = 10f;
- public float splashTimer = 2f;
- public float splashCooldown = 2f;
- public float dragTimer = 0.5f;
- public float dragCoolDown = 0.5f; //affects the time between drag checks and the smoothing between drag values.
- [KSPField]
- public float stabilForce = 10f;
- [KSPField]
- public float stabilOffset = 2f;
- //public float floatPowerTimer = 0f;
- //public float floatPowerCool = 0.125f; //affects the time between water displacement checks and smoothing.
- public bool splashed = false;
- //public float setShipTimer = 10f;
- [KSPField]
- public bool floatBypass = false;
- [KSPField]
- public bool bypassACPart = false;
- [KSPField]
- public float floatPartType = 0f; //0 is normal 1 is bow or stern 2 is main hull/float 3 is very small ship 4 is
- [KSPField]
- public bool isMultiPointFloat = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Uses WakeFX: ")]
- public bool useWakeFX = false;
- public GameObject wakeFX;
- public Transform wakeTPoint;
- public bool initialized = false;
- private ModuleEngines nukeEngine = new ModuleEngines();
- [KSPField]
- public double floatHeight = 0.0d; //change the level where the part will maintain float
- [KSPField]
- public float coefDragInWater = 0.008f;
- [KSPField]
- public float counterLever = 0.25f;
- public double waterDisplacement = 0.0; //gets calculated later.
- [KSPField(guiActive = false, isPersistant = true)]
- public bool checkShipOnce = true;
- [KSPField(guiActive = false, guiName = "Part Volume", isPersistant = true)]
- public float thisPartMeshVolume;
- public float SignedVolumeOfTriangle(Vector3 p1, Vector3 p2, Vector3 p3)
- {
- float v321 = p3.x * p2.y * p1.z;
- float v231 = p2.x * p3.y * p1.z;
- float v312 = p3.x * p1.y * p2.z;
- float v132 = p1.x * p3.y * p2.z;
- float v213 = p2.x * p1.y * p3.z;
- float v123 = p1.x * p2.y * p3.z;
- return (1.0f / 6.0f) * (-v321 + v231 + v312 - v132 - v213 + v123);
- }
- float VolumeOfMesh(Mesh mesh)
- {
- float volume = 0;
- Vector3[] vertices = mesh.vertices;
- int[] triangles = mesh.triangles;
- for (int i = 0; i < mesh.triangles.Length; i += 3)
- {
- Vector3 p1 = vertices[triangles[i + 0]];
- Vector3 p2 = vertices[triangles[i + 1]];
- Vector3 p3 = vertices[triangles[i + 2]];
- volume += SignedVolumeOfTriangle(p1, p2, p3);
- }
- return Mathf.Abs(volume);
- }
- public override void OnStart(StartState state)
- {
- base.OnStart(state);
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- print(this.vessel.parts.Count);
- foreach (Part makeFCP in this.vessel.parts) // add float code to any docked aircraft and set to acbypass.
- {
- if (!makeFCP.Modules.Contains("idFloatCode") && !makeFCP.vessel.isEVA && !makeFCP.Modules.Contains("ModuleCommand"))
- {
- idFloatCode addedFC = makeFCP.gameObject.AddComponent<idFloatCode>();
- addedFC.floatBypass = true;
- addedFC.coefDragInWater = 6f;
- addedFC.bypassACPart = true;
- addedFC.waterImpactTolerance = 1.05f;
- addedFC.initialized = true;
- addedFC.buoyancyLever = this.part.transform;
- addedFC.startDragTimer = 10f;
- if (addedFC != null)
- {
- print("Added float code to :" + makeFCP.partName + "water impact spd : " + makeFCP.crashTolerance * addedFC.waterImpactTolerance);
- }
- }
- }
- initialized = true;
- buoyancyLever = this.part.transform;
- startDragTimer = 10f;
- }
- }
- public void Update()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- if (part.partBuoyancy != null)
- {
- Destroy(part.partBuoyancy);
- //Debug.Log("Remove Stock Float Nightmare");
- }
- }
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight || !initialized) return;
- {
- # region StartDragTimer
- if (startDragTimer > 0f)
- {
- startDragTimer -= 1f;
- if (startDragTimer < 1f)
- {
- startDragTimer = 0f; //must become exactly 0.
- }
- float smoothDragTarget = coefDragInWater * ((float)hullDraught * 0.5f); // ramp up drag by the amount of hull surface touching the water and the rotational speed.
- if (smoothDragTarget > 0f)
- {
- base.rigidbody.drag = smoothDragTarget; //smooth the adjustment.
- print("Load Drag Enabled!");
- }
- if (this.part.rigidbody != null)
- {
- this.part.rigidbody.detectCollisions = false;
- }
- }
- else
- {
- if (this.part.rigidbody != null)
- {
- this.part.rigidbody.detectCollisions = true;
- }
- }
- #endregion
- if (this.part.transform != null && this.vessel.mainBody != null && useWakeFX == false)
- {
- partAltitude = Vector3.Distance(this.part.transform.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- else if (this.part.transform != null && this.vessel.mainBody != null && useWakeFX == true)
- {
- try
- {
- wakeTPoint = this.part.FindModelTransform("wakePoint");
- }
- catch
- {
- print("Problem locating wakePoint");
- }
- if (wakeTPoint != null)
- {
- partAltitude = Vector3.Distance(wakeTPoint.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- else
- {
- partAltitude = Vector3.Distance(this.part.transform.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius; //use this as backup incase wakeTpoint is null for some reason.
- }
- if (wakeTPoint.position == this.part.transform.position)
- {
- print("what the hell is going on!");
- }
- }
- #region Float Bypass false
- if (floatBypass == false)
- {
- //#region stabilizer test
- //if (rigidbody != null)
- //{
- // rigidbody.AddForceAtPosition(((this.vessel.transform.position - this.vessel.mainBody.position).normalized) * stabilForce, (this.vessel.transform.position - this.vessel.mainBody.position) * stabilOffset);
- // rigidbody.AddForceAtPosition((-(this.vessel.transform.position - this.vessel.mainBody.position).normalized) * stabilForce, -(this.vessel.transform.position - this.vessel.mainBody.position) * stabilOffset);
- //}
- //#endregion
- if (checkShipOnce == true) // persistant.. so only ever runs once per ship instance.
- {
- if (useWakeFX == true)
- {
- Debug.Log("Yes this should be using WakeFX!!!");
- }
- if (manualDisplacementVolume == 0f && this.part.collider != null)
- {
- objVolume = (this.part.collider.bounds.size.y * this.part.collider.bounds.size.x * this.part.collider.bounds.size.z);
- if (objVolume < 1f)
- {
- checkMeshVolume();
- objVolume = thisPartMeshVolume;
- }
- }
- else if (manualDisplacementVolume != 0f)
- {
- objVolume = manualDisplacementVolume;
- }
- restoreToVolume = objVolume;
- if (manualHullYSize == 0f)
- {
- hullYSize = 3f;
- }
- else if (manualHullYSize != 0f)
- {
- hullYSize = manualHullYSize;
- }
- checkShipOnce = false;
- }
- Vector3d thisWayUp = (this.vessel.transform.position - this.vessel.mainBody.position).normalized;
- dragTimer -= Time.deltaTime; // we will limit how often this checks/changes drag.
- if (dragTimer <= 0f)
- {
- dragTimer = dragCoolDown;
- if (FlightGlobals.ActiveVessel == this.vessel && this.part.WaterContact == true)
- {
- float smoothDragTarget = coefDragInWater * ((float)hullDraught * 0.0005f); // ramp up drag by the amount of hull surface touching the water and the rotational speed.
- if (smoothDragTarget > 0f)
- {
- base.rigidbody.drag = smoothDragTarget; //smooth the adjustment.
- //print(smoothDragTarget);
- }
- else if (smoothDragTarget <= 0f)
- {
- base.rigidbody.drag = coefDragInWater;
- }
- }
- else if (FlightGlobals.ActiveVessel != this.vessel && this.part.WaterContact == true && base.rigidbody != null)
- {
- float smoothDragTarget = coefDragInWater + ((float)hullDraught * 0.75f) + ((float)this.vessel.verticalSpeed * 2.75f); //carrier as stationary.
- if (smoothDragTarget > 0f) base.rigidbody.drag = smoothDragTarget;
- else if (smoothDragTarget <= 0f) base.rigidbody.drag = coefDragInWater + 0.75f;
- }
- }
- if (hullYSize < 1f)
- {
- hullYSize = 1f;
- }
- if (objVolume < 1f)
- {
- print("WARNING!!! " + this.part.partName + " is not calculating any volume, a base of 1m3 has been assigned.");
- objVolume = 1f;
- }
- hullBottom = partAltitude - (partAltitude - (hullYSize * 0.5d)); //alt of the bottom of the ship
- hullDraught = (partAltitude - hullBottom) * -1f;//reverse it
- if (hullDraught > hullYSize) hullDraught = hullYSize;//the max draught is the y height of the float collider.
- waterDisplacement = (double)objVolume * (hullDraught / hullYSize); //displacement is proportionate to the part of the float under water.
- if (floatPartType == 2)
- {
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("buoyPoint"); //placed gameobject in part - simply the point where force is applied.
- actionPoint = buoyancyLever.position;
- }
- catch
- {
- actionPoint = this.part.CenterOfBuoyancy;
- //Debug.Log("couldn't find custom buoyPoint in model! using part center.");
- }
- if (partAltitude <= floatHeight)//floatPartType 2 uses the floatHeight variable to set float level... where Type 1 and 3 are preset.
- {
- Vector3 uplift = thisWayUp * ((((waterDisplacement * floatPowerScale) * floatMulti)) - this.vessel.verticalSpeed);
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint);
- }
- else if (partAltitude > 0.0d)
- {
- Vector3 uplift = -thisWayUp * (gravityForce);
- this.part.rigidbody.AddForceAtPosition(uplift, this.part.transform.position);
- }
- }
- else if (floatPartType == 3) // small craft designation
- {
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("buoyPoint"); //placed gameobject in part - simply the point where force is applied.
- actionPoint = buoyancyLever.position;
- }
- catch
- {
- actionPoint = this.part.CenterOfBuoyancy;
- //Debug.Log("couldn't find custom buoyPoint in model! using part center.");
- }
- if (partAltitude <= -0.125d)
- {
- Vector3 uplift = thisWayUp * ((((waterDisplacement * floatPowerScale) * floatMulti)) - this.vessel.verticalSpeed);
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint);
- }
- else if (partAltitude > -0.125d)
- {
- Vector3 uplift = -thisWayUp * (gravityForce);
- this.part.rigidbody.AddForceAtPosition(uplift, this.part.rigidbody.transform.position);
- }
- }
- else if (floatPartType == 4 || isMultiPointFloat == true)//4 is a multifloat part with named colliders 'levelCollider1 or 2 etc.' edit... multi-point bool allowing other part types to take advantage of this.
- {
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("levelCollider1"); //placed gameobject in part - simply the point where force is applied.
- actionPoint = buoyancyLever.position;
- actionPointAltitude = Vector3.Distance(actionPoint, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- catch
- {
- actionPoint = this.part.CenterOfBuoyancy;
- Debug.Log("couldn't find levelCollider1 in model! using part center.");
- }
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("levelCollider2"); //placed gameobject in part - simply the point where force is applied.
- actionPoint2 = buoyancyLever.position;
- actionPoint2Altitude = Vector3.Distance(actionPoint2, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- catch
- {
- actionPoint2 = this.part.CenterOfBuoyancy;
- Debug.Log("couldn't find levelCollider2 in model! using part center.");
- }
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("levelCollider3"); //placed gameobject in part - simply the point where force is applied.
- actionPoint3 = buoyancyLever.position;
- actionPoint3Altitude = Vector3.Distance(actionPoint3, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- catch
- {
- actionPoint3 = this.part.CenterOfBuoyancy;
- //Debug.Log("couldn't find levelCollider3 in model! using part center.");
- }
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("levelCollider4"); //placed gameobject in part - simply the point where force is applied.
- actionPoint4 = buoyancyLever.position;
- actionPoint4Altitude = Vector3.Distance(actionPoint4, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- catch
- {
- actionPoint4 = this.part.CenterOfBuoyancy;
- //Debug.Log("couldn't find levelCollider4 in model! using part center.");
- }
- if (floatPartType != 1)//not a bow or stern
- {
- if (actionPointAltitude < 0.0d)
- {
- double onePortion = ((-actionPointAltitude + 1.0) * 2f); // if the corner is higher than center it will return a lower multiplier.
- if (onePortion < 0.0) onePortion = 0.0;
- if (onePortion > 5.0) onePortion = 5.0;
- apLift = thisWayUp * (((((waterDisplacement * floatPowerScale) * (float)onePortion)) - (this.vessel.verticalSpeed * 0.1f)) * 0.25f);
- //this.part.rigidbody.AddForceAtPosition(apLift, actionPoint);
- }
- else if (actionPointAltitude > 0.0d) // this is downward force on the whole part if it's center is over waterlevel.
- {
- Vector3 uplift = -thisWayUp * (gravityForce * ((this.part.mass * 10f) * 0.25f));
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint);
- }
- if (actionPoint2Altitude < 0.0d)
- {
- double twoPortion = ((-actionPoint2Altitude + 1.0) * 2f); // if the corner is higher than center it will return a lower multiplier.
- if (twoPortion < 0.0) twoPortion = 0.0;
- if (twoPortion > 5.0) twoPortion = 5.0;
- ap2Lift = thisWayUp * (((((waterDisplacement * floatPowerScale) * (float)twoPortion)) - (this.vessel.verticalSpeed * 0.1f)) * 0.25f);
- //this.part.rigidbody.AddForceAtPosition(ap2Lift, actionPoint2);
- }
- else if (actionPoint2Altitude > 0.0d) // this is downward force on the whole part if it's center is over waterlevel.
- {
- Vector3 uplift = -thisWayUp * (gravityForce * ((this.part.mass * 10f) * 0.25f));
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint2);
- }
- if (actionPoint3Altitude < 0.0d)
- {
- double threePortion = ((-actionPoint3Altitude + 1.0) * 2f); // if the corner is higher than center it will return a lower multiplier.
- if (threePortion < 0.0) threePortion = 0.0;
- if (threePortion > 5.0) threePortion = 5.0;
- ap3Lift = thisWayUp * (((((waterDisplacement * floatPowerScale) * (float)threePortion)) - (this.vessel.verticalSpeed * 0.1f)) * 0.25f);
- //this.part.rigidbody.AddForceAtPosition(ap3Lift, actionPoint3);
- }
- else if (actionPoint3Altitude > 0.0d) // this is downward force on the whole part if it's center is over waterlevel.
- {
- Vector3 uplift = -thisWayUp * (gravityForce * ((this.part.mass * 10f) * 0.25f));
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint3);
- }
- if (actionPoint4Altitude < 0.0d)
- {
- double fourPortion = ((-actionPoint4Altitude + 1.0) * 2f); // if the corner is higher than center it will return a lower multiplier.
- if (fourPortion < 0.0) fourPortion = 0.0;
- if (fourPortion > 5.0) fourPortion = 5.0;
- ap4Lift = thisWayUp * (((((waterDisplacement * floatPowerScale) * (float)fourPortion)) - (this.vessel.verticalSpeed * 0.1f)) * 0.25f);
- //this.part.rigidbody.AddForceAtPosition(ap4Lift, actionPoint4);
- }
- else if (actionPoint4Altitude > 0.0d) // this is downward force on the corner part mass if this corner is over waterlevel.
- {
- Vector3 uplift = -thisWayUp * (gravityForce * ((this.part.mass * 10f) * 0.25f));
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint4);
- }
- if (partAltitude < 0.0d)
- {
- this.part.rigidbody.AddForceAtPosition(apLift, actionPoint);
- this.part.rigidbody.AddForceAtPosition(ap2Lift, actionPoint2);
- this.part.rigidbody.AddForceAtPosition(ap3Lift, actionPoint3);
- this.part.rigidbody.AddForceAtPosition(ap4Lift, actionPoint4);
- }
- if (partAltitude >= 0.0d) // this is downward force on the whole part mass if it's center is at or over the waterlevel.
- {
- Vector3 uplift = -thisWayUp * (gravityForce * (this.part.mass * 10f)); //orig
- this.part.rigidbody.AddForceAtPosition(uplift, this.part.rigidbody.transform.position); //2nd orig
- //print("Applying all part gravity boost");
- }
- }
- else if (floatPartType == 1)// nested - even the multi-point bow or stern needs offset.
- {
- if (partAltitude <= 0.0d)
- {
- Vector3 uplift = thisWayUp * ((((waterDisplacement * floatPowerScale) * floatMulti)) - this.vessel.verticalSpeed);
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint);
- }
- if (partAltitude <= 0.0d)
- {
- Vector3 uplift = thisWayUp * ((((waterDisplacement * floatPowerScale) * floatMulti)) - this.vessel.verticalSpeed);
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint2);
- }
- else if (partAltitude > 0.5d)
- {
- Vector3 uplift = -thisWayUp * (gravityForce * (this.part.mass * 10f));
- this.part.rigidbody.AddForceAtPosition(uplift, this.part.rigidbody.transform.position);
- }
- }
- }
- else if (floatPartType == 1 && isMultiPointFloat == false)//the single point bow
- {
- try // Find the transform from the unity setup.
- {
- buoyancyLever = this.part.FindModelTransform("buoyPoint"); //placed gameobject in part - simply the point where force is applied.
- actionPoint = buoyancyLever.position;
- }
- catch
- {
- actionPoint = this.part.CenterOfBuoyancy;
- //Debug.Log("couldn't find custom buoyPoint in model! using part center.");
- }
- if (partAltitude <= 0.0d)
- {
- Vector3 uplift = thisWayUp * ((((waterDisplacement * floatPowerScale) * floatMulti) - this.part.rigidbody.velocity.y) - this.vessel.verticalSpeed);
- this.part.rigidbody.AddForceAtPosition(uplift, actionPoint);
- }
- else if (partAltitude > 0.0d)
- {
- Vector3 uplift = -thisWayUp * (gravityForce);
- this.part.rigidbody.AddForceAtPosition(uplift, this.part.rigidbody.transform.position);
- }
- }
- }
- #endregion
- if (floatBypass == true)
- {
- BypassSplashed();
- }
- #region Water Splash and Contact
- if (partAltitude <= 0.0d)// && this.vessel.altitude < 20.0d)
- {
- # region WakeFX
- if (useWakeFX == true)
- {
- if (wakeFX == null)
- {
- //setWakeFX(); //pick the right effect - right now just one
- try
- {
- wakeFX = GameDatabase.Instance.GetModel("BoatPartsR5/Effects/IDWakeFX/model");
- }
- catch
- {
- print("Problem locating wakeFX");
- }
- if (wakeFX != null)
- {
- wakeFX.SetActive(true);
- if (wakeTPoint != null)
- {
- wakeFX.transform.position = wakeTPoint.position;
- wakeFX.transform.parent = wakeTPoint;
- wakeFX.transform.LookAt(-wakeTPoint.transform.right);
- }
- else
- {
- wakeFX.transform.position = this.part.transform.position;
- wakeFX.transform.parent = this.part.transform;
- wakeFX.transform.LookAt(-this.part.transform.right);
- }
- wakeFX.gameObject.layer = 0;
- }
- }
- if (this.vessel.horizontalSrfSpeed < 5f)
- {
- KSPParticleEmitter findKspEmitter = wakeFX.GetComponentInChildren<KSPParticleEmitter>();
- if (findKspEmitter != null)
- {
- findKspEmitter.enabled = false;
- findKspEmitter.emit = false;
- //print("Found an KSPEmitter");
- }
- }
- else
- {
- KSPParticleEmitter findKspEmitter = wakeFX.GetComponentInChildren<KSPParticleEmitter>();
- if (findKspEmitter != null)
- {
- findKspEmitter.enabled = true;
- findKspEmitter.emit = true;
- //print("Found an KSPEmitter");
- findKspEmitter.transform.rotation = Quaternion.identity;
- findKspEmitter.sizeGrow = (float)this.vessel.horizontalSrfSpeed * 0.0025f;
- }
- }
- }
- # endregion
- //print("check1");
- splashed = true;
- wasInWater = true;
- if (this.part != null)
- {
- this.part.WaterContact = true;
- this.part.vessel.Splashed = true;
- }
- //print("check2");
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "IntakeAir" && this.part.vessel.IsControllable)
- {
- resource.amount = 0.0;
- //print("Found Intake Air - flooding with water!");
- }
- }
- //print("check3");
- foreach (Part checkPart in this.vessel.parts) // add float code to any docked aircraft and set to bypass.
- {
- if (checkPart.Modules.Contains("ModuleResourceIntake") && checkPart.vessel.IsControllable)
- {
- ModuleResourceIntake floodIntake = checkPart.FindModulesImplementing<ModuleResourceIntake>().FirstOrDefault();
- if (floodIntake != null && floodIntake.resourceName == "IntakeAir")
- {
- floodIntake.isEnabled = false;
- floodIntake.intakeEnabled = false;
- floodIntake.enabled = false;
- }
- }
- }
- //print("check4");
- if (this.part.rigidbody != null)
- {
- float checkWImpact = this.part.crashTolerance * this.waterImpactTolerance;
- if ((float)this.vessel.horizontalSrfSpeed > checkWImpact || this.part.rigidbody.velocity.magnitude > checkWImpact) // && startDragTimer <= 0f
- {
- //print("Part splashed down at " + this.part.rigidbody.velocity.magnitude);
- GameEvents.onCrashSplashdown.Fire(new EventReport(FlightEvents.SPLASHDOWN_CRASH, this.part, this.part.partInfo.title, "ocean", 0, "Terminal Water Impact!!!"));
- if (this.part.explosionPotential >= 0.5f)
- {
- FXMonger.Explode(this.part, this.part.transform.position, this.part.explosionPotential);
- }
- else
- {
- FXMonger.Splash(this.part.transform.position, this.part.rigidbody.velocity.magnitude / 75f);
- }
- this.part.Die();
- return;
- }
- }
- splashTimer -= Time.deltaTime;
- if (splashTimer <= 0f)
- {
- splashTimer = splashCooldown;
- if (this.part.vessel.rootPart.rigidbody != null)
- {
- if (this.part.vessel.rootPart.rigidbody.velocity.magnitude > 50f)
- {
- if (Vector3.Distance(base.transform.position, FlightGlobals.camera_position) < 50f)
- {
- FXMonger.Splash(base.transform.position, base.rigidbody.velocity.magnitude / 100f);
- }
- }
- }
- }
- //print("check6");
- }
- else
- {
- if (partAltitude > 0.0d && wasInWater == true)
- {
- //wakeFX = null;
- splashed = false;
- if (this.part != null)
- {
- this.part.WaterContact = false;
- this.part.vessel.Splashed = false;
- this.part.vessel.checkSplashed();
- if (this.part.rigidbody != null)
- {
- this.part.rigidbody.drag = 0.0001f;
- returnToDrag = 0.0001f;
- }
- }
- }
- }
- # endregion
- //if (this.vessel.horizontalSrfSpeed < 1f) wakeFX = null;
- }
- }
- public void BypassSplashed()
- {
- if (this.partAltitude <= 0.0d)
- {
- if (this.part.rigidbody != null)
- {
- this.part.rigidbody.drag = coefDragInWater;
- }
- }
- else
- {
- if (this.part.rigidbody != null)
- {
- this.part.rigidbody.drag = returnToDrag;
- if (bypassACPart == false)
- {
- this.part.rigidbody.drag = coefDragInWater * 2.25f;
- waterImpactTolerance = 1.7f;
- }
- else
- {
- waterImpactTolerance = 1.05f;
- }
- }
- }
- }
- public void ApplyDamage(float damageState)
- {
- if (damageState < 1f)//normal/fixed state.... floats
- {
- //this.floatBypass = false;
- this.objVolume = restoreToVolume * damageState; // should reduce float ability as it gets damaged.
- }
- if (damageState == 1f)//normal/fixed state.... floats
- {
- checkShipOnce = true;
- }
- //print("idFloatCode: Setting damage state to " + damageState + " object volume is now " + objVolume);
- }
- public void checkMeshVolume()
- {
- float runningTotal = 0f;
- MeshFilter[] getAllMeshes = base.part.GetComponentsInChildren<MeshFilter>();
- foreach (MeshFilter mF in getAllMeshes)
- {
- if (mF != null)
- {
- runningTotal += VolumeOfMesh(mF.sharedMesh);
- }
- }
- //Mesh mesh = this.part.GetComponentInChildren<MeshFilter>().sharedMesh;
- //thisPartMeshVolume = VolumeOfMesh(mesh);
- thisPartMeshVolume = runningTotal;
- //print("Backup method: The mesh volume of the " + this.part.partName + " mesh is " + thisPartMeshVolume + " m3");
- }
- }
- //****************************************************
- public class neutralBuoy : PartModule
- {
- [KSPField(guiActive = true, guiName = "Auto Buoy Active")]
- public bool autoNeutralOn = false;
- public string verticalDirection = "neutral";
- public bool madeAdjustment = false;
- public float adjTimer = 1f;
- public float adjTimerCooldown = 1f;
- public int autoNMode = 1;
- [KSPEvent(name = "ActivateAutoNeutralBuoy", active = true, guiActive = true, guiName = "Activate Auto Neutral")]
- public void doAutoNeutral()
- {
- if (verticalDirection != "neutral")//if it's already neutral don't activate.
- {
- autoNeutralOn = true; // this enables the process. - should shut off automatically when it reaches neutral status.
- }
- }
- [KSPAction("Auto Neutral Buoyancy")]
- public void toggleTheAutoNeutralSystem(KSPActionParam param)
- {
- doAutoNeutral();
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- adjTimer -= Time.deltaTime;
- if (adjTimer <= 0f)
- {
- adjTimer = adjTimerCooldown;//reset timer
- if (this.vessel.verticalSpeed > 0.01d)//find the direction
- {
- verticalDirection = "up";
- }
- else if (this.vessel.verticalSpeed < -0.01d)
- {
- verticalDirection = "down";
- }
- else if (this.vessel.verticalSpeed < 0.01d && this.vessel.verticalSpeed > -0.01d)
- {
- verticalDirection = "neutral";
- autoNeutralOn = false; // shut off the process.
- }
- madeAdjustment = false;
- }
- if (verticalDirection != "neutral" && autoNeutralOn == true && madeAdjustment == false)
- {
- if (verticalDirection == "up")
- {
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "WaterBallast")
- {
- if (vessel.verticalSpeed > 1.0d)
- {
- resource.amount = resource.amount + 1.5d;
- //print("Found WaterBallast - adding this resource!");
- }
- else if (vessel.verticalSpeed < 1.0d)
- {
- resource.amount = resource.amount + 0.18d;
- //print("Found WaterBallast - adding this resource!");
- }
- }
- if (resource.resourceName == "BallastGas")
- {
- if (vessel.verticalSpeed > 1.0d)
- {
- resource.amount = resource.amount - 1.5d;
- //print("Found BallastGas - removing this resource!");
- }
- else if (vessel.verticalSpeed < 1.0d)
- {
- resource.amount = resource.amount - 0.18d;
- //print("Found BallastGas - removing this resource!");
- }
- }
- }
- }
- else if (verticalDirection == "down")
- {
- PartResourceList resourceList = this.part.Resources;
- foreach (PartResource resource in resourceList)
- {
- if (resource.resourceName == "WaterBallast")
- {
- if (vessel.verticalSpeed < -1.0d)
- {
- resource.amount = resource.amount - 1.5d;
- //print("Found WaterBallast - removing this resource!");
- }
- if (vessel.verticalSpeed > -1.0d)
- {
- resource.amount = resource.amount - 0.18d;
- //print("Found WaterBallast - removing this resource!");
- }
- }
- if (resource.resourceName == "BallastGas")
- {
- if (vessel.verticalSpeed < -1.0d)
- {
- resource.amount = resource.amount + 1.5d;
- //print("Found BallastGas - adding this resource!");
- }
- if (vessel.verticalSpeed > -1.0d)
- {
- resource.amount = resource.amount + 0.18d;
- //print("Found BallastGas - adding this resource!");
- }
- }
- }
- }
- madeAdjustment = true;
- }
- }
- }
- }
- public class neutralPitch : PartModule
- {
- public bool doItOnce = true;
- public Transform bowPoint;
- public Transform sternPoint;
- public Part bowPart;
- public Part sternPart;
- [KSPField(guiActive = true, guiName = "Auto Pitch Active")]
- public bool autoNeutralOn = false;
- public string dominantPitch = "neutral";
- public bool madeAdjustment = false;
- public float adjTimer = 3f;
- public float adjTimerCooldown = 3f;
- //public int autoNMode = 1;
- public double bowAltitude = 0.0;
- public double sternAltitude = 0.0;
- public double altDif = 0.0;
- [KSPEvent(name = "UseAutoPitch", active = true, guiActive = true, guiName = "Auto Pitch")]
- public void doPitchLevel()
- {
- if (autoNeutralOn == false)
- {
- autoNeutralOn = true;
- }
- else if (autoNeutralOn == true)
- {
- autoNeutralOn = false;
- }
- }
- [KSPAction("Auto Pitch Control")]
- public void toggleAutoPitch(KSPActionParam param)
- {
- doPitchLevel();
- }
- public void FixedUpdate()
- {
- if (HighLogic.LoadedSceneIsFlight)
- {
- if (doItOnce == true)
- {
- print("Running doItOnce");
- print(this.vessel.parts.Count);
- foreach (Part p in this.vessel.parts)
- {
- if (p.FindModelTransform("bowPoint") == true)
- {
- bowPoint = p.FindModelTransform("bowPoint");
- bowPart = p;
- }
- if (p.FindModelTransform("sternPoint") == true)
- {
- sternPoint = p.FindModelTransform("sternPoint");
- sternPart = p;
- }
- }
- if (sternPoint != null && bowPoint != null)
- {
- doItOnce = false;
- print("Found both Bow and Stern Points");
- }
- }
- if (bowPoint != null && sternPoint != null && this.vessel.mainBody != null)
- {
- bowAltitude = Vector3.Distance(bowPoint.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- sternAltitude = Vector3.Distance(sternPoint.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- adjTimer -= Time.deltaTime;
- if (adjTimer <= 0f)
- {
- adjTimer = adjTimerCooldown;//reset timer
- if (bowAltitude < sternAltitude - 0.125)//find the pitch
- {
- dominantPitch = "negative"; //bow down
- }
- else if (bowAltitude > sternAltitude + 0.125)
- {
- dominantPitch = "positive";
- }
- else if (bowAltitude > sternAltitude - 0.125 && bowAltitude < sternAltitude + 0.125)
- {
- dominantPitch = "neutral";
- //autoNeutralOn = false; // shut off the process.
- }
- madeAdjustment = false;
- }
- if (dominantPitch != "neutral" && autoNeutralOn == true && madeAdjustment == false)
- {
- if (dominantPitch == "negative")//bow down
- {
- //print("inside negative");
- bool proceedExchange = false;
- double exchAmount = 0.0d;
- if (bowPoint != null)
- {
- PartResourceList resourceListBow = bowPart.Resources;
- foreach (PartResource resource in resourceListBow)
- {
- if (resource.resourceName == "WaterBallast")
- {
- float cRModifier = 1f;
- if (this.vessel.GetTotalMass() > 40f)
- {
- cRModifier = 5f;
- }
- else
- {
- cRModifier = 1f;
- }
- if (altDif > 1.5d && resource.amount >= (0.25d * cRModifier))
- {
- resource.amount = resource.amount - (0.25d * cRModifier);
- proceedExchange = true;
- exchAmount = (0.25d * cRModifier);
- //print("Found WaterBallast - removing this resource!");
- }
- else if (altDif < 1.5d && resource.amount >= (0.08d * cRModifier) || altDif > 1.5d && resource.amount < (0.25d * cRModifier) && resource.amount >= (0.08d * cRModifier))
- {
- resource.amount = resource.amount - (0.08d * cRModifier);
- proceedExchange = true;
- exchAmount = (0.08d * cRModifier);
- //print("Found WaterBallast - removing this resource!");
- }
- }
- }
- }
- if (sternPoint != null)
- {
- PartResourceList resourceListStern = sternPart.Resources;
- foreach (PartResource resource in resourceListStern)
- {
- if (resource.resourceName == "WaterBallast" && proceedExchange == true)
- {
- resource.amount = resource.amount + exchAmount;
- //print("Found WaterBallast - adding this resource!");
- }
- }
- }
- }
- else if (dominantPitch == "positive")//bow up
- {
- //print("inside positive");
- bool proceedExchange = false;
- double exchAmount = 0.0d;
- if (sternPoint != null)
- {
- PartResourceList resourceListStern = sternPart.Resources;
- foreach (PartResource resource in resourceListStern)
- {
- if (resource.resourceName == "WaterBallast")
- {
- float cRModifier = 1f;
- if (this.vessel.GetTotalMass() > 40f)
- {
- cRModifier = 5f;
- }
- else
- {
- cRModifier = 1f;
- }
- if (altDif > 1.5d && resource.amount >= (0.25d * cRModifier))
- {
- resource.amount = resource.amount - (0.25d * cRModifier);
- proceedExchange = true;
- exchAmount = (0.25d * cRModifier);
- //print("Found WaterBallast - removing this resource!");
- }
- else if (altDif < 1.5d && resource.amount >= (0.08d * cRModifier) || altDif > 1.5d && resource.amount < (0.25d * cRModifier) && resource.amount >= (0.08d * cRModifier))
- {
- resource.amount = resource.amount - (0.08d * cRModifier);
- proceedExchange = true;
- exchAmount = (0.08d * cRModifier);
- //print("Found WaterBallast - removing this resource!");
- }
- }
- }
- }
- if (bowPoint != null)
- {
- PartResourceList resourceListBow = bowPart.Resources;
- foreach (PartResource resource in resourceListBow)
- {
- if (resource.resourceName == "WaterBallast" && proceedExchange == true)
- {
- resource.amount = resource.amount + exchAmount;
- //print("Found WaterBallast - adding this resource!");
- }
- }
- }
- }
- madeAdjustment = true;
- }
- }
- }
- }
- //************************************************
- [KSPAddon(KSPAddon.Startup.Flight, false)]
- public class rangeBooster : MonoBehaviour
- {
- public bool doItOnce = true;
- public bool LRMouseBypass = false;
- public bool targeterOverride = false;
- public int overrideCategory = 0;
- public float rangeToRCast;
- private Vessel tVessel = null;
- private Vessel pVessel = null;
- public static rangeBooster Instance = null;
- void Start()
- {
- pVessel = FlightGlobals.ActiveVessel;
- Vessel.loadDistance = 10250f; //10250f
- Vessel.unloadDistance = 10000f; //10000f
- rangeToRCast = 10000f;
- Instance = this;
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 9900f;
- v.distanceLandedUnpackThreshold = 10150f;
- v.distancePackThreshold = 9990f;
- v.distanceUnpackThreshold = 10150f;
- }
- }
- }
- public void Update()
- {
- if (targeterOverride == false && LRMouseBypass == false)
- {
- if (Vessel.unloadDistance < 10000f || Vessel.loadDistance < 10250f)
- {
- Vessel.loadDistance = 10250f;
- Vessel.unloadDistance = 10000f;
- rangeToRCast = 10000f;
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 9950f;
- v.distanceLandedUnpackThreshold = 10150f;
- v.distancePackThreshold = 9950f;
- v.distanceUnpackThreshold = 10150f;
- }
- }
- }
- }
- if (targeterOverride == true || LRMouseBypass == true)
- {
- if (overrideCategory == 1)
- {
- if (Vessel.unloadDistance < 19000f || Vessel.loadDistance < 19250f)
- {
- Vessel.loadDistance = 19250f;
- Vessel.unloadDistance = 19000f;
- rangeToRCast = 19000f;
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 18950f;
- v.distanceLandedUnpackThreshold = 19150f;
- v.distancePackThreshold = 18950f;
- v.distanceUnpackThreshold = 19150f;
- }
- }
- }
- }
- if (overrideCategory == 2)
- {
- if (Vessel.unloadDistance < 49000f || Vessel.loadDistance < 49250f)
- {
- Vessel.loadDistance = 49250f;
- Vessel.unloadDistance = 49000f;
- rangeToRCast = 49000f;
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 48950f;
- v.distanceLandedUnpackThreshold = 49150f;
- v.distancePackThreshold = 48950f;
- v.distanceUnpackThreshold = 49150f;
- }
- }
- }
- }
- if (overrideCategory == 3)
- {
- if (Vessel.unloadDistance < 99000f || Vessel.loadDistance < 99250f)
- {
- Vessel.loadDistance = 99250f;
- Vessel.unloadDistance = 99000f;
- rangeToRCast = 99000f;
- var sceneVessels = FindObjectsOfType(typeof(Vessel)) as Vessel[];
- if (sceneVessels != null)
- {
- foreach (var v in sceneVessels)
- {
- v.distanceLandedPackThreshold = 98950f;
- v.distanceLandedUnpackThreshold = 99150f;
- v.distancePackThreshold = 98950f;
- v.distanceUnpackThreshold = 99150f;
- }
- }
- }
- }
- }
- }
- public void FixedUpdate()
- {
- if (pVessel != FlightGlobals.ActiveVessel)
- {
- tVessel = null;
- pVessel = FlightGlobals.ActiveVessel;
- }
- if (HighLogic.LoadedSceneIsFlight && !FlightGlobals.ActiveVessel.isEVA && FlightGlobals.ActiveVessel.IsControllable)
- {
- if (FlightGlobals.fetch.vesselTargetMode != VesselTargetModes.None && doItOnce == true && tVessel != FlightGlobals.ActiveVessel)
- {
- //tVessel = FlightGlobals.ActiveVessel.targetObject.GetVessel();
- ITargetable target = FlightGlobals.fetch.VesselTarget;
- if (target != null)
- {
- tVessel = target.GetVessel();
- float distToTarget = Vector3.Distance(tVessel.transform.position, FlightGlobals.ActiveVessel.transform.position);
- if (distToTarget > 9800f)
- {
- targeterOverride = true;
- if (distToTarget < 19800f)
- {
- overrideCategory = 1;
- }
- if (distToTarget >= 19800f && distToTarget < 49800f)
- {
- overrideCategory = 2;
- }
- if (distToTarget >= 49800f && distToTarget < 99800f)
- {
- overrideCategory = 3;
- }
- doItOnce = false;
- }
- }
- }
- if (FlightGlobals.fetch.vesselTargetMode == VesselTargetModes.None && LRMouseBypass == false)
- {
- doItOnce = true;
- targeterOverride = false;
- overrideCategory = 0;
- }
- else if (FlightGlobals.fetch.vesselTargetMode == VesselTargetModes.None && LRMouseBypass == true)
- {
- overrideCategory = 3;
- //Debug.Log("LongRange RangeBooster setting enabled!");
- doItOnce = false;
- }
- }
- else
- {
- tVessel = null;
- }
- }
- }
- //************************************************************
- public class BoatInterface : PartModule
- {
- private bool setSaveTrip = false;
- [KSPField(isPersistant = true)]
- private bool setCheckItOnce = false;
- //public AudioSource hornSound;
- public FXGroup soundGroup;
- public FXGroup soundBGroup;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "M2WTimer: "), UI_FloatRange(minValue = 5f, maxValue = 12f, stepIncrement = 1f)]
- public float timeLockFix = 5f;// wait 5 seconds between moving and making the ship unlock.
- [KSPField(isPersistant = true)]
- public bool lockFixed = false;
- [KSPField(isPersistant = true)]
- public bool flipForwardUp = false;
- [KSPField(isPersistant = true)]
- public bool flipLeftRight = false;
- [KSPField(isPersistant = true)]
- public bool flipRightForward = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = false, guiName = "Move2Water: "), UI_Toggle(controlEnabled = true, disabledText = "No", enabledText = "Yes")]
- public bool moveAtLaunch = true; // for overriding with SPH option menu
- [KSPField]
- public float stabilForce = 10f;
- [KSPField]
- public float stabilOffset = 2f;
- [KSPField(isPersistant = true, guiActiveEditor = true), UI_FloatRange(minValue = -1f, maxValue = 1f, stepIncrement = 0.01f)]
- public float latitude = -0.039751f;
- [KSPField(isPersistant = true, guiActiveEditor = true), UI_FloatRange(minValue = 285f, maxValue = 286f, stepIncrement = 0.01f)]
- public float longitude = 285.639486f;
- [KSPField(isPersistant = true, guiActiveEditor = true)]
- public float altitude = 1f;
- [KSPField(isPersistant = true, guiActiveEditor = true), UI_FloatRange(minValue = -20f, maxValue = 20f, stepIncrement = 1f)]
- public float altitudeShift = 0f;
- //[KSPField]
- //public Vector3 launchPosition = new Vector3(-2294.581f, 7.605f, -3458.309f);
- [KSPField(isPersistant = true)]
- public bool hasLaunched = false;
- [KSPField]
- public bool hornActive = true;
- [KSPField]
- public float dOLRMulti = 1f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "DepthWarning: "), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool depthWarning = false; // permits sound and warning texts.
- [KSPField]
- public float calibrateDepth = 0f; //set in cfg.
- public bool showCurrentPos = false;
- public float depthDTimer;
- public float depthDCoolDown = 15f;
- //public float oldDrag;
- public float impactDTimer;
- public float impactDCoolDown = 1.2f;
- [KSPField(guiActive = true, guiName = "Depth Under Ship")]
- public float depthUnderShip; // this variable contains the depth under the ship.
- [KSPField(guiActive = true, guiName = "Ship Total Mass")]
- public float shipsTotalMass; // this variable contains the reverse of the current heading.
- [KSPField(guiActive = true, guiName = "Reverse Heading")]
- public double shipsRevHeading; // this variable contains the reverse of the current heading.
- [KSPField]
- public float shipsRudderSet = 0; // this variable contains the reverse of the current heading.
- [KSPEvent(name = "soundHorn", active = true, guiActive = false, guiName = "Sound Horn")]
- public void doShipSoundHorn()
- {
- soundGroup.audio.Play();
- }
- [KSPEvent(name = "PrintCurrentPosition", active = true, guiActive = true, guiName = "Print Position")]
- public void doPrintPosition()
- {
- showCurrentPos = true; // this prints the current 3d world position ONE time.
- }
- [KSPEvent(name = "ShowRudder5PortSet", active = true, guiActive = true, guiName = "Set Rudder 5 Deg to Port")]
- public void CalculateShipsRudderPORTlowSet()
- {
- shipsRudderSet = -0.167f; // 1 would be 100% of 30 which is the rudder max deg .167 is close to 5 degrees.
- FlightInputHandler.state.yawTrim = shipsRudderSet;
- //print(shipsRevHeading); //use this to check it's working.
- //PopupDialog.SpawnPopupDialog("Set Ships Rudder", "Rudder set to Port " + shipsRudderSet, "Confirm", false, HighLogic.Skin);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Rudder set to Port " + shipsRudderSet, 2f, ScreenMessageStyle.UPPER_CENTER));
- }
- [KSPEvent(name = "ShowRudder5StarSet", active = true, guiActive = true, guiName = "Set Rudder 5 Deg to Starboard")]
- public void CalculateShipsRudderSTARlowSet()
- {
- shipsRudderSet = 0.167f;
- FlightInputHandler.state.yawTrim = shipsRudderSet;
- //print(shipsRevHeading); //use this to check it's working.
- //PopupDialog.SpawnPopupDialog("Set Ships Rudder", "Rudder set to Starboard " + shipsRudderSet, "Confirm", false, HighLogic.Skin);
- ScreenMessages.PostScreenMessage(new ScreenMessage("Rudder set to Starboard " + shipsRudderSet, 2f, ScreenMessageStyle.UPPER_CENTER));
- }
- [KSPAction("Sound Ship Horn")]
- public void actSoundShipHorn(KSPActionParam param)
- {
- doShipSoundHorn();
- }
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- //oldDrag = this.vessel.rigidbody.drag;
- //if (HighLogic.LoadedSceneIsFlight && moveAtLaunch == true)
- //{
- // if (!hasLaunched && setCheckItOnce == false)
- // {
- // Debug.Log("moving craft");
- // moveCraft();
- // hasLaunched = true;
- // }
- //}
- setCheckItOnce = false;
- #region Sound effects
- if (!GameDatabase.Instance.ExistsAudioClip("BoatPartsR3/Sounds/R3CarrierHorn")) return;
- //print("getting past the sound condition 1");
- soundGroup.audio = gameObject.AddComponent<AudioSource>();
- if (soundGroup.audio != null)
- {
- //print("getting past the sound condition 2");
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Logarithmic;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("BoatPartsR3/Sounds/R3CarrierHorn");
- soundGroup.audio.loop = false;
- soundGroup.audio.playOnAwake = false;
- }
- if (!GameDatabase.Instance.ExistsAudioClip("BoatPartsR3/Sounds/Klaxon")) return;
- //print("getting past the sound condition 1");
- soundBGroup.audio = gameObject.AddComponent<AudioSource>();
- if (soundBGroup.audio != null)
- {
- //print("getting past the sound condition 2");
- soundBGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundBGroup.audio.rolloffMode = AudioRolloffMode.Logarithmic;
- soundBGroup.audio.dopplerLevel = 0f;
- soundBGroup.audio.panLevel = 1f;
- soundBGroup.audio.clip = GameDatabase.Instance.GetAudioClip("BoatPartsR3/Sounds/Klaxon");
- soundBGroup.audio.loop = false;
- soundBGroup.audio.playOnAwake = false;
- }
- #endregion
- }
- public override void OnUpdate()
- {
- base.OnUpdate();
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- if (this.vessel.heightFromTerrain >= 0)
- {
- depthUnderShip = Mathf.Round(this.vessel.heightFromTerrain - calibrateDepth);
- }
- else if (this.vessel.heightFromTerrain < 0)
- {
- depthUnderShip = 600f;
- }
- if (depthWarning == true && this.vessel == FlightGlobals.ActiveVessel) //mainly for subs.
- {
- depthDTimer -= Time.deltaTime; // this is a casual info popup
- if (depthDTimer <= 0f)
- {
- depthDTimer = depthDCoolDown;
- if(depthUnderShip > 100f && depthUnderShip < 300f)//accurate reading
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Depth Below Keel " + depthUnderShip + " m", 3f, ScreenMessageStyle.UPPER_RIGHT));
- }
- if (depthUnderShip < 100f && depthUnderShip > 0f)//accurate reading
- {
- ScreenMessages.PostScreenMessage(new ScreenMessage("Shallow Water! " + depthUnderShip + " m", 3f, ScreenMessageStyle.UPPER_RIGHT));
- }
- }
- impactDTimer -= Time.deltaTime; // we check this more often as it's critical
- if (impactDTimer <= 0f)
- {
- impactDTimer = impactDCoolDown;
- if (depthUnderShip < 20f && depthUnderShip > 0f && this.vessel.horizontalSrfSpeed > 5.0d)//show constantly for now - Will also need to play warning sound.
- {
- soundBGroup.audio.Play();
- ScreenMessages.PostScreenMessage(new ScreenMessage("Impact Warning!!! " + depthUnderShip + " m", 2.5f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- }
- if (showCurrentPos == true)
- {
- //print(vessel.GetWorldPos3D());
- showCurrentPos = false;
- Debug.Log("Coordinates: lat " + vessel.latitude + ", long " + vessel.longitude + ", alt " + vessel.altitude);
- }
- if (FlightGlobals.ship_heading <= 180)
- {
- shipsRevHeading = Mathf.Round(FlightGlobals.ship_heading + 180);
- }
- else shipsRevHeading = Mathf.Round(FlightGlobals.ship_heading - 180);
- if (setCheckItOnce == false)
- {
- if (FlightGlobals.ActiveVessel.situation == Vessel.Situations.SPLASHED) //once the ship becomes splashed the first time it will toggle the setSaveTrip condition for the onSave attempt override.
- {
- setSaveTrip = true;
- setCheckItOnce = true; // this stops this from ever running again.
- }
- }
- if (Input.GetKeyUp(KeyCode.KeypadMultiply) || timeLockFix <= 0f && lockFixed == false) //press key return to ksc then choose ship from the station - should be unlocked.
- {
- this.vessel.situation = Vessel.Situations.SPLASHED;
- this.vessel.Landed = false;
- this.vessel.Splashed = true;
- //this.vessel.GoOnRails();
- //this.vessel.rigidbody.WakeUp();
- //this.vessel.ResumeStaging();
- base.vessel.landedAt = "";
- InputLockManager.ClearControlLocks();
- lockFixed = true;
- //ScreenMessages.PostScreenMessage(new ScreenMessage("Moving to the water!", 5f, ScreenMessageStyle.UPPER_CENTER));
- }
- }
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- shipsTotalMass = Mathf.Round(this.vessel.GetTotalMass());
- if (timeLockFix > 0f && !lockFixed)
- {
- timeLockFix -= Time.deltaTime;
- moveCraft();
- }
- else hasLaunched = true;
- if (hornActive == true)
- {
- Events["doShipSoundHorn"].guiActive = true;
- }
- else if (hornActive == false)
- {
- Events["doShipSoundHorn"].guiActive = false;
- }
- Vector3 forward = FlightGlobals.ActiveVessel.transform.up;
- Vector3 heading = FlightGlobals.ActiveVessel.transform.right;
- Vector3 velDirection = FlightGlobals.ActiveVessel.rigidbody.velocity;//.normalized;
- if (flipForwardUp == true)
- {
- forward = FlightGlobals.ActiveVessel.transform.forward;
- }
- if (flipRightForward == true)
- {
- heading = FlightGlobals.ActiveVessel.transform.forward;
- }
- //if (Vector3.Dot(forward, velDirection) > 0f)
- //{
- // print("Moving Forward"); // lets see what this is.
- //}
- //else if(Vector3.Dot(forward, velDirection) < 0f)
- //{
- // print("Moving Reverse");
- //}
- #region vessel stabilizer test
- stabilForce = shipsTotalMass * 0.15f;
- stabilOffset = stabilForce * 0.5f;
- if (this.vessel.rigidbody != null)
- {
- this.vessel.rigidbody.AddForceAtPosition(((this.vessel.transform.position - this.vessel.mainBody.position).normalized) * stabilForce, (this.vessel.transform.position - this.vessel.mainBody.position) * stabilOffset);
- this.vessel.rigidbody.AddForceAtPosition((-(this.vessel.transform.position - this.vessel.mainBody.position).normalized) * stabilForce, -(this.vessel.transform.position - this.vessel.mainBody.position) * stabilOffset);
- }
- #endregion
- if (this.vessel.horizontalSrfSpeed > 1.0d && this.vessel.IsControllable)
- {
- if (flipLeftRight == true)
- {
- if (Vector3.Dot(-heading, velDirection) > 3f && Vector3.Dot(-heading, velDirection) <= 15f)
- {
- //print("Drifting Right"); // lets see what this is.
- this.vessel.rigidbody.AddForce(heading.normalized * (dOLRMulti * ( 0.5f *shipsTotalMass)));
- }
- else if (Vector3.Dot(-heading, velDirection) > 15f && Vector3.Dot(-heading, velDirection) <= 45f)
- {
- //print("Drifting Right"); // lets see what this is.
- this.vessel.rigidbody.AddForce(heading.normalized * (dOLRMulti * (1.25f * shipsTotalMass)));
- }
- else if (Vector3.Dot(-heading, velDirection) > 45f && Vector3.Dot(-heading, velDirection) < 90f)
- {
- //print("Drifting Right"); // lets see what this is.
- this.vessel.rigidbody.AddForce(heading.normalized * (dOLRMulti * (1.8f * shipsTotalMass)));
- }
- else if (Vector3.Dot(-heading, velDirection) < -3f && Vector3.Dot(-heading, velDirection) >= -15f)
- {
- //print("Drifting Left");
- this.vessel.rigidbody.AddForce(heading.normalized * -(dOLRMulti * (0.5f * shipsTotalMass)));
- }
- else if (Vector3.Dot(-heading, velDirection) < -15f && Vector3.Dot(-heading, velDirection) >= -45f)
- {
- //print("Drifting Left");
- this.vessel.rigidbody.AddForce(heading.normalized * -(dOLRMulti * (1.25f * shipsTotalMass)));
- }
- else if (Vector3.Dot(-heading, velDirection) < -45f && Vector3.Dot(-heading, velDirection) > -90f)
- {
- //print("Drifting Left");
- this.vessel.rigidbody.AddForce(heading.normalized * -(dOLRMulti * (1.8f * shipsTotalMass)));
- }
- }
- else
- {
- if (Vector3.Dot(heading, velDirection) > 3f && Vector3.Dot(heading, velDirection) <= 15f)
- {
- //print("Drifting Right"); // lets see what this is.
- this.vessel.rigidbody.AddForce(heading.normalized * (dOLRMulti * (0.5f * shipsTotalMass)));
- }
- else if (Vector3.Dot(heading, velDirection) > 15f && Vector3.Dot(heading, velDirection) <= 45f)
- {
- //print("Drifting Right"); // lets see what this is.
- this.vessel.rigidbody.AddForce(heading.normalized * (dOLRMulti * (1.25f * shipsTotalMass)));
- }
- else if (Vector3.Dot(heading, velDirection) > 45f && Vector3.Dot(heading, velDirection) < 90f)
- {
- //print("Drifting Right"); // lets see what this is.
- this.vessel.rigidbody.AddForce(heading.normalized * (dOLRMulti * (1.8f * shipsTotalMass)));
- }
- else if (Vector3.Dot(heading, velDirection) < -3f && Vector3.Dot(heading, velDirection) >= -15f)
- {
- //print("Drifting Left");
- this.vessel.rigidbody.AddForce(heading.normalized * -(dOLRMulti * (0.5f * shipsTotalMass)));
- }
- else if (Vector3.Dot(heading, velDirection) < -15f && Vector3.Dot(heading, velDirection) >= -45f)
- {
- //print("Drifting Left");
- this.vessel.rigidbody.AddForce(heading.normalized * -(dOLRMulti * (1.25f * shipsTotalMass)));
- }
- else if (Vector3.Dot(heading, velDirection) < -45f && Vector3.Dot(heading, velDirection) > -90f)
- {
- //print("Drifting Left");
- this.vessel.rigidbody.AddForce(heading.normalized * -(dOLRMulti * (1.8f * shipsTotalMass)));
- }
- }
- //print(Vector3.Dot(heading, velDirection));
- }
- }
- }
- public override void OnSave(ConfigNode node) // this is the attempt to override the game saving the carrier as LANDED... LANDED = BAD :)
- {
- base.OnSave(node);
- if (!HighLogic.LoadedSceneIsFlight || setSaveTrip == false) return; //if the scene is not a flight or the condition is false... get out/don't do anything.
- {
- this.vessel.situation = Vessel.Situations.SPLASHED;
- this.vessel.Landed = false;
- this.vessel.Splashed = true;
- }
- }
- public Vector3d calculateLaunchPosition()
- {
- return vessel.mainBody.GetWorldSurfacePosition((double)latitude, (double)longitude, (double)(altitude + altitudeShift));
- }
- public void moveCraft()
- {
- if (this.vessel != null && moveAtLaunch == true)
- {
- //Debug.Log("Move to Water: " + launchPosition);
- //vessel.SetPosition(launchPosition, true);
- vessel.SetPosition(calculateLaunchPosition(), true);
- if (!vessel.rigidbody.isKinematic)
- {
- vessel.rigidbody.velocity = Vector3.zero;
- vessel.rigidbody.angularVelocity = Vector3.zero;
- }
- }
- }
- }
- //*************************************************
- public class aircraftLift : PartModule
- {
- //private bool tripLift = false;
- //[KSPField (isPersistant = true)]
- //public float liftSpeed = 0.05f; // this variable controls the speed of the lift via the CFG.
- //public AudioSource liftSound;
- public FXGroup soundGroup;
- public bool tripSoundPlay = false;
- private ModuleAnimateGeneric liftOperation = new ModuleAnimateGeneric();
- [KSPEvent(active = true, guiName = "Operate ", guiActiveUnfocused = true, externalToEVAOnly = true, guiActive = false, unfocusedRange = 20f)]
- public void actuateAirLift()
- {
- doLiftOp();
- }
- //[KSPEvent(active = false, guiName = "Decrease Speed", guiActiveUnfocused = true, externalToEVAOnly = false, guiActive = false)]
- //public void incSpdAirLift()
- //{
- // if (liftSpeed > 0)
- // {
- // liftSpeed = liftSpeed - 0.01f;
- // print(liftSpeed);
- // }
- // if (liftSpeed <= 0)
- // {
- // liftSpeed = 0.01f;
- // print(liftSpeed);
- // }
- //}
- //[KSPEvent(active = false, guiName = "Increase Speed", guiActiveUnfocused = true, externalToEVAOnly = false, guiActive = false)]
- //public void decSpdAirLift()
- //{
- // if (liftSpeed < 1)
- // {
- // liftSpeed = liftSpeed + 0.01f;
- // print(liftSpeed);
- // }
- // if (liftSpeed >= 1)
- // {
- // liftSpeed = 1f;
- // print(liftSpeed);
- // }
- //}
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- liftOperation = this.part.Modules.OfType<ModuleAnimateGeneric>().FirstOrDefault();
- //liftOperation.animSpeed = liftSpeed;
- #region Sound effects
- if (!GameDatabase.Instance.ExistsAudioClip("BoatPartsR3/Sounds/R3CarrierLift")) return;
- //print("getting past the sound condition 1");
- soundGroup.audio = gameObject.AddComponent<AudioSource>();
- if (soundGroup.audio != null)
- {
- //print("getting past the sound condition 2");
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Logarithmic;
- soundGroup.audio.dopplerLevel = 0f;
- soundGroup.audio.panLevel = 1f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("BoatPartsR3/Sounds/R3CarrierLift");
- soundGroup.audio.loop = true;
- soundGroup.audio.playOnAwake = false;
- }
- #endregion
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- if (liftOperation.animTime >= 0.02f && liftOperation.animTime <= 0.98f)
- {
- if (tripSoundPlay == false)
- {
- soundGroup.audio.Play();
- tripSoundPlay = true;
- }
- }
- if (liftOperation.animTime <= 0.01f || liftOperation.animTime >= 0.99f)
- {
- soundGroup.audio.Stop();
- tripSoundPlay = false;
- }
- }
- }
- private void doLiftOp()
- {
- //liftOperation.animSpeed = liftSpeed;
- liftOperation.Toggle();
- soundGroup.audio.Play();
- //print(liftSpeed);
- }
- }
- //**********************************************
- public class nuclearEngine : PartModule
- {
- [KSPField]
- public float revOutput = 0.5f; // this variable is how much final thrust is produced while in reverse... in percent.
- [KSPField]
- public float maxRpm;
- [KSPField]
- public float thrustScale = 1f;
- [KSPField(guiActive = true, guiActiveEditor = false, guiName = "Thrust ")]
- public float maxThrust;
- [KSPField]
- public string thrustDirection = "up";
- public Vector3 useThrustDir = new Vector3(0f,0f,0f);
- public Transform bowPoint;
- [KSPField]
- public float heatProduction = 200f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "EngineActive "), UI_Toggle(controlEnabled = false, disabledText = "No", enabledText = "Yes")]
- public bool engineActive = false;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "RPM Limit %"), UI_FloatRange(minValue = 0.1f, maxValue = 1f, stepIncrement = 0.1f)]
- public float fwdLimiter = 1f;
- [KSPField(isPersistant = true, guiActiveEditor = true, guiActive = true, guiName = "R-RPM Limit %"), UI_FloatRange(minValue = 0.1f, maxValue = 1f, stepIncrement = 0.1f)]
- public float revLimiter = 1f;
- [KSPField]
- public bool hasScrew = false;
- [KSPField]
- public bool hasHsUD = false;//subs only
- [KSPField]
- public float hSUDMulti = 1.2f;
- [KSPField]
- public bool useTTransform = false;
- [KSPField(isPersistant = true)]
- public float storeOldMaxThrust;
- [KSPField(isPersistant = true)]
- public float storeOldHeatProd;
- [KSPField(isPersistant = true)]
- public float storeOldThrustScale;
- public GameObject propWash;
- [KSPField(isPersistant = true)]
- public bool doItOnce = true;
- public Transform engThrustTransform;
- public float oOfWaterLimiter = 1f;
- public bool soundTripped = false;
- public bool isUnderWater = false;
- public double partAltitude;
- public double bowAltitude;
- public FXGroup soundGroup;
- //public float currentThrust = 0f;
- [KSPField(guiActive = true, guiName = "Propulsion Reverse", isPersistant = true)]
- public bool togRevThrust = false;
- //public Vector3 revEAngle;
- private ModuleAnimateGeneric shipsEngine = new ModuleAnimateGeneric();
- [KSPEvent(name = "togEngine", active = true, guiActive = false, guiName = "Toggle Engine")]
- public void setShipEngine()
- {
- if (engineActive == true)
- {
- engineActive = false;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine Decactivated ", 1.25f, ScreenMessageStyle.UPPER_CENTER));
- }
- else
- {
- engineActive = true;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Engine Active ", 1.25f, ScreenMessageStyle.UPPER_CENTER));
- //PopupDialog.SpawnPopupDialog("Nuclear Propulsion", "Set Back ", "Close", false, HighLogic.Skin);
- }
- }
- [KSPEvent(name = "setReverse", active = true, guiActive = true, guiName = "Reverse Propulsion")]
- public void setShipEngineReverse()
- {
- if (togRevThrust == true)
- {
- togRevThrust = false;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Propulsion Ahead ", 1.25f, ScreenMessageStyle.UPPER_CENTER));
- //PopupDialog.SpawnPopupDialog("Nuclear Propulsion", "Set Ahead ", "Close", false, HighLogic.Skin);
- }
- else
- {
- togRevThrust = true;
- ScreenMessages.PostScreenMessage(new ScreenMessage("Propulsion Reverse ", 1.25f, ScreenMessageStyle.UPPER_CENTER));
- //PopupDialog.SpawnPopupDialog("Nuclear Propulsion", "Set Back ", "Close", false, HighLogic.Skin);
- }
- }
- [KSPAction("Toggle Reverse Propulsion")]
- public void toggleTheFoldingSystem(KSPActionParam param)
- {
- setShipEngineReverse();
- }
- [KSPAction("Toggle Engine")]
- public void toggleTheEngineSystem(KSPActionParam param)
- {
- setShipEngine();
- }
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- #region Sound and FX
- if (hasScrew == true)
- {
- Transform turnSubScrew = part.FindModelTransform("subScrew");
- engThrustTransform = part.FindModelTransform("thrustTransform");
- propWash = (GameObject)GameObject.Instantiate(UnityEngine.Resources.Load("Effects/fx_smokeTrail_medium"));
- //propWash.transform.localScale = new Vector3(this.part.rescaleFactor, this.part.rescaleFactor, this.part.rescaleFactor); //will this be affected by rescaling in KSP?
- propWash.particleEmitter.emit = false;
- propWash.transform.parent = turnSubScrew;
- propWash.transform.localPosition = new Vector3(0, 0, 0);
- propWash.transform.localRotation = this.part.transform.rotation;
- propWash.particleEmitter.useWorldSpace = true;
- propWash.particleEmitter.minSize = 1.25f * (this.part.rescaleFactor * 0.75f);
- propWash.particleEmitter.maxSize = 1.5f * (this.part.rescaleFactor * 0.75f);
- propWash.particleEmitter.localVelocity = new Vector3(0, 0, 0);
- propWash.particleEmitter.minEnergy = 1.4f * (this.part.rescaleFactor * 0.75f);
- propWash.particleEmitter.maxEnergy = 1.8f * (this.part.rescaleFactor * 0.75f); // how long do the particles linger?
- propWash.particleEmitter.minEmission = 50f;
- propWash.particleEmitter.angularVelocity = 0.0075f;
- propWash.particleEmitter.rndRotation = true;
- if (!GameDatabase.Instance.ExistsAudioClip("BoatPartsR3/Sounds/propFX")) return;
- //print("getting past the sound condition 1");
- soundGroup.audio = gameObject.AddComponent<AudioSource>();
- if (soundGroup.audio != null)
- {
- //print("getting past the sound condition 2");
- soundGroup.audio.volume = GameSettings.SHIP_VOLUME;
- soundGroup.audio.rolloffMode = AudioRolloffMode.Linear;
- soundGroup.audio.dopplerLevel = 1f;
- soundGroup.audio.panLevel = 0.85f;
- soundGroup.audio.clip = GameDatabase.Instance.GetAudioClip("BoatPartsR3/Sounds/propFX");
- soundGroup.audio.loop = true;
- soundGroup.audio.playOnAwake = false;
- }
- #endregion
- /* emitter.minSize = blastradius * 1.5f; //other possibilities
- emitter.maxSize = blastradius * 2;
- emitter.minEnergy = blastradius * 0.15f;
- emitter.maxEnergy = blastradius * 0.2f;
- emitter.rndVelocity = Vector3.one * 0.6f;
- particleEmitter.angularVelocity = 100;
- fx_gasBurst_white //other fx types
- fx_gasJet_tiny
- fx_gasJet_white
- fx_smokeTrail_light
- fx_smokeTrail_medium
- fx_splashdown
- fx_waterSurface*/
- }
- }
- public void FixedUpdate()
- {
- if (!HighLogic.LoadedSceneIsFlight) return;
- {
- if (this.vessel == FlightGlobals.ActiveVessel && hasScrew == true)
- {
- Transform turnSubScrew = part.FindModelTransform("subScrew");
- if (useTTransform == false)
- {
- if (thrustDirection == "up")
- {
- useThrustDir = turnSubScrew.transform.up;
- }
- else if (thrustDirection == "down")
- {
- useThrustDir = -turnSubScrew.transform.up;
- }
- else if (thrustDirection == "forward")
- {
- useThrustDir = turnSubScrew.transform.forward;
- }
- else if (thrustDirection == "backward")
- {
- useThrustDir = -turnSubScrew.transform.forward;
- }
- else if (thrustDirection == "right")
- {
- useThrustDir = turnSubScrew.transform.right;
- }
- else if (thrustDirection == "left")
- {
- useThrustDir = -turnSubScrew.transform.right;
- }
- }
- else
- {
- if (thrustDirection == "up")
- {
- useThrustDir = engThrustTransform.transform.up;
- }
- else if (thrustDirection == "down")
- {
- useThrustDir = -engThrustTransform.transform.up;
- }
- else if (thrustDirection == "forward")
- {
- useThrustDir = engThrustTransform.transform.forward;
- }
- else if (thrustDirection == "backward")
- {
- useThrustDir = -engThrustTransform.transform.forward;
- }
- else if (thrustDirection == "right")
- {
- useThrustDir = engThrustTransform.transform.right;
- }
- else if (thrustDirection == "left")
- {
- useThrustDir = -engThrustTransform.transform.right;
- }
- }
- //print(useThrustDir);
- if (doItOnce == true)
- {
- storeOldMaxThrust = maxRpm;
- storeOldHeatProd = heatProduction;
- storeOldThrustScale = thrustScale;
- doItOnce = false;
- foreach (Part p in this.vessel.parts)
- {
- if (p.FindModelTransform("bowPoint") == true)
- {
- bowPoint = p.FindModelTransform("bowPoint");
- }
- }
- }
- bool doAlterThrust = false;
- if (this.vessel.altitude < -1.0 && partAltitude <= -8.0)
- {
- isUnderWater = true;
- doAlterThrust = true;
- }
- else if (this.vessel.altitude > -1.0 && partAltitude > -8.0)
- {
- isUnderWater = false;
- thrustScale = storeOldThrustScale;
- }
- if (hasHsUD == true && doAlterThrust == true) //be sure this isn't engaged on top of the water... that would be bad!
- {
- //thrustScale = Mathf.SmoothStep(storeOldThrustScale, hSUDMulti, 5f);
- if (thrustScale < hSUDMulti)
- {
- thrustScale = storeOldThrustScale + 0.001f;
- }
- }
- if (engineActive == true)
- {
- if (togRevThrust == false)
- {
- float currentSpeed = ((maxRpm * FlightInputHandler.state.mainThrottle) * Time.deltaTime);
- turnSubScrew.transform.Rotate(Vector3.forward * currentSpeed);
- maxThrust = ((this.part.mass * 0.35f) * (((maxRpm * thrustScale) * FlightInputHandler.state.mainThrottle) * fwdLimiter) * oOfWaterLimiter);
- this.part.temperature *= (heatProduction * Time.deltaTime);
- }
- else if (togRevThrust == true)
- {
- float currentSpeed = ((-maxRpm * FlightInputHandler.state.mainThrottle) * Time.deltaTime);
- turnSubScrew.transform.Rotate(Vector3.forward * currentSpeed);
- maxThrust = ((this.part.mass * 0.35f) * (((maxRpm * thrustScale) * FlightInputHandler.state.mainThrottle) * revLimiter) * oOfWaterLimiter) * -1f;
- this.part.temperature *= (heatProduction * Time.deltaTime);
- }
- }
- else
- {
- maxThrust = 0f;
- }
- partAltitude = Vector3.Distance(engThrustTransform.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- if (bowPoint != null)
- {
- bowAltitude = Vector3.Distance(bowPoint.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- }
- if (bowPoint != null && bowAltitude > 0.0d)
- {
- oOfWaterLimiter = 0f;
- }
- else if (bowPoint != null && bowAltitude < 0.0d || bowPoint == null)
- {
- oOfWaterLimiter = 1f;
- }
- if (partAltitude > 0.0d) //no more engine power out of the water!
- {
- propWash.particleEmitter.emit = false;
- }
- else if (partAltitude <= 0.0d)
- {
- //engine.maxThrust = storeOldMaxThrust;
- if (this.rigidbody != null)
- {
- this.rigidbody.AddForceAtPosition((useThrustDir * maxThrust) * Time.deltaTime, turnSubScrew.position, ForceMode.Impulse);
- }
- soundGroup.audio.volume = (GameSettings.SHIP_VOLUME * FlightGlobals.ActiveVessel.ctrlState.mainThrottle); //nice! :)
- if (FlightGlobals.ActiveVessel.ctrlState.mainThrottle >= 0.1f && engineActive == true)
- {
- if (soundTripped == false)
- {
- soundTripped = true;
- soundGroup.audio.Play();
- }
- propWash.particleEmitter.emit = true;
- }
- else if (FlightGlobals.ActiveVessel.ctrlState.mainThrottle < 0.1f || engineActive == false)
- {
- if (soundTripped == true)
- {
- soundTripped = false;
- soundGroup.audio.Stop();
- }
- propWash.particleEmitter.emit = false;
- }
- }
- }
- }
- }
- public void ApplyDamage(float damageState)
- {
- float chanceJammed = rndNumber.rndRoll(0, 100);
- if (chanceJammed < 12f)
- {
- heatProduction *= rndNumber.rndRoll(1,4); // causes a massive heat buildup.
- }
- if (damageState < 1f)//damaged
- {
- maxRpm = storeOldMaxThrust * damageState; // reduce RPM instead - as it gets damaged.
- }
- if (damageState == 1f)//normal/fixed state.... floats
- {
- maxRpm = storeOldMaxThrust;
- heatProduction = storeOldHeatProd;
- }
- //print("idFloatCode: Setting damage state to " + damageState + " object volume is now " + objVolume);
- }
- }
- 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(double min, double max)
- {
- return rnd2.NextDouble();
- }
- }
- //*************************************
- public class IDrudder : PartModule //Thanks to Snjo for his ideas.
- {
- [KSPField]
- public string animatedPart = "obj_ctrlSrf";
- [KSPField]
- public float range = 30f;
- [KSPField]
- public float manualRudderArea = 0f;
- [KSPField]
- public Vector3 pivotAxis = new Vector3(1f,0f,0f);
- [KSPField]
- public Vector3 useInputAxis = new Vector3(0f,0f,1f); //pitch, roll or yaw
- [KSPField]
- public string forceAxis = "forward";
- [KSPField]
- public int requiresWaterContact = 0;
- private Transform rudderTransform;
- private Transform rudderDefaultTransform;
- private FlightCtrlState ctrl;
- private float input = 0;
- private float power = 0f;
- private float rudderArea = 0f;
- private float powerScale = 0.375f;
- private float origAngDrag = 0f;
- //*********************************************new damage code - for skillful
- public float dmgModifier = 1f;
- public float origRange = 30f;
- private bool isJammed = false;
- private float jammedAngle;
- //private Transform rudderDirection;
- public override void OnStart(PartModule.StartState state)
- {
- base.OnStart(state);
- rudderTransform = part.FindModelTransform(animatedPart);
- if (rudderTransform != null)
- {
- rudderDefaultTransform = new GameObject().transform;
- rudderDefaultTransform.localRotation = rudderTransform.localRotation;
- }
- origAngDrag = this.part.angularDrag;
- origRange = range;
- //rudderDirection = this.part.FindModelTransform("thrustTransform");
- }
- public void FixedUpdate()
- {
- base.OnFixedUpdate();
- if (!HighLogic.LoadedSceneIsFlight || !vessel.isActiveVessel) return;
- if (manualRudderArea > 0f) //only uses this if it's specified in the cfg, otherwise calculates size from the first convex collider in the part/model.
- {
- rudderArea = manualRudderArea;
- }
- else
- {
- rudderArea = (this.part.collider.bounds.size.y * this.part.collider.bounds.size.x * this.part.collider.bounds.size.z); // should be metres3.
- }
- if (isJammed == true)
- {
- FlightInputHandler.state.yawTrim = jammedAngle;
- }
- power = (((float)Math.Sqrt(vessel.horizontalSrfSpeed)) * rudderArea) * dmgModifier;//gets more power from speed.
- if (power < 0f) power = 0.01f; // geezus!
- double partAltitude = Vector3.Distance(this.part.collider.transform.position, vessel.mainBody.position) - (float)vessel.mainBody.Radius;
- ctrl = vessel.ctrlState;
- Vector3 ctrlInputVector = new Vector3(ctrl.pitch, ctrl.roll, ctrl.yaw);
- Vector3 inputVector = new Vector3(ctrlInputVector.x * useInputAxis.x, ctrlInputVector.y * useInputAxis.y, ctrlInputVector.z * useInputAxis.z);
- if (inputVector.x != 0) input = inputVector.x;
- else if (inputVector.y != 0) input = inputVector.y;
- else input = inputVector.z;
- if (input != 0f)
- {
- if (partAltitude <= 0.0d || requiresWaterContact == 0)
- {
- float forcetoAdd = (input * power * ((range * 0.1f)+1f)) * powerScale;
- this.part.angularDrag = (float)this.vessel.horizontalSrfSpeed;
- //Vector3 zeroSideMotion = new Vector3(0f, 0f, rigidbody.velocity.z);
- //this.rigidbody.velocity = zeroSideMotion;
- Vector3 transformDirection = new Vector3();
- switch (forceAxis)
- {
- case "right":
- transformDirection = transform.right;
- break;
- case "left":
- transformDirection = -transform.right;
- break;
- case "up":
- transformDirection = transform.up;
- break;
- case "down":
- transformDirection = -transform.up;
- break;
- case "forward":
- transformDirection = transform.forward;
- break;
- case "back":
- transformDirection = -transform.forward;
- break;
- }
- base.rigidbody.AddForceAtPosition(transformDirection * forcetoAdd, rudderTransform.position); // was using rudderTransform direction, this will be adapted later.
- base.rigidbody.AddForce(-Vector3.Project(rigidbody.velocity, transform.right)); //add * resistance multiplier for reduction if needed.
- if (rudderTransform != null)
- {
- rudderTransform.localRotation = rudderDefaultTransform.localRotation;
- rudderTransform.Rotate(pivotAxis * input * range);
- }
- }
- }
- else
- {
- this.part.angularDrag = origAngDrag;
- if (rudderTransform != null)
- {
- rudderTransform.localRotation = rudderDefaultTransform.localRotation;
- }
- }
- }
- public void ApplyDamage(float damageState)
- {
- float chanceJammed = rndNumber.rndRoll(0, 100);
- if (chanceJammed < 12f)
- {
- isJammed = true;
- jammedAngle = (float)rndNumber.rndDouble(0.05, 0.7); // 1 would be 100% of 30 which is the rudder max deg .167 is close to 5 degrees.
- }
- if (damageState < 1f)//normal/fixed state.... floats
- {
- this.origRange *= damageState; // should reduce float ability as it gets damaged.
- }
- if (damageState == 1f)//normal/fixed state.... floats
- {
- range = origRange;
- isJammed = false;
- }
- //print("idFloatCode: Setting damage state to " + damageState + " object volume is now " + objVolume);
- }
- }
- //*********************end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement