Skip to content

Commit

Permalink
Make warp functions async (addresses #130)
Browse files Browse the repository at this point in the history
  • Loading branch information
untoldwind committed Mar 2, 2024
1 parent 104adcf commit 7d1d0e7
Show file tree
Hide file tree
Showing 11 changed files with 160 additions and 50 deletions.
5 changes: 5 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
* Add propellant information to engine via `engine.current_propellant` and `engine.propellants`
* Extend `ResourceDefinition` by `is_recipe` and `recipe_ingredients`
* Add `engine.thrust_limiter` property
* Add `part.is_cargo_bay`
* Add `engine.has_fairing` and `engine.fairing` to access engine specific fairings
* `part.fairing` will now only cover non-engine parts
* Add `set_time_warp_index(int)`, `max_warp_index()`, `is_warping()` and `is_physics_time_warp()` to `ksp::game::warp`
* `warp_to(float)` and `set_time_warp_index(int)` can not be used in a sync function

## 0.5.3.3 -> 0.5.3.4

Expand Down
12 changes: 6 additions & 6 deletions KSP2Runtime/Core/DelayedAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
namespace KontrolSystem.KSP.Runtime.Core;

public class DelayedAction<T> : Future<T> {
private readonly Action action;
private readonly Func<T> action;
private readonly IKSPContext context;
private readonly T result;
private int delay;
private int retries;
private T defaultResult;

public DelayedAction(IKSPContext context, T result, int delay, int retries, Action action) {
public DelayedAction(IKSPContext context, int delay, int retries, Func<T> action, T defaultResult) {
this.context = context;
this.result = result;
this.action = action;
this.delay = delay;
this.retries = retries;
this.defaultResult = defaultResult;
}

public override FutureResult<T> PollValue() {
Expand All @@ -27,7 +27,7 @@ public override FutureResult<T> PollValue() {
}

try {
action.Invoke();
return new FutureResult<T>(action.Invoke());
} catch {
if (retries > 0) {
retries--;
Expand All @@ -36,6 +36,6 @@ public override FutureResult<T> PollValue() {
}
}

return new FutureResult<T>(result);
return new FutureResult<T>(defaultResult);
}
}
7 changes: 0 additions & 7 deletions KSP2Runtime/Core/KSPContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,6 @@ public void CheckTimeout() {
}

public void ResetTimeout() {
if (OnNextYieldOnce != null) {
OnNextYieldOnce();
OnNextYieldOnce = null;
}

timeStopwatch.Reset();
timeStopwatch.Start();
}
Expand Down Expand Up @@ -153,8 +148,6 @@ public object? NextYield {
set => nextYield = value;
}

public Action? OnNextYieldOnce { get; set; }

public void AddMarker(IMarker marker) {
markers.Add(marker);
}
Expand Down
2 changes: 0 additions & 2 deletions KSP2Runtime/IKSPContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@ public interface IKSPContext : IContext {

object? NextYield { get; set; }

Action? OnNextYieldOnce { get; set; }

OptionalAddons OptionalAddons { get; }

KSPOrbitModule.IBody? FindBody(string name);
Expand Down
10 changes: 6 additions & 4 deletions KSP2Runtime/KSPControl/KSPControlModule.BaseAutopilot.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using KontrolSystem.TO2.Binding;
using KontrolSystem.KSP.Runtime.Core;
using KontrolSystem.TO2.Binding;
using KontrolSystem.TO2.Runtime;
using KSP.Sim.impl;
using KSP.Sim.State;
Expand Down Expand Up @@ -26,9 +27,10 @@ protected BaseAutopilot(IKSPContext context, VesselComponent vessel) {
[KSMethod]
public Future<object?> Release() {
suspended = true;
context.NextYield = new WaitForFixedUpdate();
context.OnNextYieldOnce = () => { context.UnhookAutopilot(vessel, this); };
return new Future.Success<object?>(null);
return new DelayedAction<object?>(context, 1, 0, () => {
context.UnhookAutopilot(vessel, this);
return null;
}, null);
}

[KSMethod]
Expand Down
40 changes: 16 additions & 24 deletions KSP2Runtime/KSPGame/KSPGameWarpModule.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using KontrolSystem.TO2.Binding;
using KontrolSystem.KSP.Runtime.Core;
using KontrolSystem.TO2.Binding;
using KontrolSystem.TO2.Runtime;
using KSP.Sim.impl;
using UnityEngine;

namespace KontrolSystem.KSP.Runtime.KSPGame;

Expand All @@ -11,42 +12,33 @@ public class KSPGameWarpModule {
private static TimeWarp TimeWarp => KSPContext.CurrentContext.Game.ViewController.TimeWarp;

[KSFunction(Description = "Get the current warp index. Actual factor depends on warp mode.")]
public static long CurrentIndex() {
return TimeWarp.CurrentRateIndex;
}
public static long CurrentIndex() => TimeWarp.CurrentRateIndex;

[KSFunction(Description = "Get the current warp rate (i.e. actual time multiplier).")]
public static double CurrentRate() {
return TimeWarp.CurrentRate;
}
public static double CurrentRate() => TimeWarp.CurrentRate;

[KSFunction(Description = "Warp forward to a specific universal time.")]
public static void WarpTo(double ut) {
public static Future<object?> WarpTo(double ut) => new DelayedAction<object?>(KSPContext.CurrentContext, 1, 0, () => {
TimeWarp.WarpTo(ut);
}
return null;
}, null);

[KSFunction(Description = "Cancel time warp")]
public static void Cancel() {
public static Future<object?> Cancel() => new DelayedAction<object?>(KSPContext.CurrentContext, 1, 0, () => {
TimeWarp.StopTimeWarp();
}
return null;
}, null);

[KSFunction(Description = "Get current maximum allowed time warp index.")]
public static long MaxWarpIndex() {
return TimeWarp.GetMaxRateIndex(false, out _);
}
public static long MaxWarpIndex() => TimeWarp.GetMaxRateIndex(false, out _);

[KSFunction(Description = "Set the current time warp index.")]
public static bool SetTimeWrapIndex(long index) {
return TimeWarp.SetRateIndex((int)index, true);
}
public static Future<bool> SetTimeWrapIndex(long index) => new DelayedAction<bool>(KSPContext.CurrentContext, 1, 0,
() => TimeWarp.SetRateIndex((int)index, true), false);

[KSFunction(Description = "Check if time warp is currently active")]
public static bool IsWarping() {
return TimeWarp.IsWarping;
}
public static bool IsWarping() => TimeWarp.IsWarping;

[KSFunction(Description = "Check if time warp is still in physics mode")]
public static bool IsPhysicsTimeWarp() {
return TimeWarp.IsPhysicsTimeWarp;
}
public static bool IsPhysicsTimeWarp() => TimeWarp.IsPhysicsTimeWarp;
}
14 changes: 10 additions & 4 deletions KSP2Runtime/KSPVessel/KSPVesselModule.Maneuver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,12 @@ public Future<Result<ManeuverNodeAdapter, string>>
var result =
Result.Ok<ManeuverNodeAdapter, string>(new ManeuverNodeAdapter(vesselAdapter, maneuverNodeData));
if (KSPContext.CurrentContext.Game.Map.TryGetMapCore(out var mapCore))
return new DelayedAction<Result<ManeuverNodeAdapter, string>>(KSPContext.CurrentContext, result, 1,
return new DelayedAction<Result<ManeuverNodeAdapter, string>>(KSPContext.CurrentContext, 1,
2,
() => { mapCore.map3D.ManeuverManager.CreateGizmoForLocation(maneuverNodeData); });
() => {
mapCore.map3D.ManeuverManager.CreateGizmoForLocation(maneuverNodeData);
return result;
}, result);
return new Future.Success<Result<ManeuverNodeAdapter, string>>(result);
}

Expand Down Expand Up @@ -111,9 +114,12 @@ public Future<Result<ManeuverNodeAdapter, string>> AddBurnVector(double ut, Vect
var result =
Result.Ok<ManeuverNodeAdapter, string>(new ManeuverNodeAdapter(vesselAdapter, maneuverNodeData));
if (KSPContext.CurrentContext.Game.Map.TryGetMapCore(out var mapCore))
return new DelayedAction<Result<ManeuverNodeAdapter, string>>(KSPContext.CurrentContext, result, 1,
return new DelayedAction<Result<ManeuverNodeAdapter, string>>(KSPContext.CurrentContext, 1,
2,
() => { mapCore.map3D.ManeuverManager.CreateGizmoForLocation(maneuverNodeData); });
() => {
mapCore.map3D.ManeuverManager.CreateGizmoForLocation(maneuverNodeData);
return result;
}, result);
return new Future.Success<Result<ManeuverNodeAdapter, string>>(result);
}
}
Expand Down
2 changes: 0 additions & 2 deletions KSP2Runtime/Testing/KSPTestRunnerContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ public class KSPTestRunnerContext : TestRunnerContext, IKSPContext {

public object? NextYield { get; set; }

public Action? OnNextYieldOnce { get; set; }

public void AddMarker(IMarker marker) {
}

Expand Down
72 changes: 72 additions & 0 deletions Tools/vscode/to2-syntax/server/src/reference/reference.json
Original file line number Diff line number Diff line change
Expand Up @@ -7734,6 +7734,56 @@
"kind": "Builtin",
"name": "Unit"
}
},
"max_warp_index": {
"isAsync": false,
"name": "max_warp_index",
"description": "Get current maximum allowed time warp index.\n",
"parameters": [],
"returnType": {
"kind": "Builtin",
"name": "int"
}
},
"set_time_wrap_index": {
"isAsync": false,
"name": "set_time_wrap_index",
"description": "Set the current time warp index.\n",
"parameters": [
{
"name": "index",
"type": {
"kind": "Builtin",
"name": "int"
},
"hasDefault": false,
"description": null
}
],
"returnType": {
"kind": "Builtin",
"name": "bool"
}
},
"is_warping": {
"isAsync": false,
"name": "is_warping",
"description": "Check if time warp is currently active\n",
"parameters": [],
"returnType": {
"kind": "Builtin",
"name": "bool"
}
},
"is_physics_time_warp": {
"isAsync": false,
"name": "is_physics_time_warp",
"description": "Check if time warp is still in physics mode\n",
"parameters": [],
"returnType": {
"kind": "Builtin",
"name": "bool"
}
}
}
},
Expand Down Expand Up @@ -37854,6 +37904,28 @@
]
}
},
"has_fairing": {
"name": "has_fairing",
"readOnly": true,
"type": {
"kind": "Builtin",
"name": "bool"
}
},
"fairing": {
"name": "fairing",
"readOnly": true,
"type": {
"kind": "Option",
"parameters": [
{
"kind": "Standard",
"module": "ksp::vessel",
"name": "ModuleFairing"
}
]
}
},
"is_shutdown": {
"name": "is_shutdown",
"readOnly": true,
Expand Down
44 changes: 43 additions & 1 deletion docs/reference/ksp/game_warp.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,52 @@ pub sync fn current_rate ( ) -> float
Get the current warp rate (i.e. actual time multiplier).


### is_physics_time_warp

```rust
pub sync fn is_physics_time_warp ( ) -> bool
```

Check if time warp is still in physics mode


### is_warping

```rust
pub sync fn is_warping ( ) -> bool
```

Check if time warp is currently active


### max_warp_index

```rust
pub sync fn max_warp_index ( ) -> int
```

Get current maximum allowed time warp index.


### set_time_wrap_index

```rust
pub sync fn set_time_wrap_index ( index : int ) -> bool
```

Set the current time warp index.


Parameters

Name | Type | Optional | Description
--- | --- | --- | ---
index | int | |

### warp_to

```rust
pub sync fn warp_to ( ut : float ) -> Unit
pub fn warp_to ( ut : float ) -> Unit
```

Warp forward to a specific universal time.
Expand Down
2 changes: 2 additions & 0 deletions docs/reference/ksp/vessel.md
Original file line number Diff line number Diff line change
Expand Up @@ -764,8 +764,10 @@ current_propellant | [ksp::resource::ResourceDefinition](/reference/ksp/resource
current_throttle | float | R/O |
current_thrust | float | R/O |
engine_modes | [ksp::vessel::EngineMode](/reference/ksp/vessel.md#enginemode)[] | R/O |
fairing | Option&lt;[ksp::vessel::ModuleFairing](/reference/ksp/vessel.md#modulefairing)> | R/O |
gimbal | Option&lt;[ksp::vessel::ModuleGimbal](/reference/ksp/vessel.md#modulegimbal)> | R/O |
global_thrust_direction | [ksp::math::GlobalVector](/reference/ksp/math.md#globalvector) | R/O | Coordinate independent direction of thrust.
has_fairing | bool | R/O |
has_ignited | bool | R/O |
independent_throttle | float | R/W |
independent_throttle_enabled | bool | R/W |
Expand Down

0 comments on commit 7d1d0e7

Please sign in to comment.