Skip to content

Commit

Permalink
Conversation and eventing fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
csinkers committed Nov 2, 2024
1 parent b39fe35 commit 4a3981c
Show file tree
Hide file tree
Showing 39 changed files with 145 additions and 81 deletions.
4 changes: 2 additions & 2 deletions src/Api/Eventing/AdHocComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ sealed class Helper : IAdHocComponentHelper
public T Resolve<T>() => _this.Resolve<T>();
public T TryResolve<T>() => _this.TryResolve<T>();
public void Raise<T>(T e) where T : IEvent => _this.Raise(e);
public AlbionTask RaiseAsync<T>(T e) where T : IEvent => _this.RaiseAsync(e);
public AlbionTask<TResult> RaiseQueryAsync<TResult>(IQueryEvent<TResult> e) => _this.RaiseQueryAsync(e);
public AlbionTask RaiseAsync<T>(T e) where T : IEvent => _this.RaiseA(e);
public AlbionTask<TResult> RaiseQueryAsync<TResult>(IQueryEvent<TResult> e) => _this.RaiseQueryA(e);
public void Enqueue(IEvent e) => _this.Enqueue(e);
public void Distribute<T>(ICancellableEvent e, List<T> targets, Func<T, IComponent> projection) => _this.Distribute(e, targets, projection);
public void On<T>(Action<T> callback) where T : IEvent => _this.On(callback);
Expand Down
4 changes: 2 additions & 2 deletions src/Api/Eventing/AlbionTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace UAlbion.Api.Eventing;
[AsyncMethodBuilder(typeof(AlbionTaskBuilder))]
public readonly struct AlbionTask : INotifyCompletion, IEquatable<AlbionTask>
{
public static AlbionTask Complete { get; } = new(null);
public static AlbionTask CompletedTask { get; } = new(null);
public static AlbionTask<Unit> Unit { get; } = new(Api.Unit.V);
public static AlbionTask<bool> True { get; } = new(true);
public static AlbionTask<bool> False { get; } = new(false);
Expand Down Expand Up @@ -69,7 +69,7 @@ public void GetResult()
/// <summary>
/// Create a completed task
/// </summary>
public AlbionTask(T value)
internal AlbionTask(T value)
{
_core = null;
_result = value;
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Eventing/AlbionTaskBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ enum BuilderState
/// <summary>Gets the value task for this builder.</summary>
public AlbionTask Task => _state switch
{
BuilderState.Complete => AlbionTask.Complete,
BuilderState.Complete => AlbionTask.CompletedTask,
BuilderState.Pending => new AlbionTask(_core),
_ => throw new InvalidOperationException("Tried to get Task, but it hasn't been created")
};
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Eventing/AlbionTaskBuilder_T.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ enum BuilderState
/// <summary>Gets the value task for this builder.</summary>
public AlbionTask<TResult> Task => _state switch
{
BuilderState.Complete => new AlbionTask<TResult>(_result),
BuilderState.Complete => AlbionTask.FromResult(_result),
BuilderState.Pending => new AlbionTask<TResult>(_core!),
_ => throw new InvalidOperationException("Tried to get Task, but it hasn't been created")
};
Expand Down
7 changes: 7 additions & 0 deletions src/Api/Eventing/AlbionTaskCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public interface IAlbionTaskCore : ICriticalNotifyCompletion
#if DEBUG
int Id { get; }
string? Description { get; set; }
IAlbionTaskCore? Parent { get; }
#endif
bool IsCompleted { get; }
}
Expand All @@ -32,6 +33,7 @@ enum TaskStatus
[DiagEdit]
public bool BreakOnCompletion { get; set; }
public string? Description { get; set; }
public IAlbionTaskCore? Parent { get; }
#endif

#if RECORD_TASK_STACKS
Expand All @@ -56,6 +58,7 @@ public AlbionTaskCore(string? description)
#if DEBUG
Id = Tasks.GetNextId();
Description = description;
Parent = Tasks.Current;
Tasks.AddTask(this);
#endif

Expand Down Expand Up @@ -125,11 +128,14 @@ public void SetResult(T value)
{
_result = value;
IsCompleted = true;

#if DEBUG
if (BreakOnCompletion)
Debugger.Break();

_status = TaskStatus.Completing;
var previous = Tasks.Current;
Tasks.Current = this;
#endif

switch (_continuation)
Expand All @@ -149,6 +155,7 @@ public void SetResult(T value)
#if DEBUG
_status = TaskStatus.Completed;
Tasks.RemoveTask(this);
Tasks.Current = previous;
#endif
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Api/Eventing/Component.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public abstract class Component : IComponent
/// </summary>
/// <param name="e">The event to raise</param>
/// <returns>The number of async handlers which have either already called the continuation or intend to call it in the future.</returns>
protected AlbionTask RaiseAsync<T>(T e) where T : IEvent => Exchange.RaiseA(e, this);
protected AlbionTask RaiseA<T>(T e) where T : IEvent => Exchange.RaiseA(e, this);

/// <summary>
/// Raise an event via the currently subscribed event exchange (if subscribed), and
Expand All @@ -114,7 +114,7 @@ public abstract class Component : IComponent
/// <typeparam name="T">The return value that async handlers should supply upon completion.</typeparam>
/// <param name="e">The event to raise</param>
/// <returns>The number of async handlers which have either already called the continuation or intend to call it in the future.</returns>
protected AlbionTask<T> RaiseQueryAsync<T>(IQueryEvent<T> e) => Exchange.RaiseQueryA(e, this);
protected AlbionTask<T> RaiseQueryA<T>(IQueryEvent<T> e) => Exchange.RaiseQueryA(e, this);

/// <summary>
/// Enqueue an event with the currently subscribed event exchange to be raised
Expand Down
7 changes: 4 additions & 3 deletions src/Api/Eventing/EventExchange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ static AlbionTask<int> RaiseInvoker(List<Handler> handlers, IEvent e, object sen
}
}

return new(0);
return AlbionTask.FromResult(0);
}

// [DebuggerHidden, StackTraceHidden]
Expand Down Expand Up @@ -178,9 +178,10 @@ static AlbionTask<T> RaiseQueryInvoker<T>(List<Handler> handlers, IQueryEvent<T>
}
}

if (!hasResult) throw new InvalidOperationException("No result found for RaiseQuery call");
if (!hasResult)
throw new InvalidOperationException("No result found for RaiseQuery call");

return new(result);
return AlbionTask.FromResult(result);
}

// [DebuggerHidden, StackTraceHidden]
Expand Down
8 changes: 4 additions & 4 deletions src/Api/Eventing/Handler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public SyncHandler(Action<TEvent> callback, IComponent component, bool isPostHan
[DebuggerHidden, StackTraceHidden] public AlbionTask InvokeAsAsync(IEvent e)
{
Callback((TEvent)e);
return AlbionTask.Complete;
return AlbionTask.CompletedTask;
}

public override string ToString() => $"H<{Component.GetType().Name}, {Type.Name}>";
Expand All @@ -52,14 +52,14 @@ public SyncQueryHandler(Func<TEvent, TResult> callback, IComponent component, bo
[DebuggerHidden, StackTraceHidden] AlbionTask IAsyncHandler.InvokeAsAsync(IEvent e) // Ignores result
{
Callback((TEvent)e);
return AlbionTask.Complete;
return AlbionTask.CompletedTask;
}

[DebuggerHidden, StackTraceHidden] public TResult Invoke(IQueryEvent<TResult> e) => Callback((TEvent)e);
[DebuggerHidden, StackTraceHidden] public AlbionTask<TResult> InvokeAsAsync(IQueryEvent<TResult> e)
{
var result = Callback((TEvent)e);
return new AlbionTask<TResult>(result);
return AlbionTask.FromResult(result);
}

public override string ToString() => $"HQ<{Component.GetType().Name}, {Type.Name}>";
Expand All @@ -75,7 +75,7 @@ public ReceiveOnlyHandler(Action<TEvent> callback, IComponent component)
[DebuggerHidden, StackTraceHidden] public AlbionTask InvokeAsAsync(IEvent e)
{
Callback((TEvent)e);
return AlbionTask.Complete;
return AlbionTask.CompletedTask;
}

public override string ToString() => $"HR<{Component.GetType().Name}, {Type.Name}>";
Expand Down
7 changes: 7 additions & 0 deletions src/Api/Eventing/Tasks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ public static class Tasks
static int _nextId;
static readonly object SyncRoot = new();
static readonly List<IAlbionTaskCore> Pending = new(); // Just for debugging
static readonly ThreadLocal<IAlbionTaskCore?> CurrentTask = new();

public static IAlbionTaskCore? Current
{
get => CurrentTask.Value;
set => CurrentTask.Value = value;
}

public static int GetNextId() => Interlocked.Increment(ref _nextId);
public static void AddTask(IAlbionTaskCore task)
Expand Down
33 changes: 28 additions & 5 deletions src/Game.Veldrid/Diag/CodeWindow.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using ImGuiColorTextEditNet;
using System;
using ImGuiColorTextEditNet;
using ImGuiNET;
using UAlbion.Api.Eventing;
using UAlbion.Core.Veldrid;
using UAlbion.Formats;
using UAlbion.Formats.MapEvents;
Expand Down Expand Up @@ -27,12 +29,12 @@ namespace UAlbion.Game.Veldrid.Diag;
*/

public class CodeWindow : GameComponent, IImGuiWindow
public class ScriptWindow : GameComponent, IImGuiWindow
{
readonly TextEditor _editor;
public string Name { get; }

public CodeWindow(string name)
public ScriptWindow(string name)
{
Name = name;
_editor = new TextEditor
Expand Down Expand Up @@ -67,10 +69,31 @@ void DrawContext(EventContext context)
{
var eventFormatter = new EventFormatter(Assets.LoadStringSafe, context.EventSet.StringSetId);
set.Decompiled = eventFormatter.Decompile(set.Events, set.Chains, set.ExtraEntryPoints);
var code = set.Decompiled.Script;
_editor.AllText = code;
var code = set.Decompiled.Script.AsSpan();
_editor.AllText = "";

foreach (var part in set.Decompiled.Parts)
{
PaletteIndex color = part.Type switch
{
ScriptPartType.Text => PaletteIndex.Default,
ScriptPartType.Keyword => PaletteIndex.Keyword,
ScriptPartType.EventName => PaletteIndex.KnownIdentifier,
ScriptPartType.Identifier => PaletteIndex.Identifier,
ScriptPartType.Number => PaletteIndex.Number,
ScriptPartType.Operator => PaletteIndex.Punctuation,
ScriptPartType.Label => PaletteIndex.Identifier,
ScriptPartType.StringConstant => PaletteIndex.String,
ScriptPartType.Comment => PaletteIndex.Comment,
ScriptPartType.Error => PaletteIndex.ErrorMarker,
_ => PaletteIndex.Default
};

_editor.Append(code[part.Range.Start..part.Range.End], color);
}
// TODO: Add breakpoints
}
// _editor.Selection.HighlightedLine =

_editor.Render("Script");
}
Expand Down
7 changes: 4 additions & 3 deletions src/Game.Veldrid/Diag/ThreadsWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ public class ThreadsWindow : Component, IImGuiWindow
{
readonly StringCache<int> _stringCache = new();

int _currentContextIndex;
string[] _contextNames = [];

public string Name { get; }
Expand All @@ -30,9 +29,11 @@ public void Draw()
for (int i = 0; i < _contextNames.Length; i++)
_contextNames[i] = chainManager.Contexts[i].ToString();

ImGui.ListBox("Active Contexts", ref _currentContextIndex, _contextNames, _contextNames.Length);
int currentContextIndex = chainManager.CurrentDebugContextIndex;
if (ImGui.ListBox("Active Contexts", ref currentContextIndex, _contextNames, _contextNames.Length))
chainManager.CurrentDebugContextIndex = currentContextIndex;

#if DEBUG
#if DEBUG
ImGui.Text("Pending Async Tasks:");
Tasks.EnumeratePendingTasks(_stringCache, static (stringCache, core) =>
{
Expand Down
2 changes: 1 addition & 1 deletion src/Game.Veldrid/UAlbion.Game.Veldrid.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
</ItemGroup>

<ItemGroup Condition="!Exists('..\..\deps\ImGuiColorTextEditNet\')">
<PackageReference Include="ImGuiColorTextEditNet" Version="0.1.3" />
<PackageReference Include="ImGuiColorTextEditNet" Version="0.1.7" />
</ItemGroup>
<ItemGroup Condition="Exists('..\..\deps\ImGuiColorTextEditNet\')">
<ProjectReference Include="..\..\deps\ImGuiColorTextEditNet\src\TextEdit\ImGuiColorTextEditNet.csproj" />
Expand Down
2 changes: 1 addition & 1 deletion src/Game/Combat/Battle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public Battle(MonsterGroupId groupId, SpriteId backgroundId)
});
}

AlbionTask BeginRoundAsync(BeginCombatRoundEvent _) => RaiseAsync(new CombatUpdateEvent(25)); // TODO
AlbionTask BeginRoundAsync(BeginCombatRoundEvent _) => RaiseA(new CombatUpdateEvent(25)); // TODO

protected override void Subscribed()
{
Expand Down
6 changes: 3 additions & 3 deletions src/Game/Combat/CombatClock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ public CombatClock()

OnAsync<CombatUpdateEvent>(e =>
{
if (IsRunning) { Warn($"Ignoring {e} - clock paused"); return AlbionTask.Complete; }
if (_currentUpdate != null) { Warn($"Ignoring {e} - already running another update event"); return AlbionTask.Complete; }
if (IsRunning) { Warn($"Ignoring {e} - clock paused"); return AlbionTask.CompletedTask; }
if (_currentUpdate != null) { Warn($"Ignoring {e} - already running another update event"); return AlbionTask.CompletedTask; }

GameTrace.Log.CombatClockUpdating(e.Cycles);
_currentUpdate = new AlbionTaskCore("CombatClock.CombatUpdateEvent");
Expand Down Expand Up @@ -119,4 +119,4 @@ void RaiseTick()
currentUpdate.Complete();
}
}
}
}
2 changes: 1 addition & 1 deletion src/Game/Entities/ItemTransitionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ AlbionTask LinearFromTilePosition(int x, int y, ItemId itemId, float? transition
var map = TryResolve<IMapManager>()?.Current;

if (scene == null || map == null)
return AlbionTask.Complete;
return AlbionTask.CompletedTask;

var worldPosition = new Vector3(x, y, 0) * map.TileSize;
var normPosition = sceneManager.Camera.ProjectWorldToNorm(worldPosition);
Expand Down
2 changes: 1 addition & 1 deletion src/Game/Entities/Map2D/FlatMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ async AlbionTask FireEventChains(TriggerType type, bool log)

foreach (var zone in zones)
{
await RaiseAsync(
await RaiseA(
new TriggerChainEvent(
_logicalMap.EventSet,
zone.EventIndex,
Expand Down
13 changes: 9 additions & 4 deletions src/Game/EventChainManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ public sealed class EventChainManager : ServiceComponent<IEventManager>, IEventM

readonly List<EventContext> _contexts = new();
readonly List<Breakpoint> _breakpoints = new();
public EventContext CurrentDebugContext { get; }
public int CurrentDebugContextIndex { get; set; } = -1;
public EventContext CurrentDebugContext =>
CurrentDebugContextIndex >= 0 && CurrentDebugContextIndex < _contexts.Count
? _contexts[CurrentDebugContextIndex]
: null;

public IReadOnlyList<EventContext> Contexts => _contexts;
public IReadOnlyList<Breakpoint> Breakpoints => _breakpoints;

Expand Down Expand Up @@ -51,7 +56,7 @@ AlbionTask Trigger(TriggerChainEvent e)
var game = Resolve<IGameState>();
if (e.EventSet.Id.Type == AssetType.Map && game.IsChainDisabled(e.EventSet.Id, e.EventSet.GetChainForEvent(e.EntryPoint)))
{
return AlbionTask.Complete;
return AlbionTask.CompletedTask;
}

var isClockRunning = Resolve<IClock>().IsRunning;
Expand Down Expand Up @@ -151,7 +156,7 @@ async AlbionTask HandleAsyncEvent(EventContext context, IEvent asyncEvent)
{
context.Status = EventContextStatus.Waiting;

var task = RaiseAsync(asyncEvent);
var task = RaiseA(asyncEvent);
#if DEBUG
_ = task.Named($"ECM.HandleAsyncEvent for C{context.Id} {context.EventSet.Id}:{context.Node.Id}: {context.Node.Event}");
#endif
Expand All @@ -164,7 +169,7 @@ async AlbionTask HandleAsyncEvent(EventContext context, IEvent asyncEvent)
async AlbionTask<bool> HandleBoolEvent(EventContext context, IQueryEvent<bool> boolEvent, IBranchNode branch) // Return value = whether to return.
{
context.Status = EventContextStatus.Waiting;
var task = RaiseQueryAsync(boolEvent);
var task = RaiseQueryA(boolEvent);
#if DEBUG
_ = task.Named($"ECM.HandleBoolEvent for C{context.Id} {context.EventSet.Id}:{context.Node.Id}: {context.Node.Event}");
#endif
Expand Down
6 changes: 3 additions & 3 deletions src/Game/GameClock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public GameClock()

OnAsync<GameUpdateEvent>(e =>
{
if (IsRunning) { Warn($"Ignoring {e} - clock paused"); return AlbionTask.Complete; }
if (_currentUpdate != null) { Warn($"Ignoring {e} - already running another update event"); return AlbionTask.Complete; }
if (IsRunning) { Warn($"Ignoring {e} - clock paused"); return AlbionTask.CompletedTask; }
if (_currentUpdate != null) { Warn($"Ignoring {e} - already running another update event"); return AlbionTask.CompletedTask; }

GameTrace.Log.ClockUpdating(e.Cycles);
_currentUpdate = new AlbionTaskCore("GameClock.GameUpdateEvent");
Expand Down Expand Up @@ -161,4 +161,4 @@ void RaiseTick()
_currentUpdate = null;
currentUpdate.Complete();
}
}
}
Loading

0 comments on commit 4a3981c

Please sign in to comment.