Skip to content

Commit

Permalink
Finished threading and everything done on the TODO list
Browse files Browse the repository at this point in the history
Really I don't think its done though but its time to start
iterating on bugfixing and get feedback.

Signed-off-by: Lamont Granquist <lamont@scriptkiddie.org>
  • Loading branch information
lamont-granquist committed Jul 11, 2023
1 parent 2b5ee16 commit ec3be1b
Show file tree
Hide file tree
Showing 12 changed files with 168 additions and 89 deletions.
12 changes: 7 additions & 5 deletions MechJeb2/MechJebLib/Simulations/FuelFlowSimulation.cs
Expand Up @@ -4,13 +4,11 @@
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MechJebLib.Simulations.PartModules;
using MechJebLib.Utils;

namespace MechJebLib.Simulations
{
// TODO:
// - add threading
// - throttle running in VAB
public class FuelFlowSimulation
public class FuelFlowSimulation : BackgroundJob<bool>
{
private const int MAXSTEPS = 100;

Expand All @@ -21,8 +19,10 @@ public class FuelFlowSimulation
private readonly HashSet<SimPart> _partsWithResourceDrains = new HashSet<SimPart>();
private bool _allocatedFirstSegment;

public void Run(SimVessel vessel)
protected override bool Run(object? o)
{
var vessel = (SimVessel)o!;

_allocatedFirstSegment = false;
_time = 0;
Segments.Clear();
Expand All @@ -40,6 +40,8 @@ public void Run(SimVessel vessel)
Segments.Reverse();

_partsWithResourceDrains.Clear();

return true; // we pull results off the object not off the return value
}

private void SimulateStage(SimVessel vessel)
Expand Down
12 changes: 6 additions & 6 deletions MechJeb2/MechJebLib/Simulations/SimVesselManager.cs
Expand Up @@ -8,14 +8,14 @@ namespace MechJebLib.Simulations
// need to link against KSP GameObjects (MechJebLibBindings.dll or something like that)
public partial class SimVesselManager
{
public List<FuelStats> Segments => _fuelFlowSimulation.Segments;
public List<FuelStats> Segments => FuelFlowSimulation.Segments;

private readonly SimVesselBuilder _builder;
private readonly SimVesselUpdater _updater;
private SimVessel _vessel;
private IShipconstruct _kspVessel;
private readonly FuelFlowSimulation _fuelFlowSimulation = new FuelFlowSimulation();
public bool DVLinearThrust = true; // include cos losses
public readonly FuelFlowSimulation FuelFlowSimulation = new FuelFlowSimulation();
public bool DVLinearThrust = true; // include cos losses

private readonly Dictionary<Part, SimPart> _partMapping = new Dictionary<Part, SimPart>();
private readonly Dictionary<SimPart, Part> _inversePartMapping = new Dictionary<SimPart, Part>();
Expand Down Expand Up @@ -51,10 +51,10 @@ public void SetConditions(double atmDensity, double atmPressure, double machNumb
_vessel.SetConditions(atmDensity, atmPressure, machNumber);
}

public void RunFuelFlowSimulation()
public void StartFuelFlowSimulationJob()
{
_fuelFlowSimulation.DVLinearThrust = DVLinearThrust;
_fuelFlowSimulation.Run(_vessel);
FuelFlowSimulation.DVLinearThrust = DVLinearThrust;
FuelFlowSimulation.StartJob(_vessel);
}

private void Clear()
Expand Down
7 changes: 4 additions & 3 deletions MechJeb2/MechJebLib/Suicide.cs
@@ -1,4 +1,5 @@
using MechJebLib.Primitives;
using System;
using MechJebLib.Primitives;
using MechJebLib.Utils;

namespace MuMech.MechJebLib
Expand All @@ -16,9 +17,9 @@ public static SuicideBuilder Builder()
return new SuicideBuilder();
}

protected override SuicideResult Execute()
protected override SuicideResult Run(object o)
{
throw new System.NotImplementedException();
throw new NotImplementedException();
}
}
}
41 changes: 31 additions & 10 deletions MechJeb2/MechJebLib/Utils/BackgroundJob.cs
@@ -1,4 +1,6 @@

using System;
using System.Threading;
using System.Threading.Tasks;

#nullable enable
Expand All @@ -11,9 +13,18 @@ namespace MechJebLib.Utils
public abstract class BackgroundJob<T>
{
private Task<T>? _task;
public T Result = default!;
public T Result = default!;
public bool ResultReady;

protected abstract T Run(object? o);

protected abstract T Execute();
public BackgroundJob()
{
_executeDelegate = Run;
_onTaskCompletedDelegate = OnTaskCompleted;
_onTaskFaultedDelegate = OnTaskFaulted;
_onTaskCancelledDelegate = OnTaskCancelled;
}

public void Cancel()
{
Expand All @@ -22,13 +33,17 @@ public void Cancel()

public bool IsRunning()
{
return !(_task is { IsCompleted: true });
if (_task is null)
return false;

return _task.IsCompleted == false;
}

protected virtual void OnTaskCompleted(Task<T> task)
{
Result = task.Result;
_task = null;
Result = task.Result;
ResultReady = true;
_task = null;
}

protected virtual void OnTaskFaulted(Task<T> task)
Expand All @@ -41,12 +56,18 @@ protected virtual void OnTaskCancelled(Task<T> task)
_task = null;
}

public void Run()
private readonly Func<object?, T> _executeDelegate;
private readonly Action<Task<T>> _onTaskCompletedDelegate;
private readonly Action<Task<T>> _onTaskFaultedDelegate;
private readonly Action<Task<T>> _onTaskCancelledDelegate;

public void StartJob(object? o)
{
_task = Task.Run(Execute);
_task.ContinueWith(OnTaskCompleted, TaskContinuationOptions.OnlyOnRanToCompletion);
_task.ContinueWith(OnTaskFaulted, TaskContinuationOptions.OnlyOnFaulted);
_task.ContinueWith(OnTaskCancelled, TaskContinuationOptions.OnlyOnCanceled);
ResultReady = false;
_task = Task.Factory.StartNew(_executeDelegate, o, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
_task.ContinueWith(_onTaskCompletedDelegate, TaskContinuationOptions.OnlyOnRanToCompletion);
_task.ContinueWith(_onTaskFaultedDelegate, TaskContinuationOptions.OnlyOnFaulted);
_task.ContinueWith(_onTaskCancelledDelegate, TaskContinuationOptions.OnlyOnCanceled);
}
}
}
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModuleAscentBaseAutopilot.cs
Expand Up @@ -94,7 +94,7 @@ public void StartCountdown(double time)
public override void OnFixedUpdate()
{
if (AscentSettings.AscentType == AscentType.PVG)
Core.StageStats.RequestUpdate(this);
Core.StageStats.RequestUpdate();

FixupLaunchStart();
if (TimedLaunch)
Expand Down
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModuleAscentMenu.cs
Expand Up @@ -417,7 +417,7 @@ protected override void WindowGUI(int windowID)

if (_ascentSettings.AscentType == AscentType.PVG)
{
Core.StageStats.RequestUpdate(this);
Core.StageStats.RequestUpdate();
_pvgSettingsMenu.Enabled = GUILayout.Toggle(_pvgSettingsMenu.Enabled, "PVG Settings");
}

Expand Down
14 changes: 7 additions & 7 deletions MechJeb2/MechJebModuleInfoItems.cs
Expand Up @@ -943,7 +943,7 @@ public void UpdateItems()
public double StageDeltaVVacuum()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();

if (stats.VacStats.Count == 0) return 0;

Expand All @@ -954,7 +954,7 @@ public double StageDeltaVVacuum()
public double StageDeltaVAtmosphere()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();

if (stats.AtmoStats.Count == 0) return 0;

Expand All @@ -965,7 +965,7 @@ public double StageDeltaVAtmosphere()
public string StageDeltaVAtmosphereAndVac()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();

double atmDv = stats.AtmoStats.Count == 0 ? 0 : stats.AtmoStats[stats.AtmoStats.Count - 1].DeltaV;
double vacDv = stats.VacStats.Count == 0 ? 0 : stats.VacStats[stats.VacStats.Count - 1].DeltaV;
Expand All @@ -978,7 +978,7 @@ public string StageDeltaVAtmosphereAndVac()
public float StageTimeLeftFullThrottle()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();

if (stats.VacStats.Count == 0 || stats.AtmoStats.Count == 0) return 0;

Expand Down Expand Up @@ -1012,23 +1012,23 @@ public float StageTimeLeftHover()
public double TotalDeltaVVaccum()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();
return stats.VacStats.Sum(s => s.DeltaV);
}

[ValueInfoItem("#MechJeb_TotalDV_atmo", InfoItem.Category.Vessel, format = "F0", units = "m/s", showInEditor = true)] //Total ΔV (atmo)
public double TotalDeltaVAtmosphere()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();
return stats.AtmoStats.Sum(s => s.DeltaV);
}

[ValueInfoItem("#MechJeb_TotalDV_atmo_vac", InfoItem.Category.Vessel, units = "m/s", showInEditor = true)] //Total ΔV (atmo, vac)
public string TotalDeltaVAtmosphereAndVac()
{
MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();

double atmDv = stats.AtmoStats.Sum(s => s.DeltaV);
double vacDv = stats.VacStats.Sum(s => s.DeltaV);
Expand Down
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModuleNodeExecutor.cs
Expand Up @@ -352,7 +352,7 @@ private double BurnTime(double dv, out double halfBurnTime, out double spoolupTi
// burnTime = dv / vesselState.limitedMaxThrustAccel;

MechJebModuleStageStats stats = Core.GetComputerModule<MechJebModuleStageStats>();
stats.RequestUpdate(this);
stats.RequestUpdate();

double lastStageBurnTime = 0;
for (int mjPhase = stats.VacStats.Count - 1; mjPhase >= 0 && dvLeft > 0; mjPhase--)
Expand Down
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModulePVGGlueBall.cs
Expand Up @@ -55,7 +55,7 @@ protected override void OnModuleDisabled()

public override void OnFixedUpdate()
{
Core.StageStats.RequestUpdate(this);
Core.StageStats.RequestUpdate();
}

public override void OnStart(PartModule.StartState state)
Expand Down

0 comments on commit ec3be1b

Please sign in to comment.