Skip to content

Commit

Permalink
ToSI tweaks
Browse files Browse the repository at this point in the history
It looks like maxPrecision is designed to avoid things like
"0.0000000001 qm" for very small values and turn that into
"0.000 qm" instead.  What using values like "-1" did is just
kind of butcher the formatting for values smaller than 1.0 and
lose the significant digits.  There's an optimal value for a given
number of sigfigs to set maxPrecision to in order to get a fixed-width
number of characters of precision that doesn't overflow with very,
very tiny values.  That is now the default, and it adapts by default to
the setting of SigFigs..  The arguments have also been swapped so
that sigFigs is first and that's the one that should probably
be used.

When it comes to existing uses, stuff like ToSI(-1) has been converted
to the default.  When it comes to ToSI(3) that probably was intended to
mean 3 sigFigs but never did that so most of that is just set to the
default as well.  Stuff that was ToSI(-1, 3) has been converted to
ToSI(3) since that was correctly setting 3 sigFigs.

Signed-off-by: Lamont Granquist <lamont@scriptkiddie.org>
  • Loading branch information
lamont-granquist committed May 16, 2023
1 parent a380a1f commit 02fab0d
Show file tree
Hide file tree
Showing 13 changed files with 167 additions and 129 deletions.
6 changes: 3 additions & 3 deletions MechJeb2/MechJebLib/PVG/Solution.cs
Expand Up @@ -309,9 +309,9 @@ public string TerminalString()
double vT = vf.magnitude;

var sb = new StringBuilder();
sb.AppendLine($"Orbit: {peA.ToSI(0)}m x {apA.ToSI(0)}m");
sb.AppendLine($"rT: {rT.ToSI(0)}m vT: {vT.ToSI(0)}m/s FPA: {Rad2Deg(fpa):F1}°");
sb.AppendLine($"sma: {sma.ToSI(0)}m ecc: {ecc:F3} inc: {Rad2Deg(inc):F1}°");
sb.AppendLine($"Orbit: {peA.ToSI()}m x {apA.ToSI()}m");
sb.AppendLine($"rT: {rT.ToSI()}m vT: {vT.ToSI()}m/s FPA: {Rad2Deg(fpa):F1}°");
sb.AppendLine($"sma: {sma.ToSI()}m ecc: {ecc:F3} inc: {Rad2Deg(inc):F1}°");
sb.Append($"lan: {Rad2Deg(lan):F1}° argp: {Rad2Deg(argp):F1}° ta: {Rad2Deg(tanom):F1}°");
return sb.ToString();
}
Expand Down
6 changes: 4 additions & 2 deletions MechJeb2/MechJebLib/Utils/Statics.cs
Expand Up @@ -415,13 +415,15 @@ public static double DoubleArrayMagnitude(IList<double> array)
private static readonly string[] _posPrefix = { " ", "k", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q" };
private static readonly string[] _negPrefix = { " ", "m", "μ", "n", "p", "f", "a", "z", "y", "r", "q" };

public static string ToSI(this double d, int maxPrecision = -99, int sigFigs = 4)
public static string ToSI(this double d, int sigFigs = 4, int maxPrecision = int.MaxValue)
{
if (!IsFinite(d)) return d.ToString();

if (maxPrecision == int.MaxValue)
maxPrecision = -29 - sigFigs;

// this is an offset to d to deal with rounding (e.g. 9.9995 gets rounded to 10.00 so gains a wholeDigit)
// (also 999.95 should be rounded to 1k, so bumps up an SI prefix)
// FIXME: probably needs to be fixed to work when maxPrecision kicks in
double offset = 5 * (d != 0 ? Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) - sigFigs) : 0);

int exponent = (int)Math.Floor(Math.Log10(Math.Abs(d) + offset));
Expand Down
6 changes: 3 additions & 3 deletions MechJeb2/MechJebModuleAscentClassicPathMenu.cs
Expand Up @@ -66,13 +66,13 @@ protected override void WindowGUI(int windowID)
{
GUILayout.BeginHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_AscentPathEd_label3"), GUILayout.ExpandWidth(false)); //"Turn start when Altitude is "
GUILayout.Label(_ascentSettings.AutoTurnStartAltitude.ToSI( -1, 2) + "m ", GUILayout.ExpandWidth(false));
GUILayout.Label(_ascentSettings.AutoTurnStartAltitude.ToSI(2) + "m ", GUILayout.ExpandWidth(false));
GUILayout.Label(Localizer.Format("#MechJeb_AscentPathEd_label4"), GUILayout.ExpandWidth(false)); //"or Velocity reach "
GUILayout.Label(_ascentSettings.AutoTurnStartVelocity.ToSI(-1, 3) + "m/s", GUILayout.ExpandWidth(false)); //
GUILayout.Label(_ascentSettings.AutoTurnStartVelocity.ToSI(3) + "m/s", GUILayout.ExpandWidth(false)); //
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label(Localizer.Format("#MechJeb_AscentPathEd_label5")); //"Turn end altitude: "
GUILayout.Label(_ascentSettings.AutoTurnEndAltitude.ToSI(-1, 2) + "m", GuiUtils.middleRightLabel,
GUILayout.Label(_ascentSettings.AutoTurnEndAltitude.ToSI(2) + "m", GuiUtils.middleRightLabel,
GUILayout.ExpandWidth(true));
GUILayout.EndHorizontal();
}
Expand Down
8 changes: 4 additions & 4 deletions MechJeb2/MechJebModuleCustomInfoWindow.cs
Expand Up @@ -245,7 +245,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global
foreach (ConfigNode windowNode in windowNodes)
{
MechJebModuleCustomInfoWindow window = new MechJebModuleCustomInfoWindow(core);

ConfigNode.LoadObjectFromConfig(window, windowNode);

window.UpdateRefreshRate();
Expand Down Expand Up @@ -290,7 +290,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global
window.enabledEditor = window.enabled;
window.enabledFlight = window.enabled;
}

window.items = new List<InfoItem>();

if (windowNode.HasNode("items"))
Expand Down Expand Up @@ -706,7 +706,7 @@ string GetStringValue(object value)
else if (format == ANGLE) return Coordinates.AngleToDMS(doubleValue);
else if (format == ANGLE_NS) return Coordinates.AngleToDMS(doubleValue) + (doubleValue > 0 ? " N" : " S");
else if (format == ANGLE_EW) return Coordinates.AngleToDMS(doubleValue) + (doubleValue > 0 ? " E" : " W");
else if (format == SI) return (doubleValue.ToSI( siMaxPrecision, siSigFigs) + units);
else if (format == SI) return (doubleValue.ToSI( siSigFigs, siMaxPrecision) + units);
else return doubleValue.ToString(format) + " " + units;
}

Expand Down Expand Up @@ -862,7 +862,7 @@ public class ValueInfoItemAttribute : InfoItemAttribute
public string units = "";
public string format = "";
public int siSigFigs = 4;
public int siMaxPrecision = -99;
public int siMaxPrecision = -33;
public int timeDecimalPlaces = 0;

public ValueInfoItemAttribute(string name, InfoItem.Category category) : base(name, category) { }
Expand Down
8 changes: 4 additions & 4 deletions MechJeb2/MechJebModuleFlightRecorderGraph.cs
Expand Up @@ -136,7 +136,7 @@ protected override void WindowGUI(int windowID)

GUILayout.Label(Localizer.Format("#MechJeb_Flightrecord_Label1", GuiUtils.TimeToDHMS(recorder.timeSinceMark)), GUILayout.ExpandWidth(false));//Time <<1>>

GUILayout.Label(Localizer.Format("#MechJeb_Flightrecord_Label2", recorder.history[recorder.historyIdx].downRange.ToSI(-2)) + "m", GUILayout.ExpandWidth(false));//Downrange <<1>>
GUILayout.Label(Localizer.Format("#MechJeb_Flightrecord_Label2", recorder.history[recorder.historyIdx].downRange.ToSI()) + "m", GUILayout.ExpandWidth(false));//Downrange <<1>>

//GUILayout.Label("", GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
Expand Down Expand Up @@ -175,7 +175,7 @@ protected override void WindowGUI(int windowID)

double scaleX = downrange ? Math.Pow(2, activeScaleX) : precision * Math.Pow(2, activeScaleX);

GUILayout.Label((downrange ? scaleX.ToSI(-1, 2) + "m/px" : GuiUtils.TimeToDHMS(scaleX, 1) + "/px"), GUILayout.ExpandWidth(false));
GUILayout.Label((downrange ? scaleX.ToSI(2) + "m/px" : GuiUtils.TimeToDHMS(scaleX, 1) + "/px"), GUILayout.ExpandWidth(false));

if (!autoScale && GUILayout.Button("+", GUILayout.ExpandWidth(false)))
{
Expand Down Expand Up @@ -310,7 +310,7 @@ protected override void WindowGUI(int windowID)

GUILayout.BeginVertical();

//GUILayout.Label("X " + MuUtils.ToSI(hPos, -1, 2) + " " + MuUtils.ToSI(hPos + scaleX * width, -1, 2), GUILayout.Width(110));
//GUILayout.Label("X " + hPos.ToSI(2) + " " + (hPos+scaleX*width).ToSI(2), GUILayout.Width(110));

color = GUI.color;

Expand Down Expand Up @@ -514,7 +514,7 @@ private void DrawScaleLabels(Rect r)

const int w = 80;
const int h = 20;

graphState state = graphStates[scaleIdx];
if (state.labels == null)
return;
Expand Down
24 changes: 12 additions & 12 deletions MechJeb2/MechJebModuleInfoItems.cs
Expand Up @@ -14,7 +14,7 @@ namespace MuMech
{
//This class just exists to collect miscellaneous info item functions in one place.
//If any of these functions are useful in another module, they should be moved there.

[UsedImplicitly]
public class MechJebModuleInfoItems : ComputerModule
{
Expand Down Expand Up @@ -53,7 +53,7 @@ public string NextManeuverNodeDeltaV()
{
if (!vessel.patchedConicsUnlocked() || !vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A";

return vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(orbit).magnitude.ToSI(-1) + "m/s";
return vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(orbit).magnitude.ToSI() + "m/s";
}

[ValueInfoItem("#MechJeb_SurfaceTWR", InfoItem.Category.Vessel, format = "F2", showInEditor = true)]//Surface TWR
Expand Down Expand Up @@ -94,7 +94,7 @@ public string GetCoordinateString()

public string OrbitSummary(Orbit o)
{
return (o.eccentricity > 1) ? $"hyperbolic, Pe = {o.PeA.ToSI(2)}m" : $"{o.PeA.ToSI(2)}m x {o.ApA.ToSI(2)}m";
return (o.eccentricity > 1) ? $"hyperbolic, Pe = {o.PeA.ToSI()}m" : $"{o.PeA.ToSI()}m x {o.ApA.ToSI()}m";
}

public string OrbitSummaryWithInclination(Orbit o)
Expand Down Expand Up @@ -387,7 +387,7 @@ public double MonoPropellantMass()
return vessel.TotalResourceMass("MonoPropellant");
}

[ValueInfoItem("#MechJeb_TotalElectricCharge", InfoItem.Category.Vessel, showInEditor = true, format = ValueInfoItem.SI, siMaxPrecision = 1, units = "Ah")]//Total electric charge
[ValueInfoItem("#MechJeb_TotalElectricCharge", InfoItem.Category.Vessel, showInEditor = true, format = ValueInfoItem.SI, units = "Ah")]//Total electric charge
public double TotalElectricCharge()
{
return vessel.TotalResourceAmount(PartResourceLibrary.ElectricityHashcode);
Expand Down Expand Up @@ -534,7 +534,7 @@ public int CrewCapacity()
public string TargetDistance()
{
if (core.target.Target == null) return "N/A";
return core.target.Distance.ToSI(-1) + "m";
return core.target.Distance.ToSI() + "m";
}

[ValueInfoItem("#MechJeb_HeadingToTarget", InfoItem.Category.Target)]//Heading to target
Expand Down Expand Up @@ -575,7 +575,7 @@ public string TargetClosestApproachDistance()
if (core.target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A";
if (vesselState.altitudeTrue < 1000.0) { return "N/A"; }
if (double.IsNaN(core.target.TargetOrbit.semiMajorAxis)) { return "N/A"; }
return orbit.NextClosestApproachDistance(core.target.TargetOrbit, vesselState.time).ToSI(-1) + "m";
return orbit.NextClosestApproachDistance(core.target.TargetOrbit, vesselState.time).ToSI() + "m";
}

[ValueInfoItem("#MechJeb_RelativeVelocityAtClosestApproach", InfoItem.Category.Target)]//Rel. vel. at closest approach
Expand All @@ -598,7 +598,7 @@ public string TargetClosestApproachRelativeVelocity()
double relVel =
(orbit.WorldOrbitalVelocityAtUT(UT) - core.target.TargetOrbit.WorldOrbitalVelocityAtUT(UT))
.magnitude;
return relVel.ToSI(-1) + "m/s";
return relVel.ToSI() + "m/s";
}
catch
{
Expand Down Expand Up @@ -627,7 +627,7 @@ public string PeriapsisInTargetSOI()

if (o == null) return "N/A";

return o.PeA.ToSI(-1) + "m";
return o.PeA.ToSI() + "m";
}

[ValueInfoItem("#MechJeb_TargetCaptureDV", InfoItem.Category.Misc)]//ΔV for capture by target
Expand All @@ -645,22 +645,22 @@ public string TargetCaptureDV()
double velAtPeriapsis = Math.Sqrt(o.referenceBody.gravParameter * (2 / o.PeR - 1 / o.semiMajorAxis));
double velCapture = Math.Sqrt(o.referenceBody.gravParameter * (2 / o.PeR - 1 / smaCapture));

return (velAtPeriapsis - velCapture).ToSI(-1) + "m/s";
return (velAtPeriapsis - velCapture).ToSI() + "m/s";
}


[ValueInfoItem("#MechJeb_TargetApoapsis", InfoItem.Category.Target)]//Target apoapsis
public string TargetApoapsis()
{
if (!core.target.NormalTargetExists) return "N/A";
return core.target.TargetOrbit.ApA.ToSI(2) + "m";
return core.target.TargetOrbit.ApA.ToSI() + "m";
}

[ValueInfoItem("#MechJeb_TargetPeriapsis", InfoItem.Category.Target)]//Target periapsis
public string TargetPeriapsis()
{
if (!core.target.NormalTargetExists) return "N/A";
return core.target.TargetOrbit.PeA.ToSI(2) + "m";
return core.target.TargetOrbit.PeA.ToSI() + "m";
}

[ValueInfoItem("#MechJeb_TargetInclination", InfoItem.Category.Target)]//Target inclination
Expand Down Expand Up @@ -748,7 +748,7 @@ public string TargetEccentricity()
public string TargetSMA()
{
if (!core.target.NormalTargetExists) return "N/A";
return core.target.TargetOrbit.semiMajorAxis.ToSI(2) + "m";
return core.target.TargetOrbit.semiMajorAxis.ToSI() + "m";
}

[ValueInfoItem("#MechJeb_TargetMeanAnomaly", InfoItem.Category.Target, format = ValueInfoItem.ANGLE)]//Target Mean Anomaly
Expand Down
18 changes: 9 additions & 9 deletions MechJeb2/MechJebModuleLandingGuidance.cs
Expand Up @@ -80,7 +80,7 @@ protected override void WindowGUI(int windowID)
GUILayout.EndHorizontal();

GUILayout.BeginHorizontal();
GUILayout.Label("ASL: " + ASL.ToSI(-1, 4) + "m");
GUILayout.Label("ASL: " + ASL.ToSI() + "m");
GUILayout.Label(core.target.targetBody.GetExperimentBiomeSafe(core.target.targetLatitude, core.target.targetLongitude));
GUILayout.EndHorizontal();
}
Expand Down Expand Up @@ -144,9 +144,9 @@ protected override void WindowGUI(int windowID)

if (core.landing.enabled)
{
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label6") + core.landing.status);//Status:
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label7") + (core.landing.CurrentStep != null ? core.landing.CurrentStep.GetType().Name : "N/A"));//Step:
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label8") + (core.landing.descentSpeedPolicy != null ? core.landing.descentSpeedPolicy.GetType().Name : "N/A") + " (" + core.landing.UseAtmosphereToBrake().ToString() + ")");//Mode
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label6") + core.landing.status);//Status:
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label7") + (core.landing.CurrentStep != null ? core.landing.CurrentStep.GetType().Name : "N/A"));//Step:
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label8") + (core.landing.descentSpeedPolicy != null ? core.landing.descentSpeedPolicy.GetType().Name : "N/A") + " (" + core.landing.UseAtmosphereToBrake().ToString() + ")");//Mode
//GUILayout.Label("DecEndAlt: " + core.landing.DecelerationEndAltitude().ToString("F2"));
//var dragLength = mainBody.DragLength(core.landing.LandingAltitude, core.landing.vesselAverageDrag, vesselState.mass);
//GUILayout.Label("Drag Length: " + ( dragLength < double.MaxValue ? dragLength.ToString("F2") : "infinite"));
Expand Down Expand Up @@ -207,7 +207,7 @@ void DrawGUITogglePredictions()

GUILayout.EndVertical();
}

void DrawGUIPrediction()
{
ReentrySimulation.Result result = predictor.Result;
Expand All @@ -217,20 +217,20 @@ void DrawGUIPrediction()
{
case ReentrySimulation.Outcome.LANDED:
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label9"));//Landing Predictions:
GUILayout.Label(Coordinates.ToStringDMS(result.EndPosition.Latitude, result.EndPosition.Longitude) + "\nASL:" + result.EndASL.ToSI(-1, 4) + "m");
GUILayout.Label(Coordinates.ToStringDMS(result.EndPosition.Latitude, result.EndPosition.Longitude) + "\nASL:" + result.EndASL.ToSI() + "m");
GUILayout.Label(result.Body.GetExperimentBiomeSafe(result.EndPosition.Latitude, result.EndPosition.Longitude));
double error = Vector3d.Distance(mainBody.GetWorldSurfacePosition(result.EndPosition.Latitude, result.EndPosition.Longitude, 0) - mainBody.position,
mainBody.GetWorldSurfacePosition(core.target.targetLatitude, core.target.targetLongitude, 0) - mainBody.position);
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label10") + error.ToSI(0) + "m"
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label10") + error.ToSI() + "m"
+ Localizer.Format("#MechJeb_LandingGuidance_Label11") + result.MaxDragGees.ToString("F1") +"g"
+Localizer.Format("#MechJeb_LandingGuidance_Label12") + result.DeltaVExpended.ToString("F1") + "m/s"
+Localizer.Format("#MechJeb_LandingGuidance_Label13") + (vessel.Landed ? "0.0s" : GuiUtils.TimeToDHMS(result.EndUT - Planetarium.GetUniversalTime(), 1)));//Target difference = \nMax drag: \nDelta-v needed: \nTime to land:
+Localizer.Format("#MechJeb_LandingGuidance_Label13") + (vessel.Landed ? "0.0s" : GuiUtils.TimeToDHMS(result.EndUT - Planetarium.GetUniversalTime(), 1)));//Target difference = \nMax drag: \nDelta-v needed: \nTime to land:
break;

case ReentrySimulation.Outcome.AEROBRAKED:
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label14"));//Predicted orbit after aerobraking:
Orbit o = result.AeroBrakeOrbit();
if (o.eccentricity > 1) GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label15") + o.eccentricity.ToString("F2"));//Hyperbolic, eccentricity =
if (o.eccentricity > 1) GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label15") + o.eccentricity.ToString("F2"));//Hyperbolic, eccentricity =
else GUILayout.Label(o.PeA.ToSI(3) + "m x " + o.ApA.ToSI(3) + "m");
GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label16", result.MaxDragGees.ToString("F1"))+Localizer.Format("#MechJeb_LandingGuidance_Label17", GuiUtils.TimeToDHMS(result.AeroBrakeUT - Planetarium.GetUniversalTime(), 1)));//Max drag:<<1>>g \nExit atmosphere in:
break;
Expand Down
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModuleRendezvousGuidance.cs
Expand Up @@ -43,7 +43,7 @@ protected override void WindowGUI(int windowID)

double closestApproachTime = orbit.NextClosestApproachTime(core.target.TargetOrbit, vesselState.time);
GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label7"), GuiUtils.TimeToDHMS(closestApproachTime - vesselState.time));//"Time until closest approach"
GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label8"), orbit.Separation(core.target.TargetOrbit, closestApproachTime).ToSI(0) + "m");//"Separation at closest approach"
GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label8"), orbit.Separation(core.target.TargetOrbit, closestApproachTime).ToSI() + "m");//"Separation at closest approach"


//Maneuver planning buttons:
Expand Down
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModuleSpaceplaneGuidance.cs
Expand Up @@ -45,7 +45,7 @@ protected override void WindowGUI(int windowID)
runwayIndex = GuiUtils.ComboBox.Box(runwayIndex, availableRunways.Select(p => p.name).ToArray(), this);
autoland.runway = availableRunways[runwayIndex];

GUILayout.Label(Localizer.Format("#MechJeb_ApproAndLand_label2") + Vector3d.Distance(vesselState.CoM, autoland.runway.Start()).ToSI(0) + "m");//Distance to runway:
GUILayout.Label(Localizer.Format("#MechJeb_ApproAndLand_label2") + Vector3d.Distance(vesselState.CoM, autoland.runway.Start()).ToSI() + "m");//Distance to runway:

showLandingTarget = GUILayout.Toggle(showLandingTarget, Localizer.Format("#MechJeb_ApproAndLand_label3"));//Show landing navball guidance

Expand Down
2 changes: 1 addition & 1 deletion MechJeb2/MechJebStageStatsHelper.cs
Expand Up @@ -234,7 +234,7 @@ public void AllStageStats()
altSLTScale = GUILayout.HorizontalSlider(altSLTScale, 0, 1, GUILayout.ExpandWidth(true));
infoItems.altSLTScale = altSLTScale;
stats.altSLT = Math.Pow(altSLTScale, 2) * stats.editorBody.atmosphereDepth;
GUILayout.Label(stats.altSLT.ToSI(2) + "m", GUILayout.Width(80));
GUILayout.Label(stats.altSLT.ToSI() + "m", GUILayout.Width(80));
GUILayout.EndHorizontal();

GUILayout.BeginHorizontal();
Expand Down

0 comments on commit 02fab0d

Please sign in to comment.