void Awake() { mEnt = GetComponent<EntityBase>(); mEnt.spawnCallback += OnEntitySpawn; mEnt.setStateCallback += OnEntityState; mTimeWarp = GetComponent<TimeWarp>(); }
public TimeWarpDecorator() { mFlightButtonGreen = GUITextureButtonFactory.CreateFromFilename("texFlightGreen.png","texFlightGreenOver.png","texFlightGreenDown.png","texFlightGreenOver.png"); mFlightButtonYellow = GUITextureButtonFactory.CreateFromFilename("texFlightYellow.png","texFlightYellowOver.png","texFlightYellowDown.png","texFlightYellowOver.png"); mFlightButtonRed = GUITextureButtonFactory.CreateFromFilename("texFlightRed.png","texFlightRed.png","texFlightRed.png","texFlightRed.png"); mFlightButtonGreen.fixedHeight = mFlightButtonGreen.fixedWidth = 0; mFlightButtonYellow.fixedHeight = mFlightButtonYellow.fixedWidth = 0; mFlightButtonRed.fixedHeight = mFlightButtonRed.fixedWidth = 0; mFlightButtonGreen.stretchHeight = mFlightButtonGreen.stretchWidth = true; mFlightButtonYellow.stretchHeight = mFlightButtonYellow.stretchWidth = true; mFlightButtonRed.stretchHeight = mFlightButtonRed.stretchWidth = true; // Crap timewarp object mTimewarpObject = TimeWarp.fetch; // objects on this scene? if (mTimewarpObject == null || mTimewarpObject.timeQuadrantTab == null) { // to skip the draw calls mTimewarpObject = null; return; } var text = mTimewarpObject.timeQuadrantTab.transform.FindChild("MET timer").GetComponent<ScreenSafeGUIText>(); mTextStyle = new GUIStyle(text.textStyle); mTextStyle.fontSize = (int)(text.textSize * ScreenSafeUI.PixelRatio); // Put the draw function to the DrawQueue RenderingManager.AddToPostDrawQueue(0, Draw); // create the Background RTUtil.LoadImage(out mTexBackground, "TimeQuadrantFcStatus.png"); }
public void Patch(TimeWarp timeQuadrant) { if (mBackup != null) { throw new InvalidOperationException("Patcher is already in use."); } ScreenSafeUISlideTab tab = timeQuadrant.timeQuadrantTab; mBackup = new Backup() { TimeQuadrant = timeQuadrant, Texture = tab.renderer.material.mainTexture, Scale = tab.transform.localScale, Center = ((BoxCollider) tab.collider).center, ExpandedPosition = tab.expandedPos, CollapsedPosition = tab.collapsedPos, }; List<Transform> children = new List<Transform>(); foreach (Transform child in tab.transform) { children.Add(child); } foreach (Transform child in children) { child.parent = tab.transform.parent; } // Set the new texture Texture2D newTexture; RTUtil.LoadImage(out newTexture, "texTimeQuadrant.png"); tab.renderer.material.mainTexture = newTexture; // Apply new scale, positions tab.transform.localScale = new Vector3(tab.transform.localScale.x, tab.transform.localScale.y, tab.transform.localScale.z * 1.3970588235294117647058823529412f); tab.collapsedPos += new Vector3(0, -0.013f, 0); tab.expandedPos += new Vector3(0, -0.013f, 0); foreach (Transform child in children) { child.localPosition += new Vector3(0, 0.013f, 0); } tab.Expand(); foreach (Transform child in children) { child.parent = tab.transform; } ((BoxCollider) tab.collider).center += new Vector3(0, 0, -0.37f); ScreenSafeGUIText text = tab.transform.FindChild("MET timer").GetComponent<ScreenSafeGUIText>(); mTextStyle = text.textStyle; mTextStyle.fontSize = (int)(text.textSize * ScreenSafeUI.PixelRatio); RenderingManager.AddToPostDrawQueue(0, Draw); }
public ListValue<ScalarValue> GetRatesList(TimeWarp.Modes warpMode) { float[] ratesArray = GetRateArrayForMode(warpMode); ListValue<ScalarValue> ratesKOSList = new ListValue<ScalarValue>(); // Have to convert the elements one at a time from (float) to (ScalarDoubleValue): foreach (float val in ratesArray) ratesKOSList.Add(val); return ratesKOSList; }
public void Update() { if (HighLogic.LoadedScene.Equals (GameScenes.TRACKSTATION) || HighLogic.LoadedScene.Equals (GameScenes.FLIGHT)) { RenderingManager.AddToPostDrawQueue (3, new Callback (drawGUI)); if (FindObjectOfType (typeof(TimeWarp)) != null) this.timewarp = (TimeWarp)FindObjectOfType (typeof(TimeWarp)); /** anti Kaboom thingy from Planet Factory **/ bool speedMax = (this.timewarp.warpRates.Equals (superRates) && (this.timewarp.current_rate_index == 7)); bool ultraMax = (this.timewarp.warpRates.Equals (ultraRates) && (this.timewarp.current_rate_index >= 6)); if (!speedMax || ultraMax) ToggleCollisions (true); else ToggleCollisions (false); } }
private void Start() { print ("====== Loading KSPWarp ======"); timewarp = new TimeWarp (); baseRates = new float[] { 1.0f, 5.0f, 10.0f, 50.0f, 100.0f, 1000.0f, 10000.0f, 100000.0f }; superRates = new float[] { 1.0f, 10.0f, 50.0f, 100.0f, 1000.0f, 10000.0f, 100000.0f, 1000000.0f }; ultraRates = new float[] { 1.0f, 50.0f, 100.0f, 1000.0f, 10000.0f, 100000.0f, 1000000.0f, 10000000.0f }; rates = new float[][] { baseRates, superRates, ultraRates }; setRates (0); UnityEngine.Object.DontDestroyOnLoad (this); }
private void MaintainContainment() { var antimatterResource = part.Resources[resourceName]; if (antimatterResource == null) { return; } if (chargestatus > 0 && antimatterResource.amount > minimimAnimatterAmount) { chargestatus -= TimeWarp.fixedDeltaTime; } if (!should_charge && antimatterResource.amount <= minimimAnimatterAmount) { return; } var powerModifier = canExplodeFromGeeForce ? (resourceRatio * (currentGeeForce / 10) * 0.8) + ((part.temperature / 1000) * 0.2) : Math.Pow(resourceRatio, 2); effectivePowerNeeded = chargeNeeded * powerModifier; if (effectivePowerNeeded > 0) { var mult = chargestatus >= maxCharge ? 0.5 : 1; var powerRequest = mult * 2 * effectivePowerNeeded / 1000 * TimeWarp.fixedDeltaTime; // first try to accespower megajoules var chargeToAdd = CheatOptions.InfiniteElectricity ? powerRequest : consumeFNResource(powerRequest, ResourceManager.FNRESOURCE_MEGAJOULES) * 1000 / effectivePowerNeeded; chargestatus += chargeToAdd; // alternatively just look for any reserves of stored megajoules if (chargeToAdd == 0 && effectivePowerNeeded > 0) { var moreChargeToAdd = part.RequestResource(ResourceManager.FNRESOURCE_MEGAJOULES, powerRequest) * 1000 / effectivePowerNeeded; chargeToAdd += moreChargeToAdd; chargestatus += moreChargeToAdd; } // if still not found any power attempt to find any electricc charge to survive if (chargeToAdd < TimeWarp.fixedDeltaTime && effectivePowerNeeded > 0) { var moreChargeToAdd = part.RequestResource(ResourceManager.STOCK_RESOURCE_ELECTRICCHARGE, mult * 2 * effectivePowerNeeded * TimeWarp.fixedDeltaTime) / effectivePowerNeeded; chargeToAdd += moreChargeToAdd; chargestatus += moreChargeToAdd; } if (chargeToAdd >= TimeWarp.fixedDeltaTime) { charging = true; } else { charging = false; if (TimeWarp.CurrentRateIndex > 3 && (antimatterResource.amount > minimimAnimatterAmount)) { TimeWarp.SetRate(3, true); ScreenMessages.PostScreenMessage("Cannot Time Warp faster than " + TimeWarp.CurrentRate + "x while " + antimatterResource.resourceName + " Tank is Unpowered", 1, ScreenMessageStyle.UPPER_CENTER); } } } if (startup_timeout > 0) { startup_timeout--; } if (startup_timeout == 0 && antimatterResource.amount > minimimAnimatterAmount) { //verify temperature if (!CheatOptions.IgnoreMaxTemperature && canExplodeFromHeat && part.temperature > (double)(decimal)maxTemperature) { temperature_explode_counter++; if (temperature_explode_counter > 20) { DoExplode("Antimatter container exploded due to reaching critical temperature"); } } else { temperature_explode_counter = 0; } //verify geeforce effectiveMaxGeeforce = resourceRatio > 0 ? Math.Min(10, (double)(decimal)maxGeeforce / resourceRatio) : 10; if (!CheatOptions.UnbreakableJoints && canExplodeFromGeeForce) { if (vessel.missionTime > 0) { if (currentGeeForce > effectiveMaxGeeforce) { ScreenMessages.PostScreenMessage("ALERT: geeforce at critical!", 1, ScreenMessageStyle.UPPER_CENTER); geeforce_explode_counter++; if (geeforce_explode_counter > 30) { DoExplode("Antimatter container exploded due to reaching critical geeforce"); } } else if (TimeWarp.CurrentRateIndex > maximumTimewarpWithGeeforceWarning && currentGeeForce > effectiveMaxGeeforce - 0.02) { TimeWarp.SetRate(maximumTimewarpWithGeeforceWarning, true); ScreenMessages.PostScreenMessage("ALERT: Cannot Time Warp faster than " + TimeWarp.CurrentRate + "x while geeforce near maximum tolerance!", 1, ScreenMessageStyle.UPPER_CENTER); } else if (currentGeeForce > effectiveMaxGeeforce - 0.04) { ScreenMessages.PostScreenMessage("ALERT: geeforce at " + (currentGeeForce / effectiveMaxGeeforce * 100).ToString("F2") + "% tolerance!", 1, ScreenMessageStyle.UPPER_CENTER); } else { geeforce_explode_counter = 0; } } else if (currentGeeForce > effectiveMaxGeeforce) { ScreenMessages.PostScreenMessage("Warning: geeforce tolerance exceeded but sustanable while the mission timer has not started", 1, ScreenMessageStyle.UPPER_CENTER); } } else { geeforce_explode_counter = 0; } //verify power if (chargestatus <= 0) { chargestatus = 0; if (!CheatOptions.InfiniteElectricity && antimatterResource.amount > 0.00001 * antimatterResource.maxAmount) { power_explode_counter++; if (power_explode_counter > 20) { DoExplode("Antimatter container exploded due to running out of power"); } } } else { power_explode_counter = 0; } } else { effectiveMaxGeeforce = 0; temperature_explode_counter = 0; geeforce_explode_counter = 0; power_explode_counter = 0; } if (chargestatus > maxCharge) { chargestatus = maxCharge; } }
static void SetWarpMode (TimeWarp.Modes mode) { if (TimeWarp.WarpMode != mode) { TimeWarp.fetch.Mode = mode; TimeWarp.SetRate (0, true); } }
// this apparently does the budget private void DoBudget(double timeSinceLastUpdate) { try { float crewCosts = CrewWages(); float facilityCosts = FacilityCosts(); float vesselCosts = VesselCosts(); float totalCosts = crewCosts + vesselCosts; float funding = NextFunding(); double currentFunds = Funding.Instance.Funds; double excessCovered = 0.0; // if the previous period can cover costs on this one, and the player has enabled it, apply them. if (excessCoversCosts) { if (currentFunds >= totalCosts) { excessCovered = totalCosts; } else { excessCovered = currentFunds; } } // apply all these changes. double finalBudget = funding - (totalCosts - excessCovered); Funding.Instance.AddFunds(-currentFunds, TransactionReasons.None); // zero the budget, always. Funding.Instance.AddFunds(finalBudget, TransactionReasons.None); // tell the player what happened. String message = "Budget Report"; message += "\n"; message += "\n Current Funds : " + currentFunds.ToString("C"); if (excessCoversCosts) { message += "\n Excess Covered: " + excessCovered.ToString("C"); } message += "\n"; message += "\n Crew Costs: " + crewCosts.ToString("C"); message += "\n Facility Costs: " + facilityCosts.ToString("C"); message += "\n Vessel Upkeep: " + vesselCosts.ToString("C"); message += "\n Total Costs: " + totalCosts.ToString("C"); message += "\n"; message += "\n Funding: " + funding.ToString("C"); message += "\n"; message += "\nThis Period's Budget: " + finalBudget.ToString("C"); // upkeep lastUpdate = lastUpdate + budgetInterval; if (loanPercentage < 1) { loanPercentage = loanPercentage + 0.1f; message += "\n\nOverflow Penalty reduced to " + loanPercentage.ToString("F1") + "."; } // degrade the reputation if it's above 250. if (Reputation.CurrentRep > 250) { // Since reputation is awarded on a curve this poses some problems on how to degrade effectively at higher levels. // Higher reputation may also imply longer-term missions which can make quarterly decay punishing. Reputation.Instance.AddReputation(-(Reputation.CurrentRep * 0.015f), TransactionReasons.None); message += "\n\nReputation degrades to " + Reputation.CurrentRep.ToString("F2") + "."; } AddMessage("Budget Report", message, MessageSystemButton.MessageButtonColor.BLUE, MessageSystemButton.ButtonIcons.MESSAGE); // we're automatically stopping timewarp because we're now adding a five minute window to the KAC alarm. if (stopTimeWarp) { TimeWarp.SetRate(0, true); } CheckForAlarm(); } catch { Debug.Log("[MonthlyBudgets]: Problem calculating the budget"); } }
IEnumerator DoUpdate() { mUpdateActive = true; WaitForSeconds wait = new WaitForSeconds(0.2f); while (mUpdateActive) { yield return(wait); // Collider[] cols = Physics.OverlapSphere(transform.position, radius, masks); int colCount = 0; for (int i = 0; i < cols.Length && colCount < maxCount; i++) { TimeWarp warp = cols[i].GetComponent <TimeWarp>(); if (warp) { mColItems[colCount] = warp; colCount++; } } //check to see if colliders are already in data //if a collider in our data is not in the list, remove it for (int i = 0; i < mCount; i++) { TimeWarp item = mItems[i]; bool doRemove = true; if (item != null && item.target.gameObject.activeInHierarchy) { //check if it's in collisions for (int j = 0; j < colCount; j++) { if (item == mColItems[j]) { //remove from cols, already in our items if (colCount > 1) { mColItems[j] = mColItems[colCount - 1]; } colCount--; doRemove = false; break; } } } if (doRemove) { //Debug.Log("remove: "+item.col.name); if (item) { item.Restore(); } if (mCount > 1) { mItems[i] = mItems[mCount - 1]; mItems[mCount - 1] = null; } mCount--; i--; } } if (colCount > 0) { //add new items for (int i = 0; i < colCount && mCount < mItems.Length; i++) { if (mColItems[i]) { //Debug.Log("add: " + cols[i].name); mItems[mCount] = mColItems[i]; mItems[mCount].SetScale(scale); mCount++; } } } } }
public void FixedUpdate() { var vessel = GetComponent <Vessel>(); if (vessel != FlightGlobals.ActiveVessel) { Destroy(this); return; } if (AlreadyTeleported) { if (vessel.LandedOrSplashed) { Destroy(this); } else { var accel = (vessel.srf_velocity + vessel.upAxis) * -0.5; vessel.ChangeWorldVelocity(accel); RateLimitedLogger.Log(_accelLogObject, $"(Happening every frame) Soft-lander changed ship velocity this frame by vector {accel.x},{accel.y},{accel.z} (mag {accel.magnitude})"); } } else { var pqs = Body.pqsController; if (pqs == null) { Destroy(this); return; } var alt = pqs.GetSurfaceHeight(Body.GetRelSurfaceNVector(Latitude, Longitude)) - Body.Radius; alt = Math.Max(alt, 0); // Underwater! if (TimeWarp.CurrentRateIndex != 0) { TimeWarp.SetRate(0, true); Extensions.Log("Set time warp to index 0"); } // HoldVesselUnpack is in display frames, not physics frames var teleportPosition = Body.GetRelSurfacePosition(Latitude, Longitude, alt + Altitude); var teleportVelocity = Vector3d.Cross(Body.angularVelocity, teleportPosition); //var teleportVelocity = Vector3d.Cross(Vector3d.down, teleportPosition.normalized)* // (Math.Cos(Latitude*(Math.PI/180))*teleportPosition.magnitude* // (Math.PI*2)/(Body.rotationPeriod)); // convert from world space to orbit space teleportPosition = teleportPosition.xzy; teleportVelocity = teleportVelocity.xzy; // counter for the momentary fall when on rails (about one second) teleportVelocity += teleportPosition.normalized * (Body.gravParameter / teleportPosition.sqrMagnitude); Quaternion rotation; if (SetRotation) { var from = Vector3d.up; var to = teleportPosition.xzy.normalized; rotation = Quaternion.FromToRotation(from, to); } else { var oldUp = vessel.orbit.pos.xzy.normalized; var newUp = teleportPosition.xzy.normalized; rotation = Quaternion.FromToRotation(oldUp, newUp) * vessel.vesselTransform.rotation; } var orbit = vessel.orbitDriver.orbit.Clone(); orbit.UpdateFromStateVectors(teleportPosition, teleportVelocity, Body, Planetarium.GetUniversalTime()); vessel.SetOrbit(orbit); vessel.SetRotation(rotation); AlreadyTeleported = true; } }
private static void SetWarpRate(long newRate, int maxRate) { int clampedValue = (int)Math.Max(Math.Min(newRate, maxRate), 0); TimeWarp.SetRate(clampedValue, false); }
/// <summary> /// Update a Flight Vessel button control (including KSPActionGroups) by name /// </summary> /// <param name="Name">The name of the axis to update</param> /// <param name="value">The value to set</param> public static void UpdateButton(AltMapping Mapping, float value) { int i; if (Mapping.Action == null) { return; } // If we are in a time warp, drop all actions besides the ones we authorise below if (TimeWarp.CurrentRate != 1) { switch (Mapping.Action) { case "increaseWarp": case "decreaseWarp": case "switchMode": case "switchView": case "toggleMapView": break; default: return; } } // Check if our mapping is a FlightCtrlState axis if (AxisFields.Where(item => item.Name == Mapping.Action).Any()) { UpdateAxis(Mapping, value * Mapping.Value, 1.0f); return; } // Most actions only need to occur when the button state is pressed. // We handle the few that don't here if (value < 0.5) { switch (Mapping.Action) { case "overrideRCS": FlightGlobals.ActiveVessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); break; case "activateBrakes": FlightGlobals.ActiveVessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, false); break; case "overrideSAS": FlightGlobals.ActiveVessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); break; case "activateCustom01": case "activateCustom02": case "activateCustom03": case "activateCustom04": case "activateCustom05": case "activateCustom06": case "activateCustom07": case "activateCustom08": case "activateCustom09": case "activateCustom10": int.TryParse(Mapping.Action.Substring("activateCustom##".Length), out i); if (i > 0) { FlightGlobals.ActiveVessel.ActionGroups.SetGroup((KSPActionGroup)(128 << i), true); } break; } return; } switch (Mapping.Action) { case "increaseWarp": // Do a bunch of checks to see if we can increase the warp rate: if (TimeWarp.CurrentRateIndex + 1 == TimeWarp.fetch.warpRates.Length) { break; // Already at max warp } if (!FlightGlobals.ActiveVessel.LandedOrSplashed) { CelestialBody mainBody = FlightGlobals.getMainBody(); double instantAltitudeASL = (FlightGlobals.ActiveVessel.CoM - mainBody.position).magnitude - mainBody.Radius; if (TimeWarp.fetch.GetAltitudeLimit(TimeWarp.CurrentRateIndex + 1, mainBody) > instantAltitudeASL) { break; // Altitude too low to increase warp } } if (TimeWarp.fetch.warpRates[TimeWarp.CurrentRateIndex] != TimeWarp.CurrentRate) { break; // Most recent warp change is not yet complete } TimeWarp.SetRate(TimeWarp.CurrentRateIndex + 1, false); break; case "decreaseWarp": if (TimeWarp.CurrentRateIndex == 0) { break; // Already at minimum warp } TimeWarp.SetRate(TimeWarp.CurrentRateIndex - 1, false); break; case "switchMode": Mode NextMode = GetNextMode(); if (NextMode != CurrentMode) { // Ensure that we reset our controls and buttons before switching // TODO: Drop ResetDevice() and check that no buttons/POVs are active besides mode switch instead CurrentDevice.ResetDevice(); CurrentMode = NextMode; ScreenMessages.PostScreenMessage("Input Mode: " + ModeName[(int)CurrentMode], 1f, ScreenMessageStyle.UPPER_CENTER); } break; case "switchView": FlightCamera fc = FlightCamera.fetch; fc.SetNextMode(); break; case "toggleMapView": if (MapView.MapIsEnabled) { MapView.ExitMapView(); } else { MapView.EnterMapView(); } break; case "toggleNavBall": // MapView.MapCollapse_navBall is not currently exposed by the API // so we need to use reflection ScreenSafeUISlideTab navball = (ScreenSafeUISlideTab)typeof(MapView). GetField("MapCollapse_navBall").GetValue(MapView.fetch); if (navball.expanded) { navball.Collapse(); } else { navball.Expand(); } break; case "activateStaging": Staging.ActivateNextStage(); break; case "toggleGears": FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup(KSPActionGroup.Gear); break; case "toggleLights": FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup(KSPActionGroup.Light); break; case "overrideRCS": FlightGlobals.ActiveVessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); break; case "toggleRCS": FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup(KSPActionGroup.RCS); break; case "overrideSAS": FlightGlobals.ActiveVessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true); break; case "toggleSAS": FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup(KSPActionGroup.SAS); break; case "toggleAbort": FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup(KSPActionGroup.Abort); break; case "activateBrakes": FlightGlobals.ActiveVessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, true); break; case "toggleBrakes": FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup(KSPActionGroup.Brakes); break; case "killThrottle": UpdatedState.mainThrottle = 0.0f; break; case "fullThrottle": UpdatedState.mainThrottle = 1.0f; break; case "toggleCustom01": case "toggleCustom02": case "toggleCustom03": case "toggleCustom04": case "toggleCustom05": case "toggleCustom06": case "toggleCustom07": case "toggleCustom08": case "toggleCustom09": case "toggleCustom10": int.TryParse(Mapping.Action.Substring("toggleCustom##".Length), out i); if (i > 0) { FlightGlobals.ActiveVessel.ActionGroups.ToggleGroup((KSPActionGroup)(128 << i)); } break; case "activateCustom01": case "activateCustom02": case "activateCustom03": case "activateCustom04": case "activateCustom05": case "activateCustom06": case "activateCustom07": case "activateCustom08": case "activateCustom09": case "activateCustom10": int.TryParse(Mapping.Action.Substring("activateCustom##".Length), out i); if (i > 0) { FlightGlobals.ActiveVessel.ActionGroups.SetGroup((KSPActionGroup)(128 << i), true); } break; default: print("AltInput: Unhandled action '" + Mapping.Action + "'"); break; } }
static void SetWarpFactor(TimeWarp.Modes mode, int factor) { SetWarpMode(mode); TimeWarp.SetRate(factor, false); }
public override void OnStart(StartState state) { if (state != StartState.Editor) { _timeWarp = TimeWarp.fetch; InitStylesIfNecessary(); InitWindowSizeIfNecessary(); InitWindowPositionIfNecessary(); RenderingManager.AddToPostDrawQueue(1, OnDraw); if (_isPowerOn) TurnOn(useState: true); else TurnOff(); } }
/// <summary> /// Update rover. /// </summary> /// <param name="currentTime">Current time.</param> /// <param name="module">BVModule.</param> /// <param name="vcf">Vessel Config Node.</param> public void Update(double currentTime, ConfigNode module, ConfigNode vcf) { if (vessel.isActiveVessel) { status = "current"; return; } if (!bvActive || vessel.loaded) { status = "idle"; return; } Vector3d vesselPos = vessel.mainBody.position - vessel.GetWorldPos3D(); Vector3d toKerbol = vessel.mainBody.position - FlightGlobals.Bodies[0].position; double angle = Vector3d.Angle(vesselPos, toKerbol); vesselConfigNode = vcf; BVModule = module; // Speed penalties at twighlight and at night if (angle > 90 && isManned) { speedMultiplier = 0.25; } else if (angle > 85 && isManned) { speedMultiplier = 0.5; } else if (angle > 80 && isManned) { speedMultiplier = 0.75; } else { speedMultiplier = 1.0; } double deltaT = currentTime - lastTime; double deltaEC = deltaT * requiredPower; // max power if (solarPower + fuelCellPower + otherPower < requiredPower || !enoughEC(deltaEC)) { status = "not enough power"; lastTime = currentTime; BVModule.SetValue("lastTime", currentTime.ToString()); vessel.protoVessel = new ProtoVessel(vesselConfigNode, HighLogic.CurrentGame); return; } // At night, don't move if other OR otherANDfuelcellnotdepleted can't provide enough power if (angle > 90 && !(otherPower > requiredPower || (otherPower + fuelCellPower > requiredPower && !fuelDepleted()))) { status = "awaiting sunlight"; lastTime = currentTime; BVModule.SetValue("lastTime", currentTime.ToString()); vessel.protoVessel = new ProtoVessel(vesselConfigNode, HighLogic.CurrentGame); return; } // At day, don't move if other OR otherANDsolar ... if (angle <= 90 && !(otherPower > requiredPower || (otherPower + solarPower > requiredPower) || !fuelDepleted())) { status = "fuel cells resource depleted"; lastTime = currentTime; BVModule.SetValue("lastTime", currentTime.ToString()); vessel.protoVessel = new ProtoVessel(vesselConfigNode, HighLogic.CurrentGame); return; } ECdrain(deltaEC); double deltaS = AverageSpeed * deltaT; double bearing = GeoUtils.InitialBearing( vessel.latitude, vessel.longitude, targetLatitude, targetLongitude ); distanceTravelled += deltaS; if (distanceTravelled >= distanceToTarget) { // vessel.latitude = targetLatitude; // vessel.longitude = targetLongitude; if (!MoveSafe(targetLatitude, targetLongitude)) { distanceTravelled -= deltaS; } else { distanceTravelled = distanceToTarget; bvActive = false; BVModule.SetValue("isActive", "False"); BVModule.SetValue("distanceTravelled", distanceToTarget.ToString()); BVModule.SetValue("pathEncoded", ""); // BVModule.GetNode ("EVENTS").GetNode ("Activate").SetValue ("active", "True"); // BVModule.GetNode ("EVENTS").GetNode ("Deactivate").SetValue ("active", "False"); if (BonVoyage.Instance.AutoDewarp) { if (TimeWarp.CurrentRate > 3) { TimeWarp.SetRate(3, true); } if (TimeWarp.CurrentRate > 0) { TimeWarp.SetRate(0, false); } ScreenMessages.PostScreenMessage(vessel.vesselName + " has arrived to destination at " + vessel.mainBody.name); } HoneyImHome(); } status = "idle"; } else { int step = Convert.ToInt32(Math.Floor(distanceTravelled / PathFinder.StepSize)); double remainder = distanceTravelled % PathFinder.StepSize; if (step < path.Count - 1) { bearing = GeoUtils.InitialBearing( path[step].latitude, path[step].longitude, path[step + 1].latitude, path[step + 1].longitude ); } else { bearing = GeoUtils.InitialBearing( path[step].latitude, path[step].longitude, targetLatitude, targetLongitude ); } double[] newCoordinates = GeoUtils.GetLatitudeLongitude( path[step].latitude, path[step].longitude, bearing, remainder, vessel.mainBody.Radius ); // vessel.latitude = newCoordinates[0]; // vessel.longitude = newCoordinates[1]; if (!MoveSafe(newCoordinates [0], newCoordinates [1])) { distanceTravelled -= deltaS; status = "idle"; } else { status = "roving"; } } // vessel.altitude = GeoUtils.TerrainHeightAt(vessel.latitude, vessel.longitude, vessel.mainBody); Save(currentTime); }
protected override void Awake() { base.Awake(); mTimeWarp = GetComponent<TimeWarp>(); }
//UPDATE FUNCTIONS private void Update() { preUpdate(); if (timeWarp != null) { if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready) { flightUpdate(); } } else if (HighLogic.LoadedScene != GameScenes.MAINMENU) { timeWarp = TimeWarp.fetch; } if (timeWarp == null) return; setWarpLevels(Settings.warpLevels); for (int i = 0; i < Settings.warpLevels; i++) { timeWarp.warpRates[i] = parseSTOI(Settings.customWarpRates[i]); for (int j = 0; j < PSystemManager.Instance.localBodies.Count; j++) { PSystemManager.Instance.localBodies[j].timeWarpAltitudeLimits[i] = parseSTOI(Settings.customAltitudeLimits[j][i]); } } if (timeWarp.current_rate_index >= Settings.warpLevels && timeWarp.Mode == TimeWarp.Modes.HIGH) { TimeWarp.SetRate(Settings.warpLevels - 1, false); } if ((Planetarium.GetUniversalTime() > warpTime || Mathf.Abs((float)Planetarium.GetUniversalTime() - (float)warpTime) < 60) && autoWarping) { autoWarping = false; } }
private void Update() { // Don't do anything until the settings are loaded if (!Settings.IsReady) return; if (HighLogic.LoadedScene == GameScenes.MAINMENU) { CurrentWarpState = TimeControllable.None; IsOperational = false; return; } if (timeWarp == null) { timeWarp = TimeWarp.fetch; if (timeWarp == null) return; } UpdateRails(); switch (CurrentWarpState) { case TimeControllable.SlowMo: UpdateSlowMo(); break; case TimeControllable.Hyper: UpdateHyper(); break; case TimeControllable.None: CurrentControllerMessage = ""; break; } UpdatePaused(); }
public void onFlightStart() { loadSettings(); RenderingManager.AddToPostDrawQueue(0, new Callback(drawGUI)); firstDraw = true; FlightInputHandler.OnFlyByWire += new FlightInputHandler.FlightInputCallback(onFlyByWire); flyByWire = true; attitudeTo(Quaternion.LookRotation(part.vessel.transform.up, -part.vessel.transform.forward), MechJebCore.AttitudeReference.INERTIAL, null); _attitudeActive = false; attitudeChanged = false; timeWarp = (TimeWarp)GameObject.FindObjectOfType(typeof(TimeWarp)); foreach (ComputerModule module in modules) { module.onFlightStart(); } }
// Return which of the two rates arrays is to be used for the given mode: private float[] GetRateArrayForMode(TimeWarp.Modes whichMode) { float[] rateArray; switch (whichMode) { case TimeWarp.Modes.HIGH: rateArray = TimeWarp.fetch.warpRates; break; case TimeWarp.Modes.LOW: rateArray = TimeWarp.fetch.physicsWarpRates; break; default: throw new Exception(string.Format("WARP MODE {0} unknown to kOS - did KSP's API change?", TimeWarp.WarpMode.ToString())); } return rateArray; }
static void SetWarpFactor (TimeWarp.Modes mode, int factor) { SetWarpMode (mode); TimeWarp.SetRate (factor, false); }
private void MaintainContainment() { var antimatterResource = part.Resources.Get(_antimatterDefinition.id); if (antimatterResource == null) { return; } if (chargeStatus > 0 && antimatterResource.amount > _minimumAntimatterAmount) { // chargeStatus is in seconds chargeStatus -= vessel.packed ? 0.05f : TimeWarp.fixedDeltaTime; } if (!_shouldCharge && antimatterResource.amount <= _minimumAntimatterAmount) { return; } var powerModifier = canExplodeFromGeeForce ? (resourceRatio * (currentGeeForce / 10) * 0.8) + ((part.temperature / 1000) * 0.2) : Math.Pow(resourceRatio, 2); effectivePowerNeeded = chargeNeeded * powerModifier; if (effectivePowerNeeded > 0.0) { double powerRequest = (chargeStatus >= maxCharge ? 1.0 : 2.0) * effectivePowerNeeded; double chargeToAdd = TimeWarp.fixedDeltaTime * ConsumeMegawatts(powerRequest / GameConstants.ecPerMJ, true, true, true) * GameConstants.ecPerMJ / effectivePowerNeeded; chargeStatus += chargeToAdd; if (chargeToAdd >= TimeWarp.fixedDeltaTime) { _charging = true; } else { _charging = false; if (TimeWarp.CurrentRateIndex > 3 && (antimatterResource.amount > _minimumAntimatterAmount)) { TimeWarp.SetRate(3, true); ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg7", TimeWarp.CurrentRate, antimatterResource.resourceName), 1, ScreenMessageStyle.UPPER_CENTER);//"Cannot Time Warp faster than " + + "x while " + + " Tank is Unpowered" } } } if (_startupTimeout > 0) { _startupTimeout--; } if (_startupTimeout == 0 && antimatterResource.amount > _minimumAntimatterAmount) { //verify temperature if (!CheatOptions.IgnoreMaxTemperature && canExplodeFromHeat && part.temperature > (double)(decimal)maxTemperature) { _temperatureExplodeCounter++; if (_temperatureExplodeCounter > 20) { DoExplode(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg8"));//"Antimatter container exploded due to reaching critical temperature" } } else { _temperatureExplodeCounter = 0; } //verify geeforce _effectiveMaxGeeforce = resourceRatio > 0 ? Math.Min(10, maxGeeforce / resourceRatio) : 10; if (!CheatOptions.UnbreakableJoints && canExplodeFromGeeForce) { if (vessel.missionTime > 0) { if (currentGeeForce > _effectiveMaxGeeforce) { ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg9"), 1, ScreenMessageStyle.UPPER_CENTER);//"ALERT: geeforce at critical!" _geeforceExplodeCounter++; if (_geeforceExplodeCounter > 30) { DoExplode(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg10"));//"Antimatter container exploded due to reaching critical geeforce" } } else if (TimeWarp.CurrentRateIndex > maximumTimewarpWithGeeforceWarning && currentGeeForce > _effectiveMaxGeeforce - 0.02) { TimeWarp.SetRate(maximumTimewarpWithGeeforceWarning, true); ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg11", TimeWarp.CurrentRate), 1, ScreenMessageStyle.UPPER_CENTER);//"ALERT: Cannot Time Warp faster than " + + "x while geeforce near maximum tolerance!" } else if (currentGeeForce > _effectiveMaxGeeforce - 0.04) { ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg12", (currentGeeForce / _effectiveMaxGeeforce * 100).ToString("F2")), 1, ScreenMessageStyle.UPPER_CENTER);//"ALERT: geeforce at " + + "% tolerance!" } else { _geeforceExplodeCounter = 0; } } else if (currentGeeForce > _effectiveMaxGeeforce) { ScreenMessages.PostScreenMessage(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg13"), 1, ScreenMessageStyle.UPPER_CENTER);//"Warning: geeforce tolerance exceeded but sustanable while the mission timer has not started" } } else { _geeforceExplodeCounter = 0; } //verify power if (chargeStatus <= 0) { chargeStatus = 0; if (!CheatOptions.InfiniteElectricity && antimatterResource.amount > 0.00001 * antimatterResource.maxAmount) { _powerExplodeCounter++; if (_powerExplodeCounter > 20) { DoExplode(Localizer.Format("#LOC_KSPIE_AntimatterStorageTank_Postmsg14"));//"Antimatter container exploded due to running out of power" } } } else { _powerExplodeCounter = 0; } } else { _effectiveMaxGeeforce = 0; _temperatureExplodeCounter = 0; _geeforceExplodeCounter = 0; _powerExplodeCounter = 0; } if (chargeStatus > maxCharge) { chargeStatus = maxCharge; } }