Snapshot for release 2026.10.13.1 (internal d2b5fb3)
This commit is contained in:
parent
fe1eca0ca7
commit
319740ff5d
291 changed files with 58505 additions and 2107 deletions
55
Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs
Normal file
55
Plugins/RynthCore.Plugin.RynthThreads/PluginExports.cs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore.PluginCore;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads;
|
||||
|
||||
/// <summary>
|
||||
/// C ABI exports. Nothing may throw out of an [UnmanagedCallersOnly] method (it would take
|
||||
/// acclient.exe down): every export goes through RynthPluginRuntime, which catches and logs.
|
||||
/// The window goes through the engine's script windows (host calls from the plugin's own tick),
|
||||
/// so there is no render callback.
|
||||
/// </summary>
|
||||
public static unsafe class PluginExports
|
||||
{
|
||||
private static readonly RynthPluginRuntime<RynthThreadsPlugin> Runtime = new();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Shutdown() => Runtime.Shutdown();
|
||||
|
||||
// UTF-8 literals live in the module's read-only data: nothing to allocate or free.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetName() => LiteralPointer("RynthThreads"u8);
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static IntPtr GetVersion() => LiteralPointer("0.1.0"u8);
|
||||
|
||||
private static IntPtr LiteralPointer(ReadOnlySpan<byte> literal)
|
||||
{
|
||||
fixed (byte* p = literal)
|
||||
return (IntPtr)p;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void Tick() => Runtime.OnTick();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLoginComplete() => Runtime.OnLoginComplete();
|
||||
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnLogout() => Runtime.OnLogout();
|
||||
|
||||
// The Fragment Press lines (read only; nothing is eaten).
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag)
|
||||
=> Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
|
||||
|
||||
// "/rthreads ..." commands.
|
||||
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
RynthThreads: DreamWeave's "Threads" gem crafting. Records every Fragment Press result from chat
|
||||
(Threads/PressParser.cs) into one file shared by all characters and clients on the PC
|
||||
(%LOCALAPPDATA%\RynthCore\RynthThreads\presses.jsonl, Threads/PressStore.cs) and shows the odds
|
||||
of each modifier per component (Threads/PressInference.cs). Active only on DreamWeave (world name
|
||||
contains "DreamWeave"); elsewhere it stays idle. UI: the engine's script windows (ImGui), a bar
|
||||
button and /rthreads; Ui/ is RynthSort's script-window recorder.
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
|
||||
<OutputType>Library</OutputType>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<Nullable>enable</Nullable>
|
||||
<PublishAot>true</PublishAot>
|
||||
<NativeLib>Shared</NativeLib>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
|
||||
<StripSymbols>false</StripSymbols>
|
||||
<RootNamespace>RynthCore.Plugin.RynthThreads</RootNamespace>
|
||||
<AssemblyName>RynthCore.Plugin.RynthThreads</AssemblyName>
|
||||
<Platforms>x86</Platforms>
|
||||
<!-- Plugin manifest (embedded in the DLL; Plugins\Directory.Build.targets). minEngineApi is the
|
||||
highest API use NOT behind a Has*/version check. Nothing above the v66 baseline: the world
|
||||
and character names are behind HasGetWorldName / HasGetObjectName, the window behind HasUi
|
||||
(script windows, v71). Below v71 it still records (/rthreads stats|export). -->
|
||||
<RynthPluginMinEngineApi>66</RynthPluginMinEngineApi>
|
||||
<RynthPluginDescription>DreamWeave only: records Fragment Press results and shows the odds of each modifier per component.</RynthPluginDescription>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
|
||||
<ProjectReference Include="..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
334
Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs
Normal file
334
Plugins/RynthCore.Plugin.RynthThreads/RynthThreadsPlugin.cs
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
// RynthThreadsPlugin.cs - DreamWeave's "Threads" gem crafting: records every Fragment Press result
|
||||
// from chat and shows the odds of each modifier with each component (DreamWeave components give a
|
||||
// chance of each modifier, not a fixed one).
|
||||
//
|
||||
// Active only on DreamWeave (the world name contains "DreamWeave"); anywhere else it reads nothing,
|
||||
// shows no window and only answers /rthreads to say so. Presses go to one file shared by every
|
||||
// character and client on the PC (Threads/PressStore.cs); the window shows what the inference
|
||||
// (Threads/PressInference.cs) makes of all of them.
|
||||
//
|
||||
// Threads: OnTick, OnChatWindowText and login/logout run on the plugin pump. OnChatBarEnter may run
|
||||
// on AC's main thread, so it only queues the command.
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using RynthCore.Plugin.RynthThreads.Threads;
|
||||
using RynthCore.Plugin.RynthThreads.Ui;
|
||||
using RynthCore.Plugin.RynthThreads.Views;
|
||||
using RynthCore.PluginCore;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads;
|
||||
|
||||
public sealed class RynthThreadsPlugin : RynthPluginBase
|
||||
{
|
||||
public const string Version = "0.1.0";
|
||||
private const string Command = "/rthreads";
|
||||
private const long IdentityRetryMs = 1_000;
|
||||
/// <summary>Wait this long after login for the character's name before recording without it.</summary>
|
||||
private const long NameWaitMs = 30_000;
|
||||
/// <summary>How often the shared file is checked for other clients' presses.</summary>
|
||||
private const long PollMs = 2_000;
|
||||
private const long PassIntervalMs = 5_000;
|
||||
|
||||
private readonly PressParser _parser = new();
|
||||
private readonly UiHost _ui = new();
|
||||
private readonly ConcurrentQueue<string> _commands = new();
|
||||
private PressStore? _store;
|
||||
private UiWindow? _window;
|
||||
private ThreadsPanel? _panel;
|
||||
private ThreadsReport? _report;
|
||||
private int _reportVersion = -1;
|
||||
|
||||
private bool _inWorld;
|
||||
private bool _checked; // the world is known (DreamWeave or not)
|
||||
private bool _active; // on DreamWeave: reading chat, showing the window
|
||||
private long _loginAtMs;
|
||||
private long _nextIdentityTryMs;
|
||||
private long _nextPollMs;
|
||||
private string _world = string.Empty;
|
||||
private string _character = string.Empty;
|
||||
private bool _noUiLogged;
|
||||
|
||||
public override int Initialize()
|
||||
{
|
||||
_ui.Log = msg => Host.Log(msg);
|
||||
_panel = new ThreadsPanel
|
||||
{
|
||||
Report = CurrentReport,
|
||||
Presses = () => _store?.Presses ?? (IReadOnlyList<Press>)Array.Empty<Press>(),
|
||||
Export = Export,
|
||||
Notice = Notice,
|
||||
};
|
||||
_window = _ui.Add(new UiWindow("RynthThreads/Main", "RynthThreads")
|
||||
{
|
||||
DefaultWidth = 440f, DefaultHeight = 480f, MinWidth = 320f, MinHeight = 220f,
|
||||
});
|
||||
Host.Log($"[RynthThreads] {Version} initialized (DreamWeave only). {Command} shows or hides the window; {Command} stats|export.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>True for DreamWeave's world name (any case, any decoration around it).</summary>
|
||||
internal static bool IsDreamWeave(string? world) =>
|
||||
!string.IsNullOrEmpty(world) && world.IndexOf("DreamWeave", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
|
||||
public override void OnLoginComplete()
|
||||
{
|
||||
_inWorld = true;
|
||||
_checked = false;
|
||||
_active = false;
|
||||
_character = string.Empty;
|
||||
_loginAtMs = Environment.TickCount64;
|
||||
_nextIdentityTryMs = _loginAtMs;
|
||||
}
|
||||
|
||||
public override void OnLogout()
|
||||
{
|
||||
SaveFinished(_parser.Flush("logout"));
|
||||
_inWorld = false;
|
||||
_checked = false;
|
||||
_active = false;
|
||||
if (_window != null) { _window.Visible = false; _window.NeedsPass = true; }
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
// Plugin unload (hot reload, update, client closing): keep a half-read press.
|
||||
public override void Shutdown()
|
||||
{
|
||||
SaveFinished(_parser.Flush("logout"));
|
||||
_store?.FlushPending();
|
||||
_ui.SubmitEmpty(Host);
|
||||
}
|
||||
|
||||
public override void OnChatWindowText(string? text, int chatType, ref int eat)
|
||||
{
|
||||
if (!_active || string.IsNullOrEmpty(text)) return;
|
||||
List<Press>? done = _parser.Feed(text, Environment.TickCount64);
|
||||
if (done == null) return;
|
||||
foreach (Press p in done) SaveFinished(p);
|
||||
}
|
||||
|
||||
// May run on AC's thread: classify and queue only.
|
||||
public override void OnChatBarEnter(string? text, ref int eat)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return;
|
||||
string t = text.Trim();
|
||||
if (!t.StartsWith(Command, StringComparison.OrdinalIgnoreCase)
|
||||
|| (t.Length > Command.Length && !char.IsWhiteSpace(t[Command.Length])))
|
||||
return;
|
||||
eat = 1;
|
||||
_commands.Enqueue(t.Substring(Command.Length).Trim());
|
||||
}
|
||||
|
||||
public override void OnTick()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
|
||||
if (_inWorld && !_checked && now >= _nextIdentityTryMs) TryIdentify(now);
|
||||
if (!_active || _store == null) return;
|
||||
|
||||
SaveFinished(_parser.Tick(now));
|
||||
if (now >= _nextPollMs)
|
||||
{
|
||||
_nextPollMs = now + PollMs;
|
||||
_store.FlushPending();
|
||||
if (_store.Poll() > 0 && _window != null) _window.NeedsPass = true;
|
||||
}
|
||||
|
||||
if (!Host.HasUi || _window == null || _panel == null) return;
|
||||
_ui.Poll(Host);
|
||||
Record(_window, now);
|
||||
_ui.Submit(Host, now);
|
||||
}
|
||||
|
||||
/// <summary>Learns the world (and the character's name) after login; starts on DreamWeave.</summary>
|
||||
private void TryIdentify(long now)
|
||||
{
|
||||
_nextIdentityTryMs = now + IdentityRetryMs;
|
||||
if (!Host.HasGetWorldName || !Host.TryGetWorldName(out string world) || string.IsNullOrWhiteSpace(world)) return;
|
||||
|
||||
uint me = Host.GetPlayerId();
|
||||
string name = string.Empty;
|
||||
bool named = me != 0 && Host.HasGetObjectName && Host.TryGetObjectName(me, out name) && !string.IsNullOrWhiteSpace(name);
|
||||
if (!named && now - _loginAtMs < NameWaitMs && IsDreamWeave(world)) return;
|
||||
|
||||
_world = world.Trim();
|
||||
_character = named ? name.Trim() : string.Empty;
|
||||
_checked = true;
|
||||
_active = IsDreamWeave(_world);
|
||||
if (!_active)
|
||||
{
|
||||
Host.Log($"[RynthThreads] {_world} isn't DreamWeave: idle.");
|
||||
return;
|
||||
}
|
||||
_store ??= new PressStore(PressStore.DefaultFolder);
|
||||
_store.Poll();
|
||||
_nextPollMs = now + PollMs;
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
Host.Log($"[RynthThreads] recording Fragment Press results for {(_character.Length > 0 ? _character : "this character")} on {_world}; "
|
||||
+ $"{_store.Presses.Count} presses so far in {_store.FilePath}");
|
||||
}
|
||||
|
||||
// ── Presses ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void SaveFinished(Press? p)
|
||||
{
|
||||
if (p == null || _store == null) return;
|
||||
p.Server = _world;
|
||||
p.Character = _character;
|
||||
string? error = _store.Record(p);
|
||||
if (_window != null) _window.NeedsPass = true;
|
||||
|
||||
string level = p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? "?";
|
||||
string what = p.Complete
|
||||
? $"{p.Modifiers.Count} modifier{(p.Modifiers.Count == 1 ? "" : "s")}"
|
||||
: "incomplete";
|
||||
Print($"Saved press {_store.Presses.Count}: {p.Fragment} (Level {level}), {p.ComponentsText} - {what}.");
|
||||
if (error != null)
|
||||
{
|
||||
Host.Log($"[RynthThreads] couldn't write {_store.FilePath} yet: {error}");
|
||||
Print("The press file is busy; it will be written in a moment.");
|
||||
}
|
||||
}
|
||||
|
||||
private ThreadsReport CurrentReport()
|
||||
{
|
||||
if (_store == null) return new ThreadsReport();
|
||||
if (_report == null || _reportVersion != _store.Version)
|
||||
{
|
||||
_report = PressInference.Build(_store.Presses);
|
||||
_reportVersion = _store.Version;
|
||||
}
|
||||
return _report;
|
||||
}
|
||||
|
||||
private string Notice()
|
||||
{
|
||||
if (_store == null) return string.Empty;
|
||||
var parts = new List<string>();
|
||||
if (_store.PendingCount > 0) parts.Add($"{_store.PendingCount} press(es) waiting to be written");
|
||||
if (_store.BadLines > 0) parts.Add($"{_store.BadLines} unreadable line(s) in the file skipped");
|
||||
return string.Join("; ", parts);
|
||||
}
|
||||
|
||||
private void Export()
|
||||
{
|
||||
if (_store == null) return;
|
||||
try
|
||||
{
|
||||
string path = _store.ExportCsv(DateTime.Now);
|
||||
Print($"Exported {_store.Presses.Count} presses to {path}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Print($"Export failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Commands ────────────────────────────────────────────────────────────
|
||||
|
||||
private void RunCommand(string arg)
|
||||
{
|
||||
string word = arg.Split(' ', StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0].ToLowerInvariant() : string.Empty;
|
||||
if (word is "help" or "?")
|
||||
{
|
||||
Print($"DreamWeave only: records Fragment Press results and shows the odds of each modifier per component. {Command} shows or hides the window; {Command} stats; {Command} export.");
|
||||
return;
|
||||
}
|
||||
if (!_inWorld) { Print("Log in first."); return; }
|
||||
if (!_checked) { Print("Still finding out which server this is; try again in a moment."); return; }
|
||||
if (!_active)
|
||||
{
|
||||
Print($"RynthThreads is for DreamWeave only (this is {_world}).");
|
||||
return;
|
||||
}
|
||||
switch (word)
|
||||
{
|
||||
case "":
|
||||
if (_window == null) return;
|
||||
_window.Visible = !_window.Visible;
|
||||
_window.NeedsPass = true;
|
||||
if (_window.Visible && !Host.HasUi && !_noUiLogged)
|
||||
{
|
||||
_noUiLogged = true;
|
||||
Print($"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Presses are still recorded: {Command} stats.");
|
||||
}
|
||||
break;
|
||||
case "stats":
|
||||
foreach (string line in StatsLines(CurrentReport(), _store!.FilePath)) Print(line);
|
||||
break;
|
||||
case "export":
|
||||
Export();
|
||||
break;
|
||||
default:
|
||||
Print($"{Command} [stats | export | help]");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The short /rthreads stats summary: totals, then one line per component (at most 6) and No
|
||||
/// components with its top 5 modifiers by rate ("Guarded 75%", "+" when more likely with it).
|
||||
/// The Affinity group is left out: every gem has one.
|
||||
/// </summary>
|
||||
internal static List<string> StatsLines(ThreadsReport r, string file)
|
||||
{
|
||||
var lines = new List<string>
|
||||
{
|
||||
$"{r.Total} press{(r.Total == 1 ? "" : "es")} ({r.Usable} complete, {r.Incomplete} incomplete) by {r.Characters} character{(r.Characters == 1 ? "" : "s")}; {r.Modifiers.Count} modifiers seen.",
|
||||
};
|
||||
var groups = new List<GroupReport>(r.Components);
|
||||
if (r.NoComponents != null) groups.Add(r.NoComponents);
|
||||
int shown = 0;
|
||||
foreach (GroupReport g in groups)
|
||||
{
|
||||
if (shown++ == 6) { lines.Add($"... and {groups.Count - 6} more (see the window)."); break; }
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(g.Name).Append(" (").Append(g.Presses).Append("): ");
|
||||
int n = 0;
|
||||
foreach (Odds o in g.Odds)
|
||||
{
|
||||
if (o.IsGroup) continue;
|
||||
if (n == 5) break;
|
||||
if (n++ > 0) sb.Append(", ");
|
||||
sb.Append(o.Modifier).Append(' ')
|
||||
.Append(Math.Round(o.Rate * 100).ToString("0", CultureInfo.InvariantCulture)).Append('%');
|
||||
if (o.MoreLikely) sb.Append('+');
|
||||
}
|
||||
lines.Add(sb.ToString());
|
||||
}
|
||||
if (groups.Any(g => g.Odds.Any(o => o.MoreLikely))) lines.Add("+ = more likely with it than without.");
|
||||
if (r.Total == 0) lines.Add("Press a Raw Fragment at a Fragment Press to start.");
|
||||
lines.Add("File: " + file);
|
||||
return lines;
|
||||
}
|
||||
|
||||
private void Print(string text)
|
||||
{
|
||||
if (!Host.HasWriteToChat || !Host.WriteToChat("[RynthThreads] " + text, 1))
|
||||
Host.Log("[RynthThreads] " + text);
|
||||
}
|
||||
|
||||
/// <summary>A pass when one is wanted, or now and then while visible.</summary>
|
||||
private void Record(UiWindow w, long now)
|
||||
{
|
||||
bool due = w.NeedsPass || (w.Visible && now >= w.NextPassMs);
|
||||
if (!due) return;
|
||||
w.NeedsPass = false;
|
||||
w.NextPassMs = now + PassIntervalMs;
|
||||
w.Begin();
|
||||
try
|
||||
{
|
||||
_panel!.Draw(w);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
w.TextWrapped($"Something went wrong drawing this window: {ex.GetType().Name}: {ex.Message}");
|
||||
Host.Log($"[RynthThreads] {w.Key} pass failed: {ex}");
|
||||
}
|
||||
w.End();
|
||||
}
|
||||
}
|
||||
110
Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs
Normal file
110
Plugins/RynthCore.Plugin.RynthThreads/Threads/Press.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>One number in a modifier's description, with the form it was written in.</summary>
|
||||
internal readonly struct ModNumber
|
||||
{
|
||||
/// <summary>"x1.38" multiplier.</summary>
|
||||
public const string Mult = "mult";
|
||||
/// <summary>"12%".</summary>
|
||||
public const string Pct = "pct";
|
||||
/// <summary>"+29" (or "-5"): a signed amount, e.g. a rating.</summary>
|
||||
public const string Plus = "plus";
|
||||
/// <summary>A plain number.</summary>
|
||||
public const string Num = "num";
|
||||
|
||||
public readonly double Value;
|
||||
public readonly string Kind;
|
||||
/// <summary>As written ("x1.38", "12%", "+29", "75").</summary>
|
||||
public readonly string Text;
|
||||
|
||||
public ModNumber(double value, string kind, string text)
|
||||
{
|
||||
Value = value;
|
||||
Kind = kind;
|
||||
Text = text;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One "Name - description" line of the gem's block.</summary>
|
||||
internal sealed class GemModifier
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public string Description = string.Empty;
|
||||
public List<ModNumber> Numbers = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One press at a Fragment Press, as the server told it in chat. Everything the server says is
|
||||
/// kept as said (numbers raw): "Level 190, 4 entries." goes into ResultLevel and Entries without
|
||||
/// guessing what entries are.
|
||||
/// </summary>
|
||||
internal sealed class Press
|
||||
{
|
||||
/// <summary>Random id, so a press read back from the shared file isn't counted twice.</summary>
|
||||
public string Id = string.Empty;
|
||||
public DateTime TimeUtc;
|
||||
public string Server = string.Empty;
|
||||
public string Character = string.Empty;
|
||||
|
||||
/// <summary>"Raw Fragment" from "Using the Raw Fragment (Level 185) with the Fragment Press".</summary>
|
||||
public string Fragment = string.Empty;
|
||||
public int? FragmentLevel;
|
||||
/// <summary>"Fragment Press".</summary>
|
||||
public string Tool = string.Empty;
|
||||
|
||||
/// <summary>The "Pressed. ..." line ("Pressed. It holds."), or "" when none came.</summary>
|
||||
public string Outcome = string.Empty;
|
||||
/// <summary>A "Components selected: ..." (or "No components ...") line came.</summary>
|
||||
public bool ComponentsSeen;
|
||||
/// <summary>Sorted, case-insensitively.</summary>
|
||||
public List<string> Components = new();
|
||||
/// <summary>The "... drawn at random." line, or "".</summary>
|
||||
public string RandomNote = string.Empty;
|
||||
public List<GemModifier> Modifiers = new();
|
||||
public int? ResultLevel;
|
||||
public int? Entries;
|
||||
|
||||
/// <summary>Ended on its "Level N, M entries." line. False: timed out, or another "Using ..." line came first.</summary>
|
||||
public bool Complete;
|
||||
/// <summary>Why it ended: "done", "timeout", "next use", "logout".</summary>
|
||||
public string End = string.Empty;
|
||||
|
||||
/// <summary>The press's own lines, in order.</summary>
|
||||
public List<string> Raw = new();
|
||||
/// <summary>Lines that came while the press was open but didn't fit it (other players' chat, or text not known yet).</summary>
|
||||
public List<string> Extra = new();
|
||||
|
||||
/// <summary>The press says "It holds." (the only success text seen so far).</summary>
|
||||
public bool Held => Outcome.IndexOf("holds", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
/// <summary>Used by the inference: a finished press with its whole gem block.</summary>
|
||||
public bool Usable => Complete && Modifiers.Count > 0;
|
||||
|
||||
public bool HasComponent(string name)
|
||||
{
|
||||
foreach (string c in Components)
|
||||
if (string.Equals(c, name, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool HasModifier(string name)
|
||||
{
|
||||
foreach (GemModifier m in Modifiers)
|
||||
if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public GemModifier? FindModifier(string name)
|
||||
{
|
||||
foreach (GemModifier m in Modifiers)
|
||||
if (string.Equals(m.Name, name, StringComparison.OrdinalIgnoreCase)) return m;
|
||||
return null;
|
||||
}
|
||||
|
||||
public string ComponentsText => Components.Count == 0 ? "no components" : string.Join(", ", Components);
|
||||
|
||||
public static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 16);
|
||||
}
|
||||
458
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs
Normal file
458
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressInference.cs
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>
|
||||
/// One modifier's rate in a set of presses (a component's, a combination's, ...), with its rate
|
||||
/// in the other presses for comparison.
|
||||
/// </summary>
|
||||
internal sealed class Odds
|
||||
{
|
||||
/// <summary>The modifier's name, or <see cref="PressInference.AffinityGroup"/> for any "<Material> Affinity".</summary>
|
||||
public string Modifier = string.Empty;
|
||||
/// <summary>Presses in the set that had it, of <see cref="N"/>.</summary>
|
||||
public int Hits, N;
|
||||
/// <summary>False for the All presses row: nothing to compare with.</summary>
|
||||
public bool Compared;
|
||||
/// <summary>The other presses (without the component, ...) that had it, of <see cref="OtherN"/>; 0 = no data.</summary>
|
||||
public int OtherHits, OtherN;
|
||||
/// <summary>One-sided Fisher exact p: chance of a rate this much higher here if the set made no difference.</summary>
|
||||
public double P = 1;
|
||||
/// <summary>Clearly higher here than in the other presses (Fisher p < 0.05 or the 95% intervals apart).</summary>
|
||||
public bool MoreLikely;
|
||||
/// <summary>Its numbers in these presses ("x1.38 to x1.52").</summary>
|
||||
public string Values = string.Empty;
|
||||
/// <summary>For the Affinity group: presses per material, most first.</summary>
|
||||
public List<(string Material, int Hits)> Split = new();
|
||||
|
||||
public double Rate => N == 0 ? 0 : (double)Hits / N;
|
||||
public double? OtherRate => OtherN == 0 ? null : (double)OtherHits / OtherN;
|
||||
public bool IsGroup => Modifier == PressInference.AffinityGroup;
|
||||
}
|
||||
|
||||
internal enum GroupKind { All, Component, Combination, NoComponents }
|
||||
|
||||
/// <summary>(fragment level, result level, entries) and how many presses gave it.</summary>
|
||||
internal readonly record struct ResultCount(int? FragmentLevel, int? ResultLevel, int? Entries, int Count);
|
||||
|
||||
/// <summary>A set of presses: All presses, one component's, one exact combination's, or those with no component.</summary>
|
||||
internal sealed class GroupReport
|
||||
{
|
||||
public string Name = string.Empty;
|
||||
public GroupKind Kind;
|
||||
/// <summary>The components (one for a component row, several for a combination, none otherwise).</summary>
|
||||
public List<string> Members = new();
|
||||
public int Presses;
|
||||
public double AvgModifiers;
|
||||
public int MinModifiers, MaxModifiers;
|
||||
/// <summary>Most common first.</summary>
|
||||
public List<ResultCount> Results = new();
|
||||
/// <summary>Every modifier seen in these presses, likeliest first.</summary>
|
||||
public List<Odds> Odds = new();
|
||||
|
||||
/// <summary>What the comparison column is: "without", "other presses", "with components", or "".</summary>
|
||||
public string OtherLabel => Kind switch
|
||||
{
|
||||
GroupKind.Component => "without",
|
||||
GroupKind.Combination => "other presses",
|
||||
GroupKind.NoComponents => "with components",
|
||||
_ => string.Empty,
|
||||
};
|
||||
|
||||
public Odds? Find(string modifier) =>
|
||||
Odds.FirstOrDefault(o => o.Modifier.Equals(modifier, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
internal sealed class ModifierReport
|
||||
{
|
||||
/// <summary>The modifier's name, or <see cref="PressInference.AffinityGroup"/>.</summary>
|
||||
public string Name = string.Empty;
|
||||
public bool IsGroup;
|
||||
public string Example = string.Empty;
|
||||
/// <summary>"reward" (loot, salvage), "harder" (monster health, damage, numbers) or "" when the text doesn't say plainly.</summary>
|
||||
public string Tag = string.Empty;
|
||||
/// <summary>Its rate over all usable presses.</summary>
|
||||
public Odds Overall = new();
|
||||
/// <summary>Its rate in presses with no components (against presses with some); null when there are none.</summary>
|
||||
public Odds? NoComponents;
|
||||
/// <summary>Its rate with each component and combination (0% included), likeliest first.</summary>
|
||||
public List<(GroupReport Group, Odds Odds)> ByGroup = new();
|
||||
public string Values = string.Empty;
|
||||
/// <summary>(fragment level, presses, values), lowest level first; level null = unknown.</summary>
|
||||
public List<(int? Level, int Count, string Values)> ByLevel = new();
|
||||
|
||||
public int Seen => Overall.Hits;
|
||||
}
|
||||
|
||||
internal sealed class ThreadsReport
|
||||
{
|
||||
public int Total, Usable, Incomplete, Characters;
|
||||
/// <summary>Every usable press (the baseline); null when there are none.</summary>
|
||||
public GroupReport? All;
|
||||
public List<GroupReport> Components = new();
|
||||
/// <summary>Exact combinations of two or more components.</summary>
|
||||
public List<GroupReport> Combinations = new();
|
||||
/// <summary>Presses with no components (the plain random draw); null when there are none.</summary>
|
||||
public GroupReport? NoComponents;
|
||||
public List<ModifierReport> Modifiers = new();
|
||||
|
||||
public GroupReport? Component(string name) =>
|
||||
Components.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public GroupReport? Combination(string name) =>
|
||||
Combinations.FirstOrDefault(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public ModifierReport? Modifier(string name) =>
|
||||
Modifiers.FirstOrDefault(m => m.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The odds of each modifier from the recorded presses. On DreamWeave a component gives a chance of
|
||||
/// each modifier, not a fixed one, so for every set of presses (All presses, each component, each
|
||||
/// exact combination of components, no components) this counts how often each modifier came:
|
||||
/// hits/N, with a 95% Wilson interval, against its rate in the presses outside the set.
|
||||
///
|
||||
/// Only finished presses with their gem block count (Press.Usable); a finished press without a
|
||||
/// "Components selected" line counts as one with no components. Every gem carries one
|
||||
/// "<Material> Affinity": those are counted together as the Affinity group, with the split by
|
||||
/// material.
|
||||
///
|
||||
/// "More likely with X": the rate with X is above the rate without and either the one-sided Fisher
|
||||
/// exact p is under 0.05 or the two 95% intervals don't overlap. "Always ... so far" only for 100%
|
||||
/// over at least 10 presses.
|
||||
/// </summary>
|
||||
internal static class PressInference
|
||||
{
|
||||
public const string AffinityGroup = "Affinity";
|
||||
private const string AffinitySuffix = " Affinity";
|
||||
private const double Z = 1.96;
|
||||
/// <summary>Intervals are shown below this many presses.</summary>
|
||||
public const int IntervalBelow = 50;
|
||||
public const int AlwaysAtLeast = 10;
|
||||
|
||||
public static ThreadsReport Build(IReadOnlyList<Press> all)
|
||||
{
|
||||
var report = new ThreadsReport { Total = all.Count };
|
||||
var used = new List<Press>();
|
||||
var characters = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (Press p in all)
|
||||
{
|
||||
if (p.Character.Length > 0) characters.Add(p.Character);
|
||||
if (!p.Complete) report.Incomplete++;
|
||||
if (p.Usable) used.Add(p);
|
||||
}
|
||||
report.Usable = used.Count;
|
||||
report.Characters = characters.Count;
|
||||
if (used.Count == 0) return report;
|
||||
|
||||
List<string> components = Distinct(used.SelectMany(p => p.Components));
|
||||
List<string> keys = Distinct(used.SelectMany(Keys));
|
||||
|
||||
report.All = Group("All presses", GroupKind.All, new List<string>(), used, used);
|
||||
|
||||
foreach (string c in components)
|
||||
report.Components.Add(Group(c, GroupKind.Component, new List<string> { c }, used, used.Where(p => p.HasComponent(c)).ToList()));
|
||||
SortGroups(report.Components);
|
||||
|
||||
foreach (var g in used.Where(p => p.Components.Count > 1).GroupBy(ComboKey, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
List<string> members = g.First().Components.OrderBy(x => x, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
report.Combinations.Add(Group(string.Join(" + ", members), GroupKind.Combination, members, used, g.ToList()));
|
||||
}
|
||||
SortGroups(report.Combinations);
|
||||
|
||||
List<Press> plain = used.Where(p => p.Components.Count == 0).ToList();
|
||||
if (plain.Count > 0)
|
||||
report.NoComponents = Group("No components", GroupKind.NoComponents, new List<string>(), used, plain);
|
||||
|
||||
foreach (string k in keys)
|
||||
{
|
||||
List<Press> with = used.Where(p => Has(p, k)).ToList();
|
||||
var mr = new ModifierReport
|
||||
{
|
||||
Name = k,
|
||||
IsGroup = k == AffinityGroup,
|
||||
Example = Find(with[^1], k)!.Description,
|
||||
Overall = Count(k, used, null),
|
||||
Values = Values(with, k),
|
||||
};
|
||||
mr.Tag = Tag(mr.Example);
|
||||
if (report.NoComponents != null) mr.NoComponents = Count(k, plain, used.Where(p => p.Components.Count > 0).ToList());
|
||||
foreach (GroupReport gr in report.Components.Concat(report.Combinations))
|
||||
mr.ByGroup.Add((gr, gr.Find(k) ?? Count(k, Members(used, gr), Others(used, gr))));
|
||||
mr.ByGroup.Sort((a, b) =>
|
||||
{
|
||||
int byOdds = CompareOdds(a.Odds, b.Odds);
|
||||
return byOdds != 0 ? byOdds : string.Compare(a.Group.Name, b.Group.Name, StringComparison.OrdinalIgnoreCase);
|
||||
});
|
||||
foreach (var g in with.GroupBy(p => p.FragmentLevel).OrderBy(g => g.Key ?? int.MaxValue))
|
||||
mr.ByLevel.Add((g.Key, g.Count(), Values(g, k)));
|
||||
report.Modifiers.Add(mr);
|
||||
}
|
||||
report.Modifiers.Sort((a, b) => b.Seen != a.Seen ? b.Seen.CompareTo(a.Seen) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||
return report;
|
||||
}
|
||||
|
||||
// ── Groups ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static GroupReport Group(string name, GroupKind kind, List<string> members, List<Press> used, List<Press> set)
|
||||
{
|
||||
var g = new GroupReport { Name = name, Kind = kind, Members = members, Presses = set.Count };
|
||||
if (set.Count == 0) return g;
|
||||
g.AvgModifiers = set.Average(p => (double)p.Modifiers.Count);
|
||||
g.MinModifiers = set.Min(p => p.Modifiers.Count);
|
||||
g.MaxModifiers = set.Max(p => p.Modifiers.Count);
|
||||
g.Results = set.GroupBy(p => (p.FragmentLevel, p.ResultLevel, p.Entries))
|
||||
.Select(x => new ResultCount(x.Key.FragmentLevel, x.Key.ResultLevel, x.Key.Entries, x.Count()))
|
||||
.OrderByDescending(r => r.Count).ThenBy(r => r.ResultLevel ?? int.MaxValue).ThenBy(r => r.Entries ?? int.MaxValue)
|
||||
.ToList();
|
||||
List<Press>? others = kind == GroupKind.All ? null : Others(used, g, set);
|
||||
foreach (string k in Distinct(set.SelectMany(Keys)))
|
||||
g.Odds.Add(Count(k, set, others));
|
||||
g.Odds.Sort(CompareOdds);
|
||||
return g;
|
||||
}
|
||||
|
||||
private static void SortGroups(List<GroupReport> groups) =>
|
||||
groups.Sort((a, b) => b.Presses != a.Presses ? b.Presses.CompareTo(a.Presses) : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The presses a component or combination row covers.</summary>
|
||||
private static List<Press> Members(List<Press> used, GroupReport g) => g.Kind switch
|
||||
{
|
||||
GroupKind.Component => used.Where(p => p.HasComponent(g.Members[0])).ToList(),
|
||||
GroupKind.Combination => used.Where(p => ComboKey(p).Equals(ComboKey(g.Members), StringComparison.OrdinalIgnoreCase)).ToList(),
|
||||
GroupKind.NoComponents => used.Where(p => p.Components.Count == 0).ToList(),
|
||||
_ => used,
|
||||
};
|
||||
|
||||
/// <summary>The presses a row is compared with: without the component, not this combination, with components.</summary>
|
||||
private static List<Press> Others(List<Press> used, GroupReport g, List<Press>? set = null)
|
||||
{
|
||||
var inSet = new HashSet<Press>(set ?? Members(used, g));
|
||||
return used.Where(p => !inSet.Contains(p)).ToList();
|
||||
}
|
||||
|
||||
private static string ComboKey(Press p) => ComboKey(p.Components);
|
||||
|
||||
private static string ComboKey(IEnumerable<string> components) =>
|
||||
string.Join("\n", components.Select(c => c.ToLowerInvariant()).OrderBy(c => c, StringComparer.Ordinal));
|
||||
|
||||
/// <summary>Likeliest first; then more presses; then by name.</summary>
|
||||
private static int CompareOdds(Odds a, Odds b)
|
||||
{
|
||||
if (a.Rate != b.Rate) return b.Rate.CompareTo(a.Rate);
|
||||
if (a.Hits != b.Hits) return b.Hits.CompareTo(a.Hits);
|
||||
return string.Compare(a.Modifier, b.Modifier, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>Modifier <paramref name="k"/> in <paramref name="set"/>, against <paramref name="others"/> (null = no comparison).</summary>
|
||||
internal static Odds Count(string k, List<Press> set, List<Press>? others)
|
||||
{
|
||||
var o = new Odds { Modifier = k, N = set.Count, Compared = others != null };
|
||||
foreach (Press p in set)
|
||||
if (Has(p, k)) o.Hits++;
|
||||
if (others != null)
|
||||
{
|
||||
o.OtherN = others.Count;
|
||||
foreach (Press p in others)
|
||||
if (Has(p, k)) o.OtherHits++;
|
||||
if (o.OtherN > 0 && o.N > 0)
|
||||
{
|
||||
o.P = FisherGreater(o.Hits, o.N, o.OtherHits, o.OtherN);
|
||||
bool apart = Wilson(o.Hits, o.N).Low > Wilson(o.OtherHits, o.OtherN).High;
|
||||
o.MoreLikely = o.Rate > o.OtherRate!.Value && (o.P < 0.05 || apart);
|
||||
}
|
||||
}
|
||||
o.Values = Values(set, k);
|
||||
if (k == AffinityGroup)
|
||||
{
|
||||
var split = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
||||
var names = new List<string>();
|
||||
foreach (Press p in set)
|
||||
foreach (string mat in p.Modifiers.Select(m => Material(m.Name)).OfType<string>().Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!split.ContainsKey(mat)) { split[mat] = 0; names.Add(mat); }
|
||||
split[mat]++;
|
||||
}
|
||||
o.Split = names.Select(n => (n, split[n]))
|
||||
.OrderByDescending(x => x.Item2).ThenBy(x => x.n, StringComparer.OrdinalIgnoreCase).ToList();
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
// ── Modifier keys (the Affinity group) ──────────────────────────────────
|
||||
|
||||
/// <summary>"Amethyst" for "Amethyst Affinity", else null.</summary>
|
||||
internal static string? Material(string modifier) =>
|
||||
modifier.Length > AffinitySuffix.Length && modifier.EndsWith(AffinitySuffix, StringComparison.OrdinalIgnoreCase)
|
||||
? modifier.Substring(0, modifier.Length - AffinitySuffix.Length).Trim()
|
||||
: null;
|
||||
|
||||
/// <summary>The name the counts use: <see cref="AffinityGroup"/> for any affinity, else the modifier's own.</summary>
|
||||
internal static string Key(string modifier) => Material(modifier) != null ? AffinityGroup : modifier;
|
||||
|
||||
private static IEnumerable<string> Keys(Press p) => p.Modifiers.Select(m => Key(m.Name));
|
||||
|
||||
private static bool Has(Press p, string k) => Find(p, k) != null;
|
||||
|
||||
private static GemModifier? Find(Press p, string k)
|
||||
{
|
||||
if (k != AffinityGroup) return p.FindModifier(k);
|
||||
foreach (GemModifier m in p.Modifiers)
|
||||
if (Material(m.Name) != null) return m;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>"Affinity (any)" for the group, else the name.</summary>
|
||||
internal static string Display(string k) => k == AffinityGroup ? "Affinity (any)" : k;
|
||||
|
||||
// ── Statistics ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>95% Wilson score interval for <paramref name="hits"/> of <paramref name="n"/>.</summary>
|
||||
internal static (double Low, double High) Wilson(int hits, int n)
|
||||
{
|
||||
if (n <= 0) return (0, 1);
|
||||
double p = (double)hits / n, z2 = Z * Z;
|
||||
double denom = 1 + z2 / n;
|
||||
double centre = (p + z2 / (2 * n)) / denom;
|
||||
double half = Z * Math.Sqrt(p * (1 - p) / n + z2 / (4.0 * n * n)) / denom;
|
||||
return (Math.Max(0, centre - half), Math.Min(1, centre + half));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One-sided Fisher exact test: the chance of <paramref name="a"/> or more hits in a set of
|
||||
/// <paramref name="n"/> when <paramref name="a"/> + <paramref name="c"/> hits are spread at random
|
||||
/// over the <paramref name="n"/> + <paramref name="m"/> presses.
|
||||
/// </summary>
|
||||
internal static double FisherGreater(int a, int n, int c, int m)
|
||||
{
|
||||
int total = n + m, hits = a + c;
|
||||
if (total == 0) return 1;
|
||||
double logAll = LogChoose(total, n), sum = 0;
|
||||
for (int x = a; x <= Math.Min(n, hits); x++)
|
||||
{
|
||||
if (hits - x > m) continue;
|
||||
sum += Math.Exp(LogChoose(hits, x) + LogChoose(total - hits, n - x) - logAll);
|
||||
}
|
||||
return Math.Min(1, sum);
|
||||
}
|
||||
|
||||
private static double LogChoose(int n, int k)
|
||||
{
|
||||
if (k < 0 || k > n) return double.NegativeInfinity;
|
||||
double r = 0;
|
||||
for (int i = 1; i <= k; i++) r += Math.Log(n - k + i) - Math.Log(i);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ── Text ────────────────────────────────────────────────────────────────
|
||||
|
||||
private static string Pct(double v) => Math.Round(v * 100).ToString("0", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>"75% (3/4, 30-95%)"; the interval only below <see cref="IntervalBelow"/> presses.</summary>
|
||||
internal static string OddsText(Odds o)
|
||||
{
|
||||
if (o.N == 0) return "no data";
|
||||
if (o.N >= IntervalBelow) return $"{Pct(o.Rate)}% ({o.Hits}/{o.N})";
|
||||
var (lo, hi) = Wilson(o.Hits, o.N);
|
||||
return $"{Pct(o.Rate)}% ({o.Hits}/{o.N}, {Pct(lo)}-{Pct(hi)}%)";
|
||||
}
|
||||
|
||||
/// <summary>"without: 20% (1/5)", "without: no data", or "" when not compared.</summary>
|
||||
internal static string OtherText(Odds o, string label)
|
||||
{
|
||||
if (!o.Compared || label.Length == 0) return string.Empty;
|
||||
return o.OtherN == 0 ? label + ": no data" : $"{label}: {Pct(o.OtherRate!.Value)}% ({o.OtherHits}/{o.OtherN})";
|
||||
}
|
||||
|
||||
/// <summary>"more likely with Lead Scarab", "always with Lead Scarab so far" (100% over 10+), or "".</summary>
|
||||
internal static string LikelyText(Odds o, GroupReport g)
|
||||
{
|
||||
if (!o.MoreLikely) return string.Empty;
|
||||
string who = g.Kind == GroupKind.NoComponents ? "no components" : g.Name;
|
||||
return o.Hits == o.N && o.N >= AlwaysAtLeast ? $"always with {who} so far" : $"more likely with {who}";
|
||||
}
|
||||
|
||||
/// <summary>"Amethyst 1, Iron 1" for the Affinity group's split, else "".</summary>
|
||||
internal static string SplitText(Odds o) =>
|
||||
string.Join(", ", o.Split.Select(s => $"{s.Material} {s.Hits}"));
|
||||
|
||||
/// <summary>"5.25 modifiers per press (5-6)".</summary>
|
||||
internal static string ModifiersText(GroupReport g)
|
||||
{
|
||||
string avg = g.AvgModifiers.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
string range = g.MinModifiers == g.MaxModifiers ? "" : $" ({g.MinModifiers}-{g.MaxModifiers})";
|
||||
return $"{avg} modifiers per press{range}";
|
||||
}
|
||||
|
||||
/// <summary>"L185 -> 175, 3 entries: 4" per result, most common first.</summary>
|
||||
internal static string ResultsText(GroupReport g) =>
|
||||
string.Join("; ", g.Results.Select(r =>
|
||||
$"L{N(r.FragmentLevel)} -> {N(r.ResultLevel)}, {N(r.Entries)} entries: {r.Count}"));
|
||||
|
||||
private static string N(int? v) => v?.ToString(CultureInfo.InvariantCulture) ?? "?";
|
||||
|
||||
private static List<string> Distinct(IEnumerable<string> names)
|
||||
{
|
||||
var list = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string n in names)
|
||||
if (n.Length > 0 && seen.Add(n)) list.Add(n);
|
||||
list.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The modifier's numbers across presses, position by position: "x1.38 to x1.52, 12%". Empty
|
||||
/// when it has none.
|
||||
/// </summary>
|
||||
internal static string Values(IEnumerable<Press> presses, string k)
|
||||
{
|
||||
var ranges = new List<(string Kind, double Min, double Max)>();
|
||||
foreach (Press p in presses)
|
||||
{
|
||||
GemModifier? gm = Find(p, k);
|
||||
if (gm == null) continue;
|
||||
for (int i = 0; i < gm.Numbers.Count; i++)
|
||||
{
|
||||
ModNumber n = gm.Numbers[i];
|
||||
if (i >= ranges.Count) ranges.Add((n.Kind, n.Value, n.Value));
|
||||
else ranges[i] = (ranges[i].Kind, Math.Min(ranges[i].Min, n.Value), Math.Max(ranges[i].Max, n.Value));
|
||||
}
|
||||
}
|
||||
var sb = new StringBuilder();
|
||||
foreach (var (kind, min, max) in ranges)
|
||||
{
|
||||
if (sb.Length > 0) sb.Append(", ");
|
||||
sb.Append(Format(kind, min));
|
||||
if (max != min) sb.Append(" to ").Append(Format(kind, max));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
internal static string Format(string kind, double v)
|
||||
{
|
||||
string s = v.ToString("0.##", CultureInfo.InvariantCulture);
|
||||
return kind switch
|
||||
{
|
||||
ModNumber.Mult => "x" + s,
|
||||
ModNumber.Pct => s + "%",
|
||||
ModNumber.Plus => v >= 0 ? "+" + s : s,
|
||||
_ => s,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"reward" or "harder" when the description says so plainly, else "".</summary>
|
||||
internal static string Tag(string description)
|
||||
{
|
||||
string d = description.ToLowerInvariant();
|
||||
bool reward = d.Contains("loot") || d.Contains("salvage") || d.Contains("drop");
|
||||
bool harder = d.Contains("monsters have") || d.Contains("more monsters") || d.Contains("monsters attack")
|
||||
|| d.Contains("boss attacks") || d.Contains("hitting harder");
|
||||
return reward == harder ? string.Empty : reward ? "reward" : "harder";
|
||||
}
|
||||
}
|
||||
250
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs
Normal file
250
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressParser.cs
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>
|
||||
/// Reads Fragment Press results out of chat, one line at a time. A press starts at
|
||||
/// "Using the Raw Fragment (Level 185) with the Fragment Press"
|
||||
/// and collects, in any order and with other chat in between:
|
||||
/// "Pressed. It holds." the outcome (any "Pressed..." line)
|
||||
/// "Components selected: A, B" (or "No components ...")
|
||||
/// "Remaining slots drawn at random." (any "... drawn at random" line)
|
||||
/// "The gem carries:" then one " Name - description" line per modifier
|
||||
/// and ends at "Level 190, 4 entries." (complete). A press that never gets there is still saved,
|
||||
/// marked incomplete: after <see cref="TimeoutMs"/> without a line of its own, when another
|
||||
/// "Using ..." line comes, or at logout. Lines that don't fit are kept in the press's Extra list
|
||||
/// (other players' chat lands there too). Never throws on odd text.
|
||||
/// </summary>
|
||||
internal sealed class PressParser
|
||||
{
|
||||
/// <summary>A press's lines arrive within the same second; this long without one ends it.</summary>
|
||||
public const long TimeoutMs = 15_000;
|
||||
private const int MaxLineLength = 400;
|
||||
private const int MaxRawLines = 80;
|
||||
private const int MaxExtraLines = 40;
|
||||
private const int MaxModifiers = 40;
|
||||
|
||||
private static readonly RegexOptions Opt = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;
|
||||
private static readonly Regex UseRx = new(@"^Using (?:the |an? )?(?<item>.+?) with (?:the |an? )?(?<tool>[^.]*\bPress)\b", Opt);
|
||||
private static readonly Regex LevelInName = new(@"^(?<name>.*?)\s*\(\s*Level\s+(?<lvl>\d+)\s*\)\s*$", Opt);
|
||||
private static readonly Regex ComponentsRx = new(@"^Components?(?: selected)?\s*:\s*(?<list>.*)$", Opt);
|
||||
private static readonly Regex NoComponentsRx = new(@"^No components\b", Opt);
|
||||
private static readonly Regex CarriesRx = new(@"^The [^:]{1,40} carries\s*:?\s*$", Opt);
|
||||
private static readonly Regex EndRx = new(@"^Level\s+(?<lvl>\d+)\s*(?:,\s*(?<entries>\d+)\s+entr(?:y|ies))?\s*\.?\s*$", Opt);
|
||||
// "Name - description": a short name of letters, spaces, apostrophes and hyphens.
|
||||
private static readonly Regex ModifierRx = new(@"^(?<name>[A-Za-z][A-Za-z' \-]{0,47}?)\s+[-–—]\s+(?<desc>.+)$", Opt);
|
||||
private static readonly Regex NumberRx = new(
|
||||
@"(?<![A-Za-z0-9.])(?:(?<mult>[x×]\s?\d+(?:\.\d+)?)|(?<plus>[+\-]\d+(?:\.\d+)?)(?!\d|\.\d|\s?%)|(?<pct>[+\-]?\d+(?:\.\d+)?\s?%)|(?<num>\d+(?:\.\d+)?))",
|
||||
RegexOptions.CultureInvariant);
|
||||
|
||||
private enum State { Idle, Open, Carries }
|
||||
|
||||
private State _state = State.Idle;
|
||||
private Press? _press;
|
||||
private long _lastOwnLineMs;
|
||||
|
||||
/// <summary>A press is being read.</summary>
|
||||
public bool Busy => _press != null;
|
||||
|
||||
/// <summary>
|
||||
/// Feeds one chat message (it may hold several lines). Returns the presses it finished, or
|
||||
/// null. <paramref name="nowMs"/> is a monotonic clock (Environment.TickCount64).
|
||||
/// </summary>
|
||||
public List<Press>? Feed(string? text, long nowMs)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return null;
|
||||
List<Press>? done = null;
|
||||
foreach (string piece in text.Split('\n'))
|
||||
{
|
||||
string line = piece.TrimEnd('\r', ' ', '\t');
|
||||
if (line.Trim().Length == 0) continue;
|
||||
if (line.Length > MaxLineLength) line = line.Substring(0, MaxLineLength);
|
||||
try
|
||||
{
|
||||
Press? finished = FeedLine(line, nowMs);
|
||||
if (finished != null) (done ??= new List<Press>()).Add(finished);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Odd text must never stop chat; the line is just not used.
|
||||
}
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
/// <summary>Ends a press that has gone quiet. Returns it (incomplete), or null.</summary>
|
||||
public Press? Tick(long nowMs)
|
||||
{
|
||||
if (_press == null || nowMs - _lastOwnLineMs < TimeoutMs) return null;
|
||||
return Finish("timeout");
|
||||
}
|
||||
|
||||
/// <summary>Ends whatever is open (logout, unload). Returns it (incomplete), or null.</summary>
|
||||
public Press? Flush(string reason) => _press == null ? null : Finish(reason);
|
||||
|
||||
private Press? FeedLine(string line, long nowMs)
|
||||
{
|
||||
string t = line.Trim();
|
||||
Press? previous = null;
|
||||
|
||||
if (t.StartsWith("Using ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Match use = UseRx.Match(t);
|
||||
if (_press != null) previous = Finish("next use");
|
||||
if (!use.Success) return previous;
|
||||
Start(use, line, nowMs);
|
||||
return previous;
|
||||
}
|
||||
if (_press == null) return null;
|
||||
|
||||
if (_state == State.Carries)
|
||||
{
|
||||
Match mod = ModifierRx.Match(t);
|
||||
// Modifier lines are indented; an unindented one must still look exactly like "Name - text".
|
||||
bool indented = line.Length > 0 && char.IsWhiteSpace(line[0]);
|
||||
if (mod.Success && (indented || !LooksLikeChat(t)))
|
||||
{
|
||||
if (_press.Modifiers.Count < MaxModifiers) _press.Modifiers.Add(MakeModifier(mod));
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Match end = EndRx.Match(t);
|
||||
if (end.Success)
|
||||
{
|
||||
_press.ResultLevel = Int(end.Groups["lvl"].Value);
|
||||
if (end.Groups["entries"].Success) _press.Entries = Int(end.Groups["entries"].Value);
|
||||
Own(line, nowMs);
|
||||
return Finish("done", complete: true);
|
||||
}
|
||||
if (t.StartsWith("Pressed", StringComparison.OrdinalIgnoreCase) && _press.Outcome.Length == 0)
|
||||
{
|
||||
_press.Outcome = t;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
Match comps = ComponentsRx.Match(t);
|
||||
if (comps.Success && !_press.ComponentsSeen)
|
||||
{
|
||||
_press.ComponentsSeen = true;
|
||||
_press.Components = SplitComponents(comps.Groups["list"].Value);
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
if (NoComponentsRx.IsMatch(t) && !_press.ComponentsSeen)
|
||||
{
|
||||
_press.ComponentsSeen = true;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
if (t.IndexOf("drawn at random", StringComparison.OrdinalIgnoreCase) >= 0 && _press.RandomNote.Length == 0)
|
||||
{
|
||||
_press.RandomNote = t;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
if (CarriesRx.IsMatch(t))
|
||||
{
|
||||
_state = State.Carries;
|
||||
Own(line, nowMs);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Not ours (or not known yet): keep it beside the press, don't let it extend the timeout.
|
||||
if (_press.Extra.Count < MaxExtraLines) _press.Extra.Add(line);
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Start(Match use, string line, long nowMs)
|
||||
{
|
||||
string item = use.Groups["item"].Value.Trim();
|
||||
var p = new Press
|
||||
{
|
||||
Id = Press.NewId(),
|
||||
TimeUtc = DateTime.UtcNow,
|
||||
Tool = use.Groups["tool"].Value.Trim(),
|
||||
Fragment = item,
|
||||
};
|
||||
Match lv = LevelInName.Match(item);
|
||||
if (lv.Success)
|
||||
{
|
||||
p.Fragment = lv.Groups["name"].Value.Trim();
|
||||
p.FragmentLevel = Int(lv.Groups["lvl"].Value);
|
||||
}
|
||||
_press = p;
|
||||
_state = State.Open;
|
||||
Own(line, nowMs);
|
||||
}
|
||||
|
||||
private void Own(string line, long nowMs)
|
||||
{
|
||||
if (_press!.Raw.Count < MaxRawLines) _press.Raw.Add(line);
|
||||
_lastOwnLineMs = nowMs;
|
||||
}
|
||||
|
||||
private Press Finish(string reason, bool complete = false)
|
||||
{
|
||||
Press p = _press!;
|
||||
p.Complete = complete;
|
||||
p.End = reason;
|
||||
_press = null;
|
||||
_state = State.Idle;
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>Chat from players and channels ("Bob says, ...", "[Trade] ...", "You tell ...").</summary>
|
||||
private static bool LooksLikeChat(string t) =>
|
||||
t.StartsWith("[", StringComparison.Ordinal) || t.Contains(" says, ") || t.Contains(" tells you")
|
||||
|| t.StartsWith("You ", StringComparison.Ordinal) || t.Contains('"');
|
||||
|
||||
internal static List<string> SplitComponents(string list)
|
||||
{
|
||||
var result = new List<string>();
|
||||
string s = list.Trim().TrimEnd('.');
|
||||
if (s.Length == 0 || s.Equals("none", StringComparison.OrdinalIgnoreCase)) return result;
|
||||
foreach (string part in s.Replace(" and ", ",", StringComparison.OrdinalIgnoreCase).Split(','))
|
||||
{
|
||||
string c = part.Trim();
|
||||
if (c.Length > 0 && !result.Exists(x => x.Equals(c, StringComparison.OrdinalIgnoreCase))) result.Add(c);
|
||||
}
|
||||
result.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static GemModifier MakeModifier(Match m)
|
||||
{
|
||||
string desc = m.Groups["desc"].Value.Trim();
|
||||
return new GemModifier
|
||||
{
|
||||
Name = m.Groups["name"].Value.Trim(),
|
||||
Description = desc,
|
||||
Numbers = Numbers(desc),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Every number in a description with its form: x1.38, 12%, +29 (or -5), 75.</summary>
|
||||
internal static List<ModNumber> Numbers(string text)
|
||||
{
|
||||
var list = new List<ModNumber>();
|
||||
foreach (Match m in NumberRx.Matches(text))
|
||||
{
|
||||
string kind;
|
||||
string raw;
|
||||
if (m.Groups["mult"].Success) { kind = ModNumber.Mult; raw = m.Groups["mult"].Value; }
|
||||
else if (m.Groups["plus"].Success) { kind = ModNumber.Plus; raw = m.Groups["plus"].Value; }
|
||||
else if (m.Groups["pct"].Success) { kind = ModNumber.Pct; raw = m.Groups["pct"].Value; }
|
||||
else { kind = ModNumber.Num; raw = m.Groups["num"].Value; }
|
||||
string digits = raw.TrimStart('x', '×', '+').TrimEnd('%').Trim();
|
||||
if (double.TryParse(digits, NumberStyles.Float, CultureInfo.InvariantCulture, out double v))
|
||||
list.Add(new ModNumber(v, kind, raw.Replace(" ", string.Empty)));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static int? Int(string s) =>
|
||||
int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : null;
|
||||
}
|
||||
346
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs
Normal file
346
Plugins/RynthCore.Plugin.RynthThreads/Threads/PressStore.cs
Normal file
|
|
@ -0,0 +1,346 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Threads;
|
||||
|
||||
/// <summary>
|
||||
/// Every press, one JSON object per line, in one file shared by all characters and clients on the
|
||||
/// PC (%LOCALAPPDATA%\RynthCore\RynthThreads\presses.jsonl). Appends open the file for writing
|
||||
/// alone, so two clients never mix their lines: a writer that finds it busy tries again a few
|
||||
/// times, and a press that still can't be written waits for <see cref="FlushPending"/>.
|
||||
/// Reading follows the file's growth (<see cref="Poll"/>), so other clients' presses show up.
|
||||
/// Written by hand with Utf8JsonWriter and read with JsonDocument: plugin types never go through
|
||||
/// System.Text.Json's serializer (its cache would keep an old plugin alive across a hot reload).
|
||||
/// </summary>
|
||||
internal sealed class PressStore
|
||||
{
|
||||
public const string FileName = "presses.jsonl";
|
||||
private const int AppendTries = 4;
|
||||
private const int AppendWaitMs = 15;
|
||||
private const int MaxPending = 200;
|
||||
|
||||
private readonly List<Press> _presses = new();
|
||||
private readonly HashSet<string> _ids = new(StringComparer.Ordinal);
|
||||
private readonly List<Press> _pending = new();
|
||||
private long _readOffset;
|
||||
|
||||
public readonly string Folder;
|
||||
public string FilePath => Path.Combine(Folder, FileName);
|
||||
|
||||
/// <summary>Every press read or recorded, oldest first.</summary>
|
||||
public IReadOnlyList<Press> Presses => _presses;
|
||||
/// <summary>Presses recorded here that couldn't be written yet.</summary>
|
||||
public int PendingCount => _pending.Count;
|
||||
/// <summary>Lines in the file that couldn't be read (kept in the file, skipped here).</summary>
|
||||
public int BadLines { get; private set; }
|
||||
/// <summary>Bumped whenever <see cref="Presses"/> changes.</summary>
|
||||
public int Version { get; private set; }
|
||||
|
||||
public PressStore(string folder) => Folder = folder;
|
||||
|
||||
/// <summary>%LOCALAPPDATA%\RynthCore\RynthThreads.</summary>
|
||||
public static string DefaultFolder => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "RynthThreads");
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the press and appends it to the file. Returns null when written, else why not (it
|
||||
/// stays pending and <see cref="FlushPending"/> tries again).
|
||||
/// </summary>
|
||||
public string? Record(Press p)
|
||||
{
|
||||
if (p.Id.Length == 0) p.Id = Press.NewId();
|
||||
Add(p);
|
||||
string? error = TryAppend(ToJson(p));
|
||||
if (error != null && _pending.Count < MaxPending) _pending.Add(p);
|
||||
return error;
|
||||
}
|
||||
|
||||
/// <summary>Writes presses that found the file busy before. Returns how many are still waiting.</summary>
|
||||
public int FlushPending()
|
||||
{
|
||||
while (_pending.Count > 0)
|
||||
{
|
||||
if (TryAppend(ToJson(_pending[0])) != null) break;
|
||||
_pending.RemoveAt(0);
|
||||
}
|
||||
return _pending.Count;
|
||||
}
|
||||
|
||||
/// <summary>Appends one line, retrying briefly while another writer holds the file.</summary>
|
||||
internal string? TryAppend(string json)
|
||||
{
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(json + "\n");
|
||||
string? last = null;
|
||||
for (int attempt = 0; attempt < AppendTries; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
// FileShare.Read: readers may look, no other writer gets in until this line is down.
|
||||
using var fs = new FileStream(FilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
|
||||
fs.Write(bytes, 0, bytes.Length);
|
||||
return null;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
last = ex.Message;
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
if (attempt < AppendTries - 1) Thread.Sleep(AppendWaitMs * (attempt + 1)); // at most 90 ms on the pump
|
||||
}
|
||||
return last ?? "the file is busy";
|
||||
}
|
||||
|
||||
// ── Reading ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Reads what was added to the file since the last read (everything the first time). Returns the number of new presses.</summary>
|
||||
public int Poll()
|
||||
{
|
||||
string path = FilePath;
|
||||
long length;
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists) return 0;
|
||||
length = info.Length;
|
||||
}
|
||||
catch { return 0; }
|
||||
|
||||
if (length < _readOffset) _readOffset = 0; // replaced or cut short: read it all again (ids keep it from doubling)
|
||||
if (length == _readOffset) return 0;
|
||||
|
||||
byte[] data;
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
fs.Seek(_readOffset, SeekOrigin.Begin);
|
||||
data = new byte[length - _readOffset];
|
||||
int got = 0;
|
||||
while (got < data.Length)
|
||||
{
|
||||
int n = fs.Read(data, got, data.Length - got);
|
||||
if (n <= 0) break;
|
||||
got += n;
|
||||
}
|
||||
if (got < data.Length) Array.Resize(ref data, got);
|
||||
}
|
||||
catch { return 0; }
|
||||
|
||||
// Only whole lines; a line still being written is read next time.
|
||||
int lastNewline = Array.LastIndexOf(data, (byte)'\n');
|
||||
if (lastNewline < 0) return 0;
|
||||
_readOffset += lastNewline + 1;
|
||||
|
||||
int added = 0;
|
||||
foreach (string line in Encoding.UTF8.GetString(data, 0, lastNewline).Split('\n'))
|
||||
{
|
||||
string l = line.Trim();
|
||||
if (l.Length == 0) continue;
|
||||
Press? p = FromJson(l);
|
||||
if (p == null) { BadLines++; continue; }
|
||||
if (Add(p)) added++;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
private bool Add(Press p)
|
||||
{
|
||||
if (p.Id.Length > 0 && !_ids.Add(p.Id)) return false;
|
||||
// Kept in time order (other clients' lines can land out of order).
|
||||
int at = _presses.Count;
|
||||
while (at > 0 && _presses[at - 1].TimeUtc > p.TimeUtc) at--;
|
||||
_presses.Insert(at, p);
|
||||
Version++;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── JSON ────────────────────────────────────────────────────────────────
|
||||
|
||||
internal static string ToJson(Press p)
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("v", 1);
|
||||
w.WriteString("id", p.Id);
|
||||
w.WriteString("time", p.TimeUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture));
|
||||
w.WriteString("server", p.Server);
|
||||
w.WriteString("character", p.Character);
|
||||
w.WriteString("fragment", p.Fragment);
|
||||
WriteInt(w, "fragmentLevel", p.FragmentLevel);
|
||||
w.WriteString("tool", p.Tool);
|
||||
w.WriteString("outcome", p.Outcome);
|
||||
w.WriteBoolean("componentsSeen", p.ComponentsSeen);
|
||||
w.WriteStartArray("components");
|
||||
foreach (string c in p.Components) w.WriteStringValue(c);
|
||||
w.WriteEndArray();
|
||||
w.WriteString("random", p.RandomNote);
|
||||
w.WriteStartArray("modifiers");
|
||||
foreach (GemModifier m in p.Modifiers)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("name", m.Name);
|
||||
w.WriteString("description", m.Description);
|
||||
w.WriteStartArray("numbers");
|
||||
foreach (ModNumber n in m.Numbers)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("value", n.Value);
|
||||
w.WriteString("kind", n.Kind);
|
||||
w.WriteString("text", n.Text);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
WriteInt(w, "resultLevel", p.ResultLevel);
|
||||
WriteInt(w, "entries", p.Entries);
|
||||
w.WriteBoolean("complete", p.Complete);
|
||||
w.WriteString("end", p.End);
|
||||
WriteStrings(w, "raw", p.Raw);
|
||||
WriteStrings(w, "extra", p.Extra);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
|
||||
private static void WriteInt(Utf8JsonWriter w, string name, int? v)
|
||||
{
|
||||
if (v.HasValue) w.WriteNumber(name, v.Value);
|
||||
else w.WriteNull(name);
|
||||
}
|
||||
|
||||
private static void WriteStrings(Utf8JsonWriter w, string name, List<string> list)
|
||||
{
|
||||
w.WriteStartArray(name);
|
||||
foreach (string s in list) w.WriteStringValue(s);
|
||||
w.WriteEndArray();
|
||||
}
|
||||
|
||||
/// <summary>One line back into a press, or null when it isn't one. Unknown fields are ignored, missing ones left empty.</summary>
|
||||
internal static Press? FromJson(string line)
|
||||
{
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(line);
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object) return null;
|
||||
var p = new Press
|
||||
{
|
||||
Id = Str(r, "id"),
|
||||
Server = Str(r, "server"),
|
||||
Character = Str(r, "character"),
|
||||
Fragment = Str(r, "fragment"),
|
||||
FragmentLevel = IntOrNull(r, "fragmentLevel"),
|
||||
Tool = Str(r, "tool"),
|
||||
Outcome = Str(r, "outcome"),
|
||||
ComponentsSeen = Bool(r, "componentsSeen"),
|
||||
Components = Strings(r, "components"),
|
||||
RandomNote = Str(r, "random"),
|
||||
ResultLevel = IntOrNull(r, "resultLevel"),
|
||||
Entries = IntOrNull(r, "entries"),
|
||||
Complete = Bool(r, "complete"),
|
||||
End = Str(r, "end"),
|
||||
Raw = Strings(r, "raw"),
|
||||
Extra = Strings(r, "extra"),
|
||||
};
|
||||
p.Components.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
if (DateTime.TryParse(Str(r, "time"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t))
|
||||
p.TimeUtc = t.ToUniversalTime();
|
||||
if (r.TryGetProperty("modifiers", out JsonElement mods) && mods.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement m in mods.EnumerateArray())
|
||||
{
|
||||
if (m.ValueKind != JsonValueKind.Object) continue;
|
||||
var gm = new GemModifier { Name = Str(m, "name"), Description = Str(m, "description") };
|
||||
if (gm.Name.Length == 0) continue;
|
||||
if (m.TryGetProperty("numbers", out JsonElement nums) && nums.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement n in nums.EnumerateArray())
|
||||
if (n.ValueKind == JsonValueKind.Object && n.TryGetProperty("value", out JsonElement v) && v.TryGetDouble(out double d))
|
||||
gm.Numbers.Add(new ModNumber(d, Str(n, "kind"), Str(n, "text")));
|
||||
p.Modifiers.Add(gm);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Str(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty;
|
||||
|
||||
private static bool Bool(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
|
||||
|
||||
private static int? IntOrNull(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : null;
|
||||
|
||||
private static List<string> Strings(JsonElement o, string name)
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (o.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement e in a.EnumerateArray())
|
||||
if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? string.Empty);
|
||||
return list;
|
||||
}
|
||||
|
||||
// ── CSV ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Writes every press as CSV into this folder (presses-yyyyMMdd-HHmmss.csv). Returns the path.</summary>
|
||||
public string ExportCsv(DateTime localNow)
|
||||
{
|
||||
Directory.CreateDirectory(Folder);
|
||||
string path = Path.Combine(Folder, "presses-" + localNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture) + ".csv");
|
||||
File.WriteAllText(path, Csv(_presses), new UTF8Encoding(true));
|
||||
return path;
|
||||
}
|
||||
|
||||
internal static string Csv(IEnumerable<Press> presses)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("time_utc,server,character,fragment,fragment_level,outcome,components,result_level,entries,complete,modifier_count,modifiers\r\n");
|
||||
foreach (Press p in presses)
|
||||
{
|
||||
var mods = new List<string>();
|
||||
foreach (GemModifier m in p.Modifiers) mods.Add(m.Name + ": " + m.Description);
|
||||
Cell(sb, p.TimeUtc.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)); sb.Append(',');
|
||||
Cell(sb, p.Server); sb.Append(',');
|
||||
Cell(sb, p.Character); sb.Append(',');
|
||||
Cell(sb, p.Fragment); sb.Append(',');
|
||||
Cell(sb, p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(',');
|
||||
Cell(sb, p.Outcome); sb.Append(',');
|
||||
Cell(sb, string.Join("; ", p.Components)); sb.Append(',');
|
||||
Cell(sb, p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(',');
|
||||
Cell(sb, p.Entries?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); sb.Append(',');
|
||||
Cell(sb, p.Complete ? "yes" : "no (" + p.End + ")"); sb.Append(',');
|
||||
Cell(sb, p.Modifiers.Count.ToString(CultureInfo.InvariantCulture)); sb.Append(',');
|
||||
Cell(sb, string.Join(" | ", mods));
|
||||
sb.Append("\r\n");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static void Cell(StringBuilder sb, string s)
|
||||
{
|
||||
// A spreadsheet would run a cell starting with = + - @ as a formula: start it with ' instead.
|
||||
if (s.Length > 0 && s[0] is '=' or '+' or '-' or '@') s = "'" + s;
|
||||
bool quote = s.IndexOfAny(new[] { ',', '"', '\n', '\r' }) >= 0;
|
||||
if (!quote) { sb.Append(s); return; }
|
||||
sb.Append('"').Append(s.Replace("\"", "\"\"")).Append('"');
|
||||
}
|
||||
}
|
||||
130
Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs
Normal file
130
Plugins/RynthCore.Plugin.RynthThreads/Ui/UiFormat.cs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// Display-list format 1 for the engine's script windows (RynthSuite
|
||||
/// Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2-4.3; the engine's DisplayListParser.cs is the source of
|
||||
/// truth). Little-endian. Only the ops these windows draw are listed.
|
||||
/// </summary>
|
||||
internal static class UiFormat
|
||||
{
|
||||
public const uint Magic = 0x31575352; // 'RSW1'
|
||||
public const ushort FormatVersion = 1;
|
||||
public const uint BodyUnchanged = 0xFFFFFFFF;
|
||||
public const int MaxString = 4096;
|
||||
public const int MaxStr8 = 128;
|
||||
public const int MaxOps = 1500; // engine limit per window
|
||||
public const int MaxBodyBytes = 64 * 1024; // engine limit per window
|
||||
public const byte OpHasBlock = 1;
|
||||
|
||||
// Ops
|
||||
public const byte OpEnd = 0x00;
|
||||
public const byte OpText = 0x01;
|
||||
public const byte OpTextColored = 0x02;
|
||||
public const byte OpTextWrapped = 0x03;
|
||||
public const byte OpTextDisabled = 0x04;
|
||||
public const byte OpBulletText = 0x05;
|
||||
public const byte OpSeparatorText = 0x06;
|
||||
public const byte OpSeparator = 0x10;
|
||||
public const byte OpSameLine = 0x11;
|
||||
public const byte OpSpacing = 0x13;
|
||||
public const byte OpDummy = 0x14;
|
||||
public const byte OpIndent = 0x15;
|
||||
public const byte OpUnindent = 0x16;
|
||||
public const byte OpButton = 0x20;
|
||||
public const byte OpCheckbox = 0x21;
|
||||
public const byte OpSliderInt = 0x22;
|
||||
public const byte OpInputText = 0x24;
|
||||
public const byte OpCombo = 0x25;
|
||||
public const byte OpSelectable = 0x26;
|
||||
public const byte OpProgressBar = 0x27;
|
||||
public const byte OpImage = 0x28; // op level 2 (engines from 2026-09-30)
|
||||
public const byte OpPushID = 0x30;
|
||||
public const byte OpPopID = 0x31;
|
||||
public const byte OpPushStyleColor = 0x32;
|
||||
public const byte OpPopStyleColor = 0x33;
|
||||
public const byte OpSetItemTooltip = 0x38;
|
||||
public const byte OpChild = 0x40;
|
||||
public const byte OpCollapsingHeader = 0x41;
|
||||
|
||||
// Window flags
|
||||
public const uint FlagVisible = 1u << 0;
|
||||
public const uint FlagShowInBar = 1u << 1;
|
||||
/// <summary>With ShowInBar: a bar button of its own instead of a Scripts menu line (engines from
|
||||
/// 2026-10-11; older ones ignore it and list the window in the Scripts menu).</summary>
|
||||
public const uint FlagBarButton = 1u << 11;
|
||||
public const uint FlagNoScrollbar = 1u << 5;
|
||||
|
||||
// Image icon kinds (op level 2)
|
||||
public const byte IconKindIcon = 0; // a 0x06 texture id
|
||||
public const byte IconKindObject = 1; // a live object's icon with underlay and overlay
|
||||
|
||||
// Selectable flags
|
||||
public const uint SelectableAllowDoubleClick = 4;
|
||||
|
||||
// Event types
|
||||
public const ushort EvClicked = 1;
|
||||
public const ushort EvBool = 2;
|
||||
public const ushort EvInt = 3;
|
||||
public const ushort EvText = 5;
|
||||
public const ushort EvOpen = 6;
|
||||
public const ushort EvVisibility = 8;
|
||||
public const ushort EvError = 10;
|
||||
|
||||
// ImGuiCol ids the engine accepts in PushStyleColor (ImGui.NET 1.91.6.1)
|
||||
public const int ColText = 0;
|
||||
public const int ColButton = 21;
|
||||
public const int ColButtonHovered = 22;
|
||||
public const int ColHeader = 24;
|
||||
|
||||
// InputText flags
|
||||
public const uint InputAutoSelectAll = 4096;
|
||||
/// <summary>The text box reports Enter (its event carries submitted = true).</summary>
|
||||
public const uint InputEnterReturnsTrue = 32;
|
||||
|
||||
// CollapsingHeader flags
|
||||
public const uint TreeDefaultOpen = 32;
|
||||
|
||||
public static uint Fnv1a(ReadOnlySpan<byte> bytes, uint hash = 2166136261)
|
||||
{
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
hash ^= b;
|
||||
hash *= 16777619;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>The length of <paramref name="s"/> cut to at most <paramref name="max"/> bytes without splitting a character.</summary>
|
||||
public static int CutUtf8(ReadOnlySpan<byte> s, int max)
|
||||
{
|
||||
if (s.Length <= max) return s.Length;
|
||||
int n = Math.Max(0, max);
|
||||
while (n > 0 && (s[n] & 0xC0) == 0x80) n--;
|
||||
return n;
|
||||
}
|
||||
|
||||
/// <summary>An ImGui U32 colour (0xAABBGGRR) from RGB bytes.</summary>
|
||||
public static uint Rgb(byte r, byte g, byte b, byte a = 255) =>
|
||||
((uint)a << 24) | ((uint)b << 16) | ((uint)g << 8) | r;
|
||||
}
|
||||
|
||||
/// <summary>Colours RynthThreads uses (copied from RynthSort) (0xAABBGGRR).</summary>
|
||||
internal static class UiColors
|
||||
{
|
||||
public static readonly uint Green = UiFormat.Rgb(110, 210, 110);
|
||||
public static readonly uint Red = UiFormat.Rgb(225, 95, 95);
|
||||
public static readonly uint Yellow = UiFormat.Rgb(235, 205, 90);
|
||||
public static readonly uint Grey = UiFormat.Rgb(150, 150, 150);
|
||||
public static readonly uint Gold = UiFormat.Rgb(230, 180, 60);
|
||||
/// <summary>Upstream's "destruction" highlight: deep pink brightened by half (255, 30, 220).</summary>
|
||||
public static readonly uint Destruction = UiFormat.Rgb(255, 30, 220);
|
||||
public static readonly uint TabActive = UiFormat.Rgb(60, 110, 170);
|
||||
public static readonly uint TabActiveHover = UiFormat.Rgb(75, 130, 195);
|
||||
public static readonly uint OtherServer = UiFormat.Rgb(150, 185, 235);
|
||||
public static readonly uint Stale = UiFormat.Rgb(225, 150, 80);
|
||||
public static readonly uint White = UiFormat.Rgb(255, 255, 255);
|
||||
/// <summary>The Lua script's amber (paused, full packs): 1.0, 0.75, 0.25.</summary>
|
||||
public static readonly uint Amber = UiFormat.Rgb(255, 191, 64);
|
||||
}
|
||||
202
Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs
Normal file
202
Plugins/RynthCore.Plugin.RynthThreads/Ui/UiHost.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's side of the engine's script windows (API v71): polls the engine's events into
|
||||
/// the windows' handlers and submits the window set when something changed. Plugin pump thread
|
||||
/// only (inside the plugin's own tick), as the engine requires.
|
||||
/// </summary>
|
||||
internal sealed class UiHost
|
||||
{
|
||||
private readonly List<UiWindow> _windows = new();
|
||||
private readonly Dictionary<uint, UiWindow> _byHash = new();
|
||||
private byte[] _events = new byte[8192];
|
||||
private byte[] _submit = new byte[64 * 1024];
|
||||
private uint _lastSeq;
|
||||
private bool _submittedSomething;
|
||||
private long _retryAtMs;
|
||||
private long _lastErrorLogMs;
|
||||
|
||||
public Action<string>? Log;
|
||||
|
||||
public IReadOnlyList<UiWindow> Windows => _windows;
|
||||
|
||||
public UiWindow Add(UiWindow w)
|
||||
{
|
||||
_windows.Add(w);
|
||||
_byHash[w.Hash] = w;
|
||||
return w;
|
||||
}
|
||||
|
||||
/// <summary>Drains the engine's queued events into the windows' handlers.</summary>
|
||||
public void Poll(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
for (int round = 0; round < 8; round++)
|
||||
{
|
||||
int n = host.UiPollEvents(_events, out int remaining);
|
||||
if (n > 0) Apply(_events.AsSpan(0, n));
|
||||
if (remaining == 0) break;
|
||||
if (n == 0) Array.Resize(ref _events, _events.Length * 2); // one event didn't fit
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(ReadOnlySpan<byte> data)
|
||||
{
|
||||
int pos = 0;
|
||||
while (data.Length - pos >= 16)
|
||||
{
|
||||
ushort type = BinaryPrimitives.ReadUInt16LittleEndian(data[pos..]);
|
||||
int size = BinaryPrimitives.ReadUInt16LittleEndian(data[(pos + 2)..]);
|
||||
if (size < 16 || size > data.Length - pos) break;
|
||||
uint seq = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 4)..]);
|
||||
uint window = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 8)..]);
|
||||
uint key = BinaryPrimitives.ReadUInt32LittleEndian(data[(pos + 12)..]);
|
||||
ReadOnlySpan<byte> p = data.Slice(pos + 16, size - 16);
|
||||
pos += size;
|
||||
if (seq > _lastSeq) _lastSeq = seq;
|
||||
|
||||
_byHash.TryGetValue(window, out UiWindow? w);
|
||||
switch (type)
|
||||
{
|
||||
case UiFormat.EvClicked when w != null && p.Length >= 2:
|
||||
int count = BinaryPrimitives.ReadUInt16LittleEndian(p);
|
||||
for (int i = 0; i < Math.Min(count, 4); i++) w.Dispatch(key, new UiEvent(type));
|
||||
break;
|
||||
case UiFormat.EvBool when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvInt when w != null && p.Length >= 4:
|
||||
w.Dispatch(key, new UiEvent(type, i: BinaryPrimitives.ReadInt32LittleEndian(p)));
|
||||
break;
|
||||
case UiFormat.EvText when w != null && p.Length >= 3:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p[1..]), p.Length - 3);
|
||||
w.Dispatch(key, new UiEvent(type, text: Encoding.UTF8.GetString(p.Slice(3, n)), submitted: p[0] != 0));
|
||||
break;
|
||||
}
|
||||
case UiFormat.EvOpen when w != null && p.Length >= 1:
|
||||
w.Dispatch(key, new UiEvent(type, b: p[0] != 0));
|
||||
break;
|
||||
case UiFormat.EvVisibility when w != null && p.Length >= 1:
|
||||
// The player closed it (X) or opened it (bar menu / command): theirs wins.
|
||||
w.Visible = p[0] != 0;
|
||||
w.NeedsPass = true;
|
||||
break;
|
||||
case UiFormat.EvError when p.Length >= 2:
|
||||
{
|
||||
int n = Math.Min(BinaryPrimitives.ReadUInt16LittleEndian(p), p.Length - 2);
|
||||
Log?.Invoke("[RynthThreads] window error: " + Encoding.UTF8.GetString(p.Slice(2, n)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sends the window set when any window's list or header changed.</summary>
|
||||
public void Submit(RynthCoreHost host, long nowMs)
|
||||
{
|
||||
if (!host.HasUi || nowMs < _retryAtMs) return;
|
||||
bool changed = !_submittedSomething && _windows.Count > 0;
|
||||
foreach (UiWindow w in _windows)
|
||||
if (w.BodyDirty || w.HeaderDirty) { changed = true; break; }
|
||||
if (!changed) return;
|
||||
|
||||
int pos = Write();
|
||||
int rc = host.UiSubmit(_submit.AsSpan(0, pos));
|
||||
if (rc == 0)
|
||||
{
|
||||
foreach (UiWindow w in _windows) w.MarkSubmitted(w.BodyDirty);
|
||||
_submittedSomething = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nothing was applied; the engine keeps the previous lists. Try again in a second.
|
||||
_retryAtMs = nowMs + 1000;
|
||||
if (nowMs - _lastErrorLogMs > 10_000)
|
||||
{
|
||||
_lastErrorLogMs = nowMs;
|
||||
Log?.Invoke($"[RynthThreads] the engine refused the window list ({rc}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Removes every window from the engine (logout, shutdown). Their placement is kept by the engine.</summary>
|
||||
public void SubmitEmpty(RynthCoreHost host)
|
||||
{
|
||||
if (!host.HasUi || !_submittedSomething) return;
|
||||
Span<byte> b = stackalloc byte[16];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], 16);
|
||||
if (host.UiSubmit(b) == 0)
|
||||
{
|
||||
_submittedSomething = false;
|
||||
foreach (UiWindow w in _windows) w.ForgetSubmitted();
|
||||
}
|
||||
}
|
||||
|
||||
private int Write()
|
||||
{
|
||||
int size = 16;
|
||||
foreach (UiWindow w in _windows) size += 2 * (1 + UiFormat.MaxStr8) + 4 + 32 + 8 + (w.BodyDirty ? w.Body.Length : 0);
|
||||
if (_submit.Length < size) _submit = new byte[Math.Max(size, _submit.Length * 2)];
|
||||
Span<byte> b = _submit;
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, UiFormat.Magic);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[4..], UiFormat.FormatVersion);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b[6..], (ushort)_windows.Count);
|
||||
// Every event polled so far has been applied (handlers run as they arrive).
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[8..], _lastSeq);
|
||||
int pos = 16;
|
||||
foreach (UiWindow w in _windows)
|
||||
{
|
||||
pos = Str8(b, pos, w.KeyUtf8);
|
||||
pos = Str8(b, pos, Encoding.UTF8.GetBytes(w.Title ?? string.Empty));
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.Flags); pos += 4;
|
||||
pos = F32(b, pos, w.DefaultWidth);
|
||||
pos = F32(b, pos, w.DefaultHeight);
|
||||
pos = F32(b, pos, w.MinWidth);
|
||||
pos = F32(b, pos, w.MinHeight);
|
||||
pos = F32(b, pos, float.NaN); // RequestSize: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
pos = F32(b, pos, float.NaN); // RequestPos: none
|
||||
pos = F32(b, pos, float.NaN);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], w.ListSeq); pos += 4;
|
||||
if (w.BodyDirty)
|
||||
{
|
||||
ReadOnlySpan<byte> body = w.Body;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], (uint)body.Length); pos += 4;
|
||||
body.CopyTo(b[pos..]);
|
||||
pos += body.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[pos..], UiFormat.BodyUnchanged); pos += 4;
|
||||
}
|
||||
}
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b[12..], (uint)pos);
|
||||
return pos;
|
||||
}
|
||||
|
||||
private static int Str8(Span<byte> b, int pos, ReadOnlySpan<byte> s)
|
||||
{
|
||||
int n = UiFormat.CutUtf8(s, UiFormat.MaxStr8);
|
||||
b[pos] = (byte)n;
|
||||
s[..n].CopyTo(b[(pos + 1)..]);
|
||||
return pos + 1 + n;
|
||||
}
|
||||
|
||||
private static int F32(Span<byte> b, int pos, float v)
|
||||
{
|
||||
BinaryPrimitives.WriteSingleLittleEndian(b[pos..], v);
|
||||
return pos + 4;
|
||||
}
|
||||
}
|
||||
515
Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs
Normal file
515
Plugins/RynthCore.Plugin.RynthThreads/Ui/UiWindow.cs
Normal file
|
|
@ -0,0 +1,515 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Ui;
|
||||
|
||||
/// <summary>One input from the engine for a widget (a click, a new value, an open state).</summary>
|
||||
internal readonly struct UiEvent
|
||||
{
|
||||
public readonly ushort Type;
|
||||
public readonly bool Bool;
|
||||
public readonly int Int;
|
||||
public readonly string Text;
|
||||
public readonly bool Submitted;
|
||||
|
||||
public UiEvent(ushort type, bool b = false, int i = 0, string? text = null, bool submitted = false)
|
||||
{
|
||||
Type = type;
|
||||
Bool = b;
|
||||
Int = i;
|
||||
Text = text ?? string.Empty;
|
||||
Submitted = submitted;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One script window (engine API v71) and its recorder. A render pass records ImGui-style calls
|
||||
/// into a display list; every widget's handler (click, value change) is kept by its widget key
|
||||
/// until the next pass, so an event from the engine runs the code that drew that widget.
|
||||
///
|
||||
/// Widget keys are FNV-1a(id, window hash): RynthThreads names every widget itself, so it needs
|
||||
/// no ID stack. ImGui sees "label###id": its ID comes from the id alone, so labels can change.
|
||||
/// The engine echoes the key in events and keys its per-widget local values by it.
|
||||
/// </summary>
|
||||
internal sealed class UiWindow
|
||||
{
|
||||
public readonly string Key;
|
||||
public readonly byte[] KeyUtf8;
|
||||
public readonly uint Hash;
|
||||
|
||||
public string Title;
|
||||
public bool Visible;
|
||||
public bool ShowInBar = true;
|
||||
/// <summary>With ShowInBar: the window has its own button on the RynthCore bar (title as the
|
||||
/// tooltip) rather than a line in the Scripts menu.</summary>
|
||||
public bool BarButton = true;
|
||||
public float DefaultWidth, DefaultHeight, MinWidth, MinHeight;
|
||||
|
||||
/// <summary>A pass is wanted at the next chance (input arrived, it was just shown, data changed).</summary>
|
||||
public bool NeedsPass = true;
|
||||
public long NextPassMs;
|
||||
|
||||
// The list as recorded by the last pass, and what the engine last accepted.
|
||||
private byte[] _body = new byte[16 * 1024];
|
||||
private int _len;
|
||||
private int _ops;
|
||||
private bool _cut;
|
||||
private byte[] _sentBody = Array.Empty<byte>();
|
||||
private int _sentLen = -1;
|
||||
public uint ListSeq { get; private set; }
|
||||
internal bool BodyDirty;
|
||||
|
||||
// Header as last accepted by the engine.
|
||||
private string? _sentTitle;
|
||||
private uint _sentFlags;
|
||||
private float _sentDw = float.NaN, _sentDh, _sentMw, _sentMh;
|
||||
|
||||
private Dictionary<uint, Action<UiEvent>> _handlers = new();
|
||||
private Dictionary<uint, Action<UiEvent>> _next = new();
|
||||
private readonly Dictionary<uint, bool> _openStates = new();
|
||||
|
||||
// Child blocks: where each open block's u32 length sits, or -1 when the block was dropped.
|
||||
private readonly int[] _blocks = new int[16];
|
||||
private int _blockDepth;
|
||||
private byte[] _tmp = new byte[512];
|
||||
|
||||
public UiWindow(string key, string title)
|
||||
{
|
||||
Key = key;
|
||||
KeyUtf8 = Encoding.UTF8.GetBytes(key);
|
||||
Hash = UiFormat.Fnv1a(KeyUtf8);
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public uint Flags => (Visible ? UiFormat.FlagVisible : 0) | (ShowInBar ? UiFormat.FlagShowInBar : 0)
|
||||
| (ShowInBar && BarButton ? UiFormat.FlagBarButton : 0);
|
||||
|
||||
public bool HeaderDirty =>
|
||||
_sentTitle != Title || _sentFlags != Flags || _sentDw != DefaultWidth || _sentDh != DefaultHeight
|
||||
|| _sentMw != MinWidth || _sentMh != MinHeight;
|
||||
|
||||
public ReadOnlySpan<byte> Body => _body.AsSpan(0, _len);
|
||||
|
||||
// ── Pass ────────────────────────────────────────────────────────────────
|
||||
|
||||
public void Begin()
|
||||
{
|
||||
_len = 0;
|
||||
_ops = 0;
|
||||
_cut = false;
|
||||
_blockDepth = 0;
|
||||
_next.Clear();
|
||||
}
|
||||
|
||||
/// <summary>Ends the pass: closes open blocks, writes End, and notes whether the list changed.</summary>
|
||||
public void End()
|
||||
{
|
||||
while (_blockDepth > 0) EndChild();
|
||||
if (_cut)
|
||||
{
|
||||
// Room was kept for this line (see Room).
|
||||
int p = BeginOp(UiFormat.OpTextDisabled);
|
||||
Str("(more than fits in one window; narrow the list)");
|
||||
EndOp(p);
|
||||
}
|
||||
Ensure(4);
|
||||
_body[_len++] = UiFormat.OpEnd;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
_body[_len++] = 0;
|
||||
|
||||
(_handlers, _next) = (_next, _handlers);
|
||||
bool differs = _sentLen != _len || !_body.AsSpan(0, _len).SequenceEqual(_sentBody.AsSpan(0, _sentLen));
|
||||
if (differs && !BodyDirty) ListSeq++;
|
||||
BodyDirty = differs;
|
||||
}
|
||||
|
||||
/// <summary>The engine accepted the last submit: remember what it now has.</summary>
|
||||
internal void MarkSubmitted(bool bodySent)
|
||||
{
|
||||
if (bodySent)
|
||||
{
|
||||
if (_sentBody.Length < _len) _sentBody = new byte[_body.Length];
|
||||
_body.AsSpan(0, _len).CopyTo(_sentBody);
|
||||
_sentLen = _len;
|
||||
BodyDirty = false;
|
||||
}
|
||||
_sentTitle = Title;
|
||||
_sentFlags = Flags;
|
||||
_sentDw = DefaultWidth; _sentDh = DefaultHeight; _sentMw = MinWidth; _sentMh = MinHeight;
|
||||
}
|
||||
|
||||
/// <summary>The engine dropped every window (logout, empty submit): send everything again next time.</summary>
|
||||
internal void ForgetSubmitted()
|
||||
{
|
||||
_sentLen = -1;
|
||||
_sentTitle = null;
|
||||
BodyDirty = _len > 0;
|
||||
}
|
||||
|
||||
internal void Dispatch(uint widgetKey, in UiEvent e)
|
||||
{
|
||||
if (_handlers.TryGetValue(widgetKey, out Action<UiEvent>? h))
|
||||
h(e);
|
||||
NeedsPass = true;
|
||||
}
|
||||
|
||||
// ── Widgets ─────────────────────────────────────────────────────────────
|
||||
|
||||
public uint KeyOf(string id)
|
||||
{
|
||||
int max = Encoding.UTF8.GetMaxByteCount(id.Length);
|
||||
if (_tmp.Length < max) _tmp = new byte[Math.Max(max, _tmp.Length * 2)];
|
||||
int n = Encoding.UTF8.GetBytes(id, _tmp);
|
||||
return UiFormat.Fnv1a(_tmp.AsSpan(0, n), Hash);
|
||||
}
|
||||
|
||||
public void Text(string text) => WriteText(UiFormat.OpText, text);
|
||||
public void TextDisabled(string text) => WriteText(UiFormat.OpTextDisabled, text);
|
||||
public void TextWrapped(string text) => WriteText(UiFormat.OpTextWrapped, text);
|
||||
public void BulletText(string text) => WriteText(UiFormat.OpBulletText, text);
|
||||
public void SeparatorText(string text) => WriteText(UiFormat.OpSeparatorText, text);
|
||||
|
||||
public void TextColored(uint abgr, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpTextColored);
|
||||
U32(abgr);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Separator()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSeparator));
|
||||
}
|
||||
|
||||
public void Spacing()
|
||||
{
|
||||
if (!Room()) return;
|
||||
EndOp(BeginOp(UiFormat.OpSpacing));
|
||||
}
|
||||
|
||||
/// <summary>Next item on the same line, <paramref name="x"/> logical units from the content start (0 = right after).</summary>
|
||||
public void SameLine(float x = 0f, float spacing = -1f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpSameLine);
|
||||
F32(x);
|
||||
F32(spacing);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Dummy(float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpDummy);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Moves the following items right by <paramref name="w"/> logical units, until <see cref="Unindent"/>.</summary>
|
||||
public void Indent(float w)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpIndent);
|
||||
F32(w);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Unindent(float w)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpUnindent);
|
||||
F32(w);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void Button(string label, string id, Action onClick, float w = 0f, float h = 0f, bool small = false)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpButton);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(small ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void SmallButton(string label, string id, Action onClick) => Button(label, id, onClick, small: true);
|
||||
|
||||
/// <summary>A button drawn highlighted when <paramref name="active"/> (tabs, toggles).</summary>
|
||||
public void ToggleButton(string label, string id, bool active, Action onClick, bool small = false)
|
||||
{
|
||||
if (active)
|
||||
{
|
||||
PushStyleColor(UiFormat.ColButton, UiColors.TabActive);
|
||||
PushStyleColor(UiFormat.ColButtonHovered, UiColors.TabActiveHover);
|
||||
}
|
||||
Button(label, id, onClick, small: small);
|
||||
if (active) PopStyleColor(2);
|
||||
}
|
||||
|
||||
public void Checkbox(string label, string id, bool value, Action<bool> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpCheckbox);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(value ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvBool) set(e.Bool); };
|
||||
}
|
||||
|
||||
/// <summary>An integer slider from <paramref name="min"/> to <paramref name="max"/> (clamped by the engine).</summary>
|
||||
public void SliderInt(string label, string id, int value, int min, int max, Action<int> set, string format = "%d")
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSliderInt);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(value);
|
||||
I32(min);
|
||||
I32(max);
|
||||
Str(format);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(Math.Clamp(e.Int, min, max)); };
|
||||
}
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit (submitted = Enter was pressed).</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string> set, uint flags = 0) =>
|
||||
InputText(label, id, value, maxLen, (text, _) => set(text), flags);
|
||||
|
||||
/// <summary>A text box; <paramref name="set"/> gets every edit and whether Enter was pressed.</summary>
|
||||
public void InputText(string label, string id, string value, int maxLen, Action<string, bool> set, uint flags = 0)
|
||||
{
|
||||
if (!Room()) return;
|
||||
maxLen = Math.Clamp(maxLen, 1, UiFormat.MaxString);
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpInputText);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
Str(value ?? string.Empty, maxLen);
|
||||
U16((ushort)maxLen);
|
||||
U32(flags);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvText) set(e.Text, e.Submitted); };
|
||||
}
|
||||
|
||||
public void Combo(string label, string id, int index, IReadOnlyList<string> items, Action<int> set)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int count = Math.Min(items.Count, 512);
|
||||
int p = BeginOp(UiFormat.OpCombo);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
I32(index);
|
||||
U16((ushort)count);
|
||||
for (int i = 0; i < count; i++) Str(items[i]);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvInt) set(e.Int); };
|
||||
}
|
||||
|
||||
public void Selectable(string label, string id, bool selected, Action onClick, float w = 0f, float h = 0f)
|
||||
{
|
||||
if (!Room()) return;
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpSelectable);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U8(selected ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
F32(w);
|
||||
F32(h);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvClicked) onClick(); };
|
||||
}
|
||||
|
||||
public void ProgressBar(float fraction, float w, float h, string overlay)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpProgressBar);
|
||||
F32(float.IsFinite(fraction) ? Math.Clamp(fraction, 0f, 1f) : 0f);
|
||||
F32(w);
|
||||
F32(h);
|
||||
Str(overlay ?? string.Empty);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An icon (op level 2): <paramref name="kind"/> <see cref="UiFormat.IconKindIcon"/> = a 0x06
|
||||
/// texture id, <see cref="UiFormat.IconKindObject"/> = a live object. Engines without op level
|
||||
/// 2 skip it (the caller checks first so the layout doesn't shift).
|
||||
/// </summary>
|
||||
public void Image(byte kind, uint id, float w, float h)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpImage);
|
||||
U8(kind);
|
||||
U32(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
F32(0f); F32(0f); // uv0
|
||||
F32(1f); F32(1f); // uv1
|
||||
U32(0xFFFFFFFFu); // tint: as is
|
||||
U32(0u); // border: none
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Tooltip for the item just drawn.</summary>
|
||||
public void Tooltip(string text)
|
||||
{
|
||||
if (!Room() || string.IsNullOrEmpty(text)) return;
|
||||
int p = BeginOp(UiFormat.OpSetItemTooltip);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
public void PushStyleColor(int colId, uint abgr)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPushStyleColor);
|
||||
U16((ushort)colId);
|
||||
U32(abgr);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>Pops are dropped when the list is cut short; the engine pops leftovers at the scope's end.</summary>
|
||||
public void PopStyleColor(int count = 1)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(UiFormat.OpPopStyleColor);
|
||||
U8((byte)Math.Clamp(count, 1, 255));
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A collapsing header; returns whether to record its contents. The open state is the
|
||||
/// player's (kept from the engine's Open events), so a header stays as they left it.
|
||||
/// </summary>
|
||||
public bool CollapsingHeader(string label, string id, bool defaultOpen = false)
|
||||
{
|
||||
uint key = KeyOf(id);
|
||||
bool open = _openStates.TryGetValue(key, out bool o) ? o : defaultOpen;
|
||||
if (!Room()) return false;
|
||||
int p = BeginOp(UiFormat.OpCollapsingHeader);
|
||||
U32(key);
|
||||
Str(label + "###" + id);
|
||||
U32(defaultOpen ? UiFormat.TreeDefaultOpen : 0);
|
||||
U8(open ? (byte)1 : (byte)0);
|
||||
EndOp(p);
|
||||
_next[key] = e => { if (e.Type == UiFormat.EvOpen) _openStates[key] = e.Bool; };
|
||||
return open;
|
||||
}
|
||||
|
||||
/// <summary>A scrolling region; h 0 = fill the rest of the window. Must be closed with <see cref="EndChild"/>.</summary>
|
||||
public void BeginChild(string id, float w = 0f, float h = 0f, bool border = true)
|
||||
{
|
||||
if (_blockDepth >= _blocks.Length) throw new InvalidOperationException("child regions nested too deep");
|
||||
if (!Room())
|
||||
{
|
||||
_blocks[_blockDepth++] = -1;
|
||||
return;
|
||||
}
|
||||
uint key = KeyOf(id);
|
||||
int p = BeginOp(UiFormat.OpChild, UiFormat.OpHasBlock);
|
||||
U32(key);
|
||||
Str(id);
|
||||
F32(w);
|
||||
F32(h);
|
||||
U8(border ? (byte)1 : (byte)0);
|
||||
U32(0);
|
||||
EndOp(p);
|
||||
_blocks[_blockDepth++] = _len;
|
||||
U32(0); // BlockLength, patched by EndChild
|
||||
}
|
||||
|
||||
public void EndChild()
|
||||
{
|
||||
if (_blockDepth == 0) return;
|
||||
int at = _blocks[--_blockDepth];
|
||||
if (at < 0) return;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(at), (uint)(_len - (at + 4)));
|
||||
}
|
||||
|
||||
// ── Writing ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Whether another op fits. Room is kept for the closing "list cut short" line and the End
|
||||
/// op, so the list never goes over the engine's limits (it refuses an over-limit list whole).
|
||||
/// </summary>
|
||||
private bool Room()
|
||||
{
|
||||
if (_cut) return false;
|
||||
if (_ops < UiFormat.MaxOps - 8 && _len < UiFormat.MaxBodyBytes - 4096) return true;
|
||||
_cut = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private void WriteText(byte code, string text)
|
||||
{
|
||||
if (!Room()) return;
|
||||
int p = BeginOp(code);
|
||||
Str(text);
|
||||
EndOp(p);
|
||||
}
|
||||
|
||||
private int BeginOp(byte code, byte opFlags = 0)
|
||||
{
|
||||
_ops++;
|
||||
Ensure(4);
|
||||
_body[_len++] = code;
|
||||
_body[_len++] = opFlags;
|
||||
_len += 2; // PayloadLength, patched by EndOp
|
||||
return _len;
|
||||
}
|
||||
|
||||
private void EndOp(int payloadStart)
|
||||
{
|
||||
int length = _len - payloadStart;
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(payloadStart - 2), (ushort)Math.Min(length, ushort.MaxValue));
|
||||
}
|
||||
|
||||
private void Ensure(int extra)
|
||||
{
|
||||
if (_len + extra <= _body.Length) return;
|
||||
int size = _body.Length;
|
||||
while (size < _len + extra) size *= 2;
|
||||
Array.Resize(ref _body, size);
|
||||
}
|
||||
|
||||
private void U8(byte v) { Ensure(1); _body[_len++] = v; }
|
||||
private void U16(ushort v) { Ensure(2); BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), v); _len += 2; }
|
||||
private void U32(uint v) { Ensure(4); BinaryPrimitives.WriteUInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
private void I32(int v) { Ensure(4); BinaryPrimitives.WriteInt32LittleEndian(_body.AsSpan(_len), v); _len += 4; }
|
||||
|
||||
private void F32(float v)
|
||||
{
|
||||
Ensure(4);
|
||||
BinaryPrimitives.WriteSingleLittleEndian(_body.AsSpan(_len), float.IsFinite(v) ? v : 0f);
|
||||
_len += 4;
|
||||
}
|
||||
|
||||
/// <summary>str: u16 length + UTF-8, cut to <paramref name="maxBytes"/> on a character boundary.</summary>
|
||||
private void Str(string s, int maxBytes = UiFormat.MaxString)
|
||||
{
|
||||
s ??= string.Empty;
|
||||
ReadOnlySpan<char> src = s.Length > maxBytes ? s.AsSpan(0, maxBytes) : s.AsSpan();
|
||||
Ensure(2 + Encoding.UTF8.GetMaxByteCount(src.Length));
|
||||
int at = _len + 2;
|
||||
Span<byte> dst = _body.AsSpan(at);
|
||||
int n = UiFormat.CutUtf8(dst[..Encoding.UTF8.GetBytes(src, dst)], maxBytes);
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(_body.AsSpan(_len), (ushort)n);
|
||||
_len = at + n;
|
||||
}
|
||||
}
|
||||
186
Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs
Normal file
186
Plugins/RynthCore.Plugin.RynthThreads/Views/ThreadsPanel.cs
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using RynthCore.Plugin.RynthThreads.Threads;
|
||||
using RynthCore.Plugin.RynthThreads.Ui;
|
||||
|
||||
namespace RynthCore.Plugin.RynthThreads.Views;
|
||||
|
||||
/// <summary>
|
||||
/// The RynthThreads window: a summary line and Export, then three tabs. Components: All presses
|
||||
/// (the baseline), each component, each exact combination and No components, each opening to the
|
||||
/// rate of every modifier seen in its presses (hits/presses, a 95% range while few, the rate
|
||||
/// without it), modifiers per press and the results. Modifiers: each one's overall rate, its rate
|
||||
/// with each component, its values by fragment level. Presses: the newest first, each opening to
|
||||
/// its modifiers and raw chat lines.
|
||||
/// Recorded on the pump thread, replayed by the engine.
|
||||
/// </summary>
|
||||
internal sealed class ThreadsPanel
|
||||
{
|
||||
private enum Tab { Components, Modifiers, Presses }
|
||||
|
||||
private const int MaxPressesShown = 60;
|
||||
private Tab _tab = Tab.Components;
|
||||
|
||||
public Func<ThreadsReport> Report = () => new ThreadsReport();
|
||||
public Func<IReadOnlyList<Press>> Presses = () => Array.Empty<Press>();
|
||||
public Action Export = () => { };
|
||||
/// <summary>Extra status (pending writes, unreadable lines), or "".</summary>
|
||||
public Func<string> Notice = () => string.Empty;
|
||||
|
||||
public void Draw(UiWindow w)
|
||||
{
|
||||
ThreadsReport r = Report();
|
||||
w.Text($"{r.Total} press{(r.Total == 1 ? "" : "es")}, {r.Usable} complete" + (r.Incomplete > 0 ? $", {r.Incomplete} incomplete" : "")
|
||||
+ $" ({r.Characters} character{(r.Characters == 1 ? "" : "s")})");
|
||||
w.SameLine();
|
||||
w.SmallButton("Export CSV", "export", Export);
|
||||
w.Tooltip("Writes every press to a CSV file next to presses.jsonl (the folder is named in chat)");
|
||||
string notice = Notice();
|
||||
if (notice.Length > 0) w.TextColored(UiColors.Amber, notice);
|
||||
|
||||
w.ToggleButton("Components", "tab.c", _tab == Tab.Components, () => _tab = Tab.Components, small: true);
|
||||
w.SameLine();
|
||||
w.ToggleButton("Modifiers", "tab.m", _tab == Tab.Modifiers, () => _tab = Tab.Modifiers, small: true);
|
||||
w.SameLine();
|
||||
w.ToggleButton("Presses", "tab.p", _tab == Tab.Presses, () => _tab = Tab.Presses, small: true);
|
||||
w.Separator();
|
||||
|
||||
w.BeginChild("body", 0f, 0f, border: false);
|
||||
if (r.Total == 0)
|
||||
w.TextWrapped("No presses yet. Press a Raw Fragment at a Fragment Press: the result is read from chat and saved for every character on this PC.");
|
||||
else if (_tab == Tab.Components) DrawComponents(w, r);
|
||||
else if (_tab == Tab.Modifiers) DrawModifiers(w, r);
|
||||
else DrawPresses(w);
|
||||
w.EndChild();
|
||||
}
|
||||
|
||||
// ── Components ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void DrawComponents(UiWindow w, ThreadsReport r)
|
||||
{
|
||||
w.TextWrapped("Each component gives a chance of each modifier. Rates are how often it came: hits/presses, "
|
||||
+ "with a 95% range while presses are few, and the rate without the component to compare.");
|
||||
if (r.All is { } all) DrawGroup(w, all, "c:(all)");
|
||||
if (r.Components.Count == 0)
|
||||
w.TextDisabled("No complete press with a component yet.");
|
||||
foreach (GroupReport c in r.Components) DrawGroup(w, c, "c:" + c.Name);
|
||||
foreach (GroupReport c in r.Combinations) DrawGroup(w, c, "k:" + c.Name);
|
||||
if (r.NoComponents is { } nc) DrawGroup(w, nc, "c:(none)");
|
||||
}
|
||||
|
||||
private static void DrawGroup(UiWindow w, GroupReport g, string id)
|
||||
{
|
||||
if (!w.CollapsingHeader($"{g.Name} ({g.Presses} press{(g.Presses == 1 ? "" : "es")})", id)) return;
|
||||
w.Indent(8f);
|
||||
if (g.Kind == GroupKind.All) w.TextDisabled("Every complete press: the baseline.");
|
||||
else if (g.Kind == GroupKind.Combination) w.TextDisabled("Presses with exactly these components.");
|
||||
else if (g.Kind == GroupKind.NoComponents) w.TextDisabled("The plain random draw: no component used.");
|
||||
w.TextDisabled(PressInference.ModifiersText(g));
|
||||
w.TextDisabled("Results: " + PressInference.ResultsText(g));
|
||||
foreach (Odds o in g.Odds) DrawOdds(w, PressInference.Display(o.Modifier), o, g);
|
||||
w.Unindent(8f);
|
||||
}
|
||||
|
||||
/// <summary>"Guarded 75% (3/4, 30-95%); without: no data; x1.83 to x1.91", green when more likely.</summary>
|
||||
private static void DrawOdds(UiWindow w, string label, Odds o, GroupReport g)
|
||||
{
|
||||
var parts = new List<string> { $"{label} {PressInference.OddsText(o)}" };
|
||||
string other = PressInference.OtherText(o, g.OtherLabel);
|
||||
if (other.Length > 0) parts.Add(other);
|
||||
if (o.Values.Length > 0) parts.Add(o.Values);
|
||||
string likely = PressInference.LikelyText(o, g);
|
||||
if (likely.Length > 0) parts.Add(likely);
|
||||
string line = string.Join("; ", parts);
|
||||
if (likely.Length > 0)
|
||||
{
|
||||
w.PushStyleColor(UiFormat.ColText, UiColors.Green);
|
||||
w.BulletText(line);
|
||||
w.PopStyleColor();
|
||||
}
|
||||
else w.BulletText(line);
|
||||
if (o.IsGroup && o.Split.Count > 0) w.TextDisabled(" " + PressInference.SplitText(o));
|
||||
}
|
||||
|
||||
// ── Modifiers ───────────────────────────────────────────────────────────
|
||||
|
||||
private static void DrawModifiers(UiWindow w, ThreadsReport r)
|
||||
{
|
||||
if (r.Modifiers.Count == 0) w.TextDisabled("No complete press yet.");
|
||||
foreach (ModifierReport m in r.Modifiers)
|
||||
{
|
||||
string tag = m.Tag.Length > 0 ? " [" + m.Tag + "]" : "";
|
||||
if (!w.CollapsingHeader($"{PressInference.Display(m.Name)} {PressInference.OddsText(m.Overall)}{tag}", "m:" + m.Name)) continue;
|
||||
w.Indent(8f);
|
||||
w.TextWrapped(m.Example);
|
||||
w.Text("All presses: " + PressInference.OddsText(m.Overall));
|
||||
if (m.NoComponents is { } nc && r.NoComponents is { } ncg) DrawOdds(w, "No components", nc, ncg);
|
||||
if (m.ByGroup.Count > 0)
|
||||
{
|
||||
w.SeparatorText("By component");
|
||||
foreach (var (g, o) in m.ByGroup) DrawOdds(w, g.Name, o, g);
|
||||
}
|
||||
if (m.IsGroup && m.Overall.Split.Count > 0)
|
||||
{
|
||||
w.SeparatorText("By material");
|
||||
foreach (var (mat, hits) in m.Overall.Split)
|
||||
w.BulletText($"{mat}: {PressInference.OddsText(new Odds { Hits = hits, N = m.Overall.N })}");
|
||||
}
|
||||
if (m.Values.Length > 0) w.Text("Values: " + m.Values);
|
||||
if (m.ByLevel.Count > 1 || (m.ByLevel.Count == 1 && m.ByLevel[0].Level != null))
|
||||
{
|
||||
w.SeparatorText("By fragment level");
|
||||
foreach (var (level, count, values) in m.ByLevel)
|
||||
w.BulletText($"{(level?.ToString(CultureInfo.InvariantCulture) ?? "?")}: {(values.Length > 0 ? values : "-")} ({count} press{(count == 1 ? "" : "es")})");
|
||||
}
|
||||
w.Unindent(8f);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Presses ─────────────────────────────────────────────────────────────
|
||||
|
||||
private void DrawPresses(UiWindow w)
|
||||
{
|
||||
IReadOnlyList<Press> presses = Presses();
|
||||
int shown = 0;
|
||||
for (int i = presses.Count - 1; i >= 0 && shown < MaxPressesShown; i--, shown++)
|
||||
{
|
||||
Press p = presses[i];
|
||||
if (!w.CollapsingHeader(PressTitle(p), "p:" + p.Id)) continue;
|
||||
w.Indent(8f);
|
||||
w.TextDisabled($"{p.Character} on {p.Server}, {p.TimeUtc.ToLocalTime():yyyy-MM-dd HH:mm:ss}");
|
||||
if (p.Outcome.Length > 0) w.Text(p.Outcome);
|
||||
w.Text("Components: " + (p.ComponentsSeen ? p.ComponentsText : "(no line)"));
|
||||
foreach (GemModifier m in p.Modifiers) w.BulletText(m.Name + " - " + m.Description);
|
||||
if (p.ResultLevel != null || p.Entries != null)
|
||||
w.Text($"Level {p.ResultLevel?.ToString(CultureInfo.InvariantCulture) ?? "?"}, {p.Entries?.ToString(CultureInfo.InvariantCulture) ?? "?"} entries");
|
||||
if (!p.Complete) w.TextColored(UiColors.Amber, "Incomplete: " + EndText(p.End));
|
||||
w.SeparatorText("Chat lines");
|
||||
foreach (string line in p.Raw) w.TextDisabled(line);
|
||||
if (p.Extra.Count > 0)
|
||||
{
|
||||
w.SeparatorText("Other lines while it was open");
|
||||
foreach (string line in p.Extra) w.TextDisabled(line);
|
||||
}
|
||||
w.Unindent(8f);
|
||||
}
|
||||
if (presses.Count > MaxPressesShown)
|
||||
w.TextDisabled($"The newest {MaxPressesShown} of {presses.Count}; Export CSV has them all.");
|
||||
}
|
||||
|
||||
internal static string PressTitle(Press p)
|
||||
{
|
||||
string lvl = p.FragmentLevel?.ToString(CultureInfo.InvariantCulture) ?? "?";
|
||||
string to = p.ResultLevel != null ? " -> " + p.ResultLevel.Value.ToString(CultureInfo.InvariantCulture) : "";
|
||||
string state = p.Complete ? $"{p.Modifiers.Count} modifiers" : "incomplete";
|
||||
return $"{p.TimeUtc.ToLocalTime():MM-dd HH:mm} L{lvl}{to} {p.ComponentsText} ({state})";
|
||||
}
|
||||
|
||||
private static string EndText(string end) => end switch
|
||||
{
|
||||
"timeout" => "the press's lines stopped before its Level line",
|
||||
"next use" => "another item was used before its Level line",
|
||||
"logout" => "logged out before its Level line",
|
||||
_ => end,
|
||||
};
|
||||
}
|
||||
Loading…
Reference in a new issue