Snapshot for release 2026.10.31.1 (internal 69b244e)

This commit is contained in:
Tom Bohar 2026-10-31 15:01:58 -04:00
commit 2546497f37
122 changed files with 22896 additions and 170 deletions

View file

@ -0,0 +1,233 @@
// ============================================================================
// rynth-headless - Bot.cs
// One character in a multi-character run: its own socket, session, world model,
// plugin host (each plugin in its own load context, so two RynthAi instances don't
// share statics) and log; the geometry and spell table are shared by all bots.
//
// Life: connect -> in world (plugins get OnLoginComplete) -> its commands, 2 s apart ->
// runs until its stay time is up or the runner stops -> end commands, 3 s apart ->
// logout. A session that fails is retried (reconnect: 15 s, doubling to 5 min; an
// account still in use by a session being booted: 8 s).
// ============================================================================
using System.Text;
using RynthCore.Headless.Dat;
using RynthCore.Headless.Host;
using RynthCore.Headless.Host.Status;
using RynthCore.Headless.Movement;
using RynthCore.Headless.Net;
using RynthCore.Headless.Session;
namespace RynthCore.Headless.Cli;
internal sealed class Bot : IDisposable
{
private readonly RunConfig _run;
private readonly SessionConfig _cfg;
private readonly GeometryWalk? _geo;
private readonly SpellTable? _spells;
private readonly Action<string> _console;
private readonly StreamWriter _log;
private UdpLink? _link;
private ClientSession? _session;
private HostContext? _ctx;
private PluginHost? _plugins;
private HostBridge? _bridge;
private readonly StatusExporter? _status;
private readonly int _clientId;
private long _nextConnect, _inWorldAt = -1, _nextCommand, _nextEnd;
private int _commandIndex, _endIndex, _failures;
private bool _stopping, _loggingOut, _done;
public string Label => _cfg.Label;
public bool Done => _done;
public UdpLink? Link => _link;
public ClientSession? Session => _session;
public HostContext? Context => _ctx;
public int Failures => _failures;
public long InWorldSince => _inWorldAt;
/// <summary>The id its status files carry (RynthCore.&lt;id&gt;.*), stable across reconnects.</summary>
public int ClientId => _clientId;
public Bot(RunConfig run, SessionConfig cfg, int slot, GeometryWalk? geo, SpellTable? spells, Action<string> console)
{
_clientId = StatusExporter.MakeClientId(slot);
_run = run;
_cfg = cfg;
_geo = geo;
_spells = spells;
_console = console;
Directory.CreateDirectory(run.SuiteDir);
_log = new StreamWriter(Path.Combine(run.SuiteDir, $"headless-{Safe(cfg.Account)}.log"), append: true, Encoding.UTF8) { AutoFlush = true };
if (run.StatusDir.Length > 0)
_status = new StatusExporter(run.StatusDir, _clientId, cfg.Account) { ServerName = cfg.ServerName, LastCharacter = cfg.Character ?? "" };
}
private static string Safe(string s) => string.Concat(s.Select(c => char.IsLetterOrDigit(c) ? c : '_'));
private void Say(string s)
{
_log.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {s}");
_console($"[{Label}] {s}");
}
private void Note(string s) => _log.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {s}");
/// <summary>Asks the bot to finish: end commands, logout, done.</summary>
public void Stop() => _stopping = true;
public void Tick(long now)
{
if (_done) return;
if (_session == null)
{
_status?.Tick();
if (_stopping) { Finish(); return; }
if (now >= _nextConnect) Connect(now);
return;
}
_session.Tick();
_bridge?.Tick();
_status?.Tick();
if (_session.Finished)
{
Say($"session ended: {_session.State}{(_session.FailReason != null ? " - " + _session.FailReason : "")}; {_session.Stats}");
bool inUse = _session.FailReason == "character error 0x1";
bool failed = _session.State == SessionState.Failed;
TearDown();
if (_stopping || _loggingOut && !failed || !_cfg.Reconnect) { Finish(); return; }
_failures++;
long wait = inUse ? 8_000 : Math.Min(300_000, 15_000L << Math.Min(_failures - 1, 5));
_nextConnect = now + wait;
Say($"reconnecting in {wait / 1000} s");
return;
}
if (_session.State != SessionState.InWorld) return;
if (_inWorldAt < 0)
{
_inWorldAt = now;
_failures = 0;
_nextCommand = now + 4000;
Say($"in the world as {_session.World.PlayerObject?.Name ?? "?"}");
}
if (_commandIndex < _cfg.Commands.Count && now >= _nextCommand && !_stopping)
{
string cmd = _cfg.Commands[_commandIndex++];
Say($"command {cmd}: {(Invoke(cmd) ? "handled" : "refused")}");
_nextCommand = now + 2000;
}
bool timeUp = _cfg.StaySeconds > 0 && now - _inWorldAt > _cfg.StaySeconds * 1000L;
if ((timeUp || _stopping) && !_loggingOut)
{
if (_endIndex < _cfg.EndCommands.Count)
{
if (now >= _nextEnd)
{
string cmd = _cfg.EndCommands[_endIndex++];
Say($"end command {cmd}: {(Invoke(cmd) ? "handled" : "refused")}");
_nextEnd = now + 3000;
}
return;
}
if (now < _nextEnd) return;
_loggingOut = true;
_stopping = true;
Say("logging out");
_session.Logout();
}
}
private bool Invoke(string cmd)
{
if (_ctx != null && _plugins != null) return _ctx.ActInvokeChatParser(cmd);
_session!.Say(cmd);
return true;
}
private void Connect(long now)
{
string problem = $"environment variable {_cfg.PasswordEnv} is not set";
string? password = _cfg.LauncherProfileId.Length > 0 ? LauncherAccounts.TryGetPasswordById(_cfg.LauncherProfileId, out problem)
: _cfg.LauncherAccount.Length > 0 ? LauncherAccounts.TryGetPassword(_cfg.LauncherAccount, _cfg.Host, _cfg.ServerPort, out problem)
: Environment.GetEnvironmentVariable(_cfg.PasswordEnv);
if (string.IsNullOrEmpty(password))
{
Say($"no password: {problem}");
Finish();
return;
}
_link = UdpLink.Open(_cfg.Host, _cfg.ServerPort);
_session = ClientSession.Connect(_link, new SessionOptions
{
Account = _cfg.Account,
Character = _cfg.Character,
PickFirstCharacter = _cfg.Character == null,
});
_session.Log += Note;
_session.StateChanged += s => Note($"state: {s}");
// What the server refuses and where it sends us: a bot has no screen to show these on.
var w = _session.World;
w.InventoryFailed += (item, error) => Note($"[server] inventory move of 0x{item:X8} failed (error 0x{error:X})");
w.Error += (code, text) => Note($"[server] error 0x{code:X}{(text.Length > 0 ? ": " + text : "")}");
w.TransientMessage += text => Note($"[server] {text}");
w.PlayerMoveTo += m => Note($"[server] move-to type {m.MovementType}{(m.TargetId != 0 ? $" object 0x{m.TargetId:X8}" : "")} within {m.DistanceToObject:F1} m");
if (_geo != null)
{
_session.Walker = _geo;
_geo.TrackDoors(_session.World);
}
_ctx = new HostContext(_session, _cfg.Account, _geo, _spells) { LogSink = Note, TraceActions = true };
var plugins = _cfg.Plugins ?? _run.Plugins;
if (plugins.Count > 0)
{
_plugins = new PluginHost(_ctx);
foreach (string p in plugins)
Say($"plugin {Path.GetFileName(p)}: {(_plugins.Load(p) ? "loaded" : "FAILED")}");
_bridge = new HostBridge(_ctx, _plugins);
}
if (_status != null) _status.Context = _ctx;
_inWorldAt = -1;
_commandIndex = 0;
_endIndex = 0;
_loggingOut = false;
Say($"connecting to {_cfg.Host}:{_cfg.ServerPort}");
_session.Start(password);
}
private void TearDown()
{
if (_status != null) _status.Context = null;
_plugins?.Dispose();
_plugins = null;
_bridge = null;
_ctx = null;
_session = null;
_link?.Dispose();
_link = null;
_inWorldAt = -1;
}
private void Finish()
{
_done = true;
_status?.Retire();
}
public void Dispose()
{
if (_session is { Finished: false }) _session.Close("process exiting");
TearDown();
_status?.Retire();
_log.Dispose();
}
}

View file

@ -0,0 +1,28 @@
// ============================================================================
// rynth-headless - HeadlessDefaults.cs
// Where an installed rynth-headless keeps its files when the run config (or the
// launcher's HeadlessSuiteDir / HeadlessStatusDir) names no folder.
//
// Suite folder: %LOCALAPPDATA%\RynthCore\headless. It becomes RYNTHSUITE_DIR, so the
// headless plugins' data (RynthAi\ profiles, metas, loot profiles, logs) and the
// headless-<account>.log files live there. Per Windows user (the launcher's saved
// passwords are per user too), always writable without administrator rights, outside
// the install folder (an update or uninstall never touches it), and apart from the
// game clients' C:\Games\RynthSuite, so a headless RynthAi never writes the files a
// RynthAi in a game client is using.
// Status folder: <RynthCore>\Logs\status (C:\Games\RynthCore\Logs\status unless
// RYNTHCORE_DIR or the registry says otherwise), the folder the status files of the
// game clients use and the StatusAgent reads by default.
// ============================================================================
using RynthCore.Install;
namespace RynthCore.Headless.Cli;
internal static class HeadlessDefaults
{
public static string SuiteDir =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "headless");
public static string StatusDir => Path.Combine(RynthInstallPaths.CoreLogsDir, "status");
}

View file

@ -0,0 +1,75 @@
// ============================================================================
// rynth-headless - LauncherAccounts.cs
// Reads an account saved in the RynthCore launcher (%APPDATA%\RynthCore\appsettings.json)
// for the server we are connecting to, and decrypts its password (Windows DPAPI, this user
// only) at the moment of login. The password is never printed, logged or written.
// ============================================================================
using System.Text.Json;
using RynthCore.App;
namespace RynthCore.Headless.Cli;
internal static class LauncherAccounts
{
private static string SettingsPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "appsettings.json");
/// <summary>
/// The saved password for <paramref name="account"/> on host:port. Null with a reason when
/// the launcher has no such account for that server, or the password can't be decrypted.
/// </summary>
public static string? TryGetPassword(string account, string host, int port, out string problem)
{
problem = "";
if (!File.Exists(SettingsPath)) { problem = "no launcher settings"; return null; }
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(SettingsPath));
JsonElement root = doc.RootElement;
var serverIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (root.TryGetProperty("ServerProfiles", out JsonElement servers))
foreach (JsonElement s in servers.EnumerateArray())
if (string.Equals(Str(s, "Host"), host, StringComparison.OrdinalIgnoreCase)
&& s.TryGetProperty("Port", out JsonElement p) && p.TryGetInt32(out int sp) && sp == port)
serverIds.Add(Str(s, "Id"));
if (serverIds.Count == 0) { problem = $"the launcher has no server {host}:{port}"; return null; }
if (root.TryGetProperty("AccountProfiles", out JsonElement accounts))
{
foreach (JsonElement a in accounts.EnumerateArray())
{
if (!serverIds.Contains(Str(a, "ServerId"))
|| !string.Equals(Str(a, "AccountName"), account, StringComparison.OrdinalIgnoreCase))
continue;
if (AccountPasswordProtection.TryUnprotect(Str(a, "PasswordProtected"), out string pw))
return pw;
problem = "the saved password can't be decrypted on this Windows user";
return null;
}
}
problem = $"the launcher has no account {account} for {host}:{port}";
return null;
}
/// <summary>The saved password of the launcher account profile <paramref name="profileId"/>.</summary>
public static string? TryGetPasswordById(string profileId, out string problem)
{
problem = "";
if (!File.Exists(SettingsPath)) { problem = "no launcher settings"; return null; }
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(SettingsPath));
if (doc.RootElement.TryGetProperty("AccountProfiles", out JsonElement accounts))
foreach (JsonElement a in accounts.EnumerateArray())
{
if (!string.Equals(Str(a, "Id"), profileId, StringComparison.OrdinalIgnoreCase)) continue;
if (AccountPasswordProtection.TryUnprotect(Str(a, "PasswordProtected"), out string pw)) return pw;
problem = "the saved password can't be decrypted on this Windows user";
return null;
}
problem = $"the launcher has no account profile {profileId}";
return null;
}
private static string Str(JsonElement e, string name)
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
}

View file

@ -0,0 +1,83 @@
// ============================================================================
// rynth-headless - LauncherSession.cs
// `run --launcher`: what the engine's SessionStateRegistry does for an injected client,
// for the one character the launcher started this process for. It writes the launcher's
// %APPDATA%\RynthCore\sessions\session_<pid>.json (IsLoggedIn once in the world, LogoutAtUtc
// when it leaves) and the account's character cache from the server's character list, so the
// launcher's row and character dropdown work as they do for a retail client.
// ============================================================================
using System.Diagnostics;
using RynthCore.App;
using RynthCore.Headless.Session;
namespace RynthCore.Headless.Cli;
internal sealed class LauncherSession
{
private readonly string _account, _server, _target;
private readonly DateTime _startedUtc;
private ClientSession? _seen;
private bool _loggedIn, _cacheWritten;
private DateTime? _loginUtc;
private string _name = "";
public LauncherSession(RunConfig run, SessionConfig session)
{
_account = session.Account;
_server = session.ServerName;
_target = session.Character ?? "";
using (Process me = Process.GetCurrentProcess()) _startedUtc = me.StartTime.ToUniversalTime();
Write(loggedIn: false, character: "", logoutUtc: null);
}
public void Tick(Bot bot)
{
ClientSession? s = bot.Session;
if (!ReferenceEquals(s, _seen))
{
_seen = s;
_cacheWritten = false;
}
if (s != null && !_cacheWritten && s.Characters.Count > 0)
{
_cacheWritten = true;
Try(() => CharacterCacheStore.Write(_account, _server, s.Characters.Select(c => c.Name).ToList()));
}
bool inWorld = s?.State == SessionState.InWorld && s.World.PlayerObject != null;
if (inWorld && !_loggedIn)
{
_loggedIn = true;
_loginUtc = DateTime.UtcNow;
string name = _name = s!.World.PlayerObject!.Name;
Write(loggedIn: true, character: name, logoutUtc: null);
Try(() => CharacterCacheStore.UpsertCharacter(_account, _server, name));
}
else if (!inWorld && _loggedIn)
{
_loggedIn = false;
Write(loggedIn: false, character: _name, logoutUtc: DateTime.UtcNow);
}
}
private void Write(bool loggedIn, string character, DateTime? logoutUtc)
=> Try(() => SessionStateStore.WriteForProcess(Environment.ProcessId, new SessionStateRecord
{
AccountName = _account,
ServerName = _server,
TargetCharacter = _target,
CharacterName = character,
LaunchStartedAtUtc = _startedUtc,
LoginCompletedAtUtc = _loginUtc,
IsLoggedIn = loggedIn,
LogoutAtUtc = logoutUtc,
}));
private static void Try(Action a)
{
try { a(); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}

View file

@ -0,0 +1,312 @@
// ============================================================================
// rynth-headless - P0 protocol spike.
// Connects, logs in, enters the world as one character, prints chat and objects as
// they appear, says one line in local chat, then logs out cleanly.
//
// rynth-headless --host 127.0.0.1 --port 9000
// (--account NAME --password-env VAR | --launcher-account NAME)
// [--character NAME] [--say TEXT] [--stay SECONDS] [--objects] [--capture FILE]
//
// The password comes from the environment variable named by --password-env, or from the
// launcher's saved (DPAPI-encrypted) account; it is never printed, logged or written.
// ============================================================================
using RynthCore.Headless.Net;
using RynthCore.Headless.Session;
namespace RynthCore.Headless.Cli;
internal static class Program
{
private static int Main(string[] args)
{
// Several characters in one process: rynth-headless run --config bots.json
if (args.Length >= 1 && args[0] == "run")
{
int i = Array.IndexOf(args, "--config");
if (i < 0 || i + 1 >= args.Length) { Console.Error.WriteLine("usage: rynth-headless run --config FILE [--launcher] [--ac-folder DIR]"); return 2; }
int ac = Array.IndexOf(args, "--ac-folder");
return Runner.Run(args[i + 1], launcher: args.Contains("--launcher"), acFolder: ac >= 0 && ac + 1 < args.Length ? args[ac + 1] : null);
}
var a = ParseArgs(args);
if (a == null) return Usage();
// ACE boots a session already using the account and refuses the new login (character
// error 0x1) until that is done, so an account-in-use failure is retried.
for (int attempt = 1; ; attempt++)
{
int rc = RunOnce(a, out bool accountInUse);
if (!accountInUse || attempt == 3) return rc;
Console.WriteLine("account was in use; the server is booting the other session - retrying in 8 s");
Thread.Sleep(8000);
}
}
private static string? GetPassword(Args a)
{
if (a.PasswordEnv.Length > 0)
{
string? pw = Environment.GetEnvironmentVariable(a.PasswordEnv);
if (string.IsNullOrEmpty(pw)) Console.Error.WriteLine($"environment variable {a.PasswordEnv} is not set");
return string.IsNullOrEmpty(pw) ? null : pw;
}
string? saved = LauncherAccounts.TryGetPassword(a.Account, a.Host, a.Port, out string problem);
if (saved == null) Console.Error.WriteLine($"launcher account: {problem}");
return saved;
}
private static int RunOnce(Args a, out bool accountInUse)
{
accountInUse = false;
string? password = GetPassword(a);
if (password == null) return 2;
using UdpLink link = UdpLink.Open(a.Host, a.Port);
using StreamWriter? capture = a.CapturePath != null ? new StreamWriter(a.CapturePath) : null;
var captureClock = System.Diagnostics.Stopwatch.StartNew();
if (capture != null)
{
capture.WriteLine("# rynth-headless capture: <ms> <C|S> <hex datagram>. The LoginRequest (it holds the password) is left out.");
link.Tap = (outbound, d) =>
{
if (outbound && d.Length >= 8 && (System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(d.Slice(4)) & 0x00010000) != 0)
return;
capture.WriteLine($"{captureClock.ElapsedMilliseconds} {(outbound ? 'C' : 'S')} {Convert.ToHexString(d)}");
};
}
var clock = System.Diagnostics.Stopwatch.StartNew();
string T() => $"[{clock.Elapsed.TotalSeconds,7:F2}]";
var session = ClientSession.Connect(link, new SessionOptions { Account = a.Account, Character = a.Character, PickFirstCharacter = a.Character == null });
string? acFolder = RynthCore.Headless.Dat.DatFile.FindAcFolder();
using var geometry = acFolder != null ? RynthCore.Headless.Movement.GeometryWalk.Open(acFolder) : null;
if (geometry != null)
{
session.Walker = geometry;
geometry.TrackDoors(session.World);
}
// Plugins (P3): RynthCore plugins hosted headless, their data under --suite-dir.
RynthCore.Headless.Host.PluginHost? plugins = null;
RynthCore.Headless.Host.HostBridge? bridge = null;
StreamWriter? pluginLog = null;
if (a.Plugins.Count > 0)
{
Directory.CreateDirectory(a.SuiteDir);
Environment.SetEnvironmentVariable("RYNTHSUITE_DIR", a.SuiteDir);
pluginLog = new StreamWriter(Path.Combine(a.SuiteDir, "headless-plugins.log"), append: true) { AutoFlush = true };
RynthCore.Headless.Dat.SpellTable? spells = acFolder != null ? RynthCore.Headless.Dat.SpellTable.Load(acFolder, out _) : null;
var ctx = new RynthCore.Headless.Host.HostContext(session, a.Account, geometry, spells);
ctx.LogSink = line =>
{
pluginLog.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {line}");
if (line.StartsWith("[host]") || a.ShowPluginLog) Console.WriteLine($"{T()} {line}");
};
ctx.TraceActions = true;
session.ActionSent += (type, arg) => { if (type != 0xF753) ctx.Log($"[act] sent 0x{type:X4} 0x{arg:X8}"); };
session.World.Error += (code, text) => ctx.Log($"[act] WeenieError 0x{code:X} {text}");
session.World.InventoryFailed += (item, err) => ctx.Log($"[act] InventoryServerSaveFailed 0x{item:X8} 0x{err:X}");
session.World.ContainerOpened += id => ctx.Log($"[act] ViewContents 0x{id:X8}: {session.World.Contents(id).Count()} items ({string.Join(", ", session.World.Contents(id).Take(6).Select(o => o.Name.Length > 0 ? o.Name : $"0x{o.Id:X8}"))})");
plugins = new RynthCore.Headless.Host.PluginHost(ctx);
foreach (string pl in a.Plugins)
Console.WriteLine($"{T()} plugin {Path.GetFileName(pl)}: {(plugins.Load(pl) ? "loaded" : "FAILED")}");
bridge = new RynthCore.Headless.Host.HostBridge(ctx, plugins);
}
long nextCommand = -1, nextEnd = 0;
int endIndex = 0;
int commandIndex = 0;
Console.WriteLine(geometry != null ? $"walking on the dats in {acFolder}" : "no dats found: walking flat (no terrain, walls or cells)");
session.Log += s => Console.WriteLine($"{T()} {s}");
session.StateChanged += s => Console.WriteLine($"{T()} state: {s}");
session.Chat += c => Console.WriteLine($"{T()} chat[{c.ChatType:X2}] {(c.Sender.Length > 0 ? c.Sender + ": " : "")}{c.Text}");
int objects = 0;
session.ObjectCreated += o =>
{
objects++;
if (a.PrintObjects || objects <= 25)
Console.WriteLine($"{T()} + 0x{o.Id:X8} {o.Name} (wcid {o.WeenieClassId}, cell 0x{o.Cell:X8})");
else if (objects == 26)
Console.WriteLine($"{T()} ... (more objects; --objects prints all)");
};
bool stop = false;
Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop = true; };
Console.WriteLine($"{T()} connecting to {a.Host}:{a.Port} as {a.Account}");
session.Start(password);
password = null;
long inWorldAt = -1;
bool said = false, loggingOut = false, scenarioOk = true;
while (!session.Finished)
{
link.Wait(15);
session.Tick();
bridge?.Tick();
// --command lines go to the plugins (as if typed in the chat bar) once in the world, 2 s apart.
if (plugins != null && session.State == SessionState.InWorld && commandIndex < a.Commands.Count)
{
if (nextCommand < 0) nextCommand = clock.ElapsedMilliseconds + 4000;
if (clock.ElapsedMilliseconds >= nextCommand)
{
string cmd = a.Commands[commandIndex++];
// As if typed: plugins first, then on to the server (same route as the API's InvokeChatParser).
bool sent = plugins.Context.ActInvokeChatParser(cmd);
Console.WriteLine($"{T()} command {cmd}: {(sent ? "handled" : "refused")}");
nextCommand = clock.ElapsedMilliseconds + 2000;
}
}
if (session.State == SessionState.InWorld && inWorldAt < 0)
inWorldAt = clock.ElapsedMilliseconds;
if (a.Scenario != null && inWorldAt >= 0 && !said && clock.ElapsedMilliseconds - inWorldAt > 2000 && session.State == SessionState.InWorld)
{
said = true;
if (a.Scenario == "probe")
{
// Debug: say each --say line and list what the server sends for 6 s after it.
foreach (string line in a.Say.Split('|'))
{
var ops = new List<string>();
Action<uint, ReadOnlyMemory<byte>> tap = (op, m) =>
{
uint ev = op == 0xF7B0 && m.Length >= 16 ? System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(m.Span.Slice(12)) : 0;
if (ev != 0x1B4) ops.Add(op == 0xF7B0 ? $"ev{ev:X}" : $"{op:X}" + (m.Length >= 8 && op is 0xF745 or 0xF748 or 0xF74C or 0xF747 ? $"[{System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(m.Span.Slice(4)):X8}]" : ""));
};
session.RawMessage += tap;
Console.WriteLine($"{T()} probe: {line}");
if (line == "!pos" && session.World.PlayerObject?.Position is { } here) session.SendPosition(here);
else if (line.StartsWith("!drop ")) session.Drop(Convert.ToUInt32(line.Substring(6), 16));
else if (line == "!equipped")
foreach (var (eid, loc) in session.World.Player.EquippedItems)
Console.WriteLine($"{T()} equipped 0x{eid:X8} {session.World.Get(eid)?.Name} at 0x{loc:X}");
else if (line.StartsWith("!unwield ")) session.MoveItem(Convert.ToUInt32(line.Substring(9), 16), session.PlayerId, 0);
else if (line.StartsWith("!wield "))
{
string[] w = line.Split(' ');
session.Wield(Convert.ToUInt32(w[1], 16), Convert.ToUInt32(w[2], 16));
}
else if (line.StartsWith("!walk ") && session.World.PlayerObject?.Position is { } start)
{
// "!walk north east": metres relative to where we stand.
string[] d = line.Split(' ');
float n = float.Parse(d[1]), e = float.Parse(d[2]);
session.MoveFinished += (ok, why) => Console.WriteLine($"{T()} walk finished: {ok} ({why}), run rate {session.World.PlayerRunRate?.ToString("F2") ?? "?"}");
session.WalkTo(RynthCore.Headless.Session.ClientSession.Relocate(start, start.X + e, start.Y + n));
}
else session.Say(line);
long until = clock.ElapsedMilliseconds + 6000;
long nextTrace = 0;
while (clock.ElapsedMilliseconds < until)
{
link.Wait(15);
session.Tick();
if (session.Moving && clock.ElapsedMilliseconds >= nextTrace && session.World.PlayerObject?.Position is { } tp)
{
nextTrace = clock.ElapsedMilliseconds + 500;
Console.WriteLine($"{T()} at 0x{tp.Cell:X8} {tp.X:F1} {tp.Y:F1} {tp.Z:F1} speed {session.MoveSpeed:F1}");
}
}
session.RawMessage -= tap;
Console.WriteLine($"{T()} probe got: {string.Join(" ", ops)}");
}
}
else if (a.Scenario == "p2")
{
if (geometry == null) { Console.WriteLine("p2 needs the AC dats"); scenarioOk = false; }
else scenarioOk = new ScenarioP2(session, link, geometry, s => Console.WriteLine($"{T()} {s}")).Run();
}
else if (a.Scenario != "p1") { Console.WriteLine($"unknown scenario {a.Scenario}"); scenarioOk = false; }
else scenarioOk = new ScenarioP1(session, link, s => Console.WriteLine($"{T()} {s}")).Run();
loggingOut = true;
Console.WriteLine($"{T()} logging out");
session.Logout();
}
if (inWorldAt >= 0 && !said && clock.ElapsedMilliseconds - inWorldAt > 3000 && session.State == SessionState.InWorld)
{
if (a.Say.Length > 0)
{
Console.WriteLine($"{T()} saying: {a.Say}");
session.Say(a.Say);
}
said = true;
}
bool timeUp = inWorldAt >= 0 && clock.ElapsedMilliseconds - inWorldAt > a.StaySeconds * 1000L;
if ((timeUp || stop) && !loggingOut && plugins != null && endIndex < a.EndCommands.Count && session.State == SessionState.InWorld)
{
// --end-command lines (e.g. "/ra stop", a teleport home) go out first, 3 s apart.
if (clock.ElapsedMilliseconds >= nextEnd)
{
string cmd = a.EndCommands[endIndex++];
Console.WriteLine($"{T()} end command {cmd}: {(plugins.Context.ActInvokeChatParser(cmd) ? "handled" : "refused")}");
nextEnd = clock.ElapsedMilliseconds + 3000;
}
continue;
}
if ((timeUp || stop) && !loggingOut && clock.ElapsedMilliseconds >= nextEnd)
{
loggingOut = true;
Console.WriteLine($"{T()} logging out");
session.Logout();
}
}
Console.WriteLine($"{T()} done: {session.State}{(session.FailReason != null ? " - " + session.FailReason : "")}");
Console.WriteLine($"{T()} objects seen: {session.ObjectsSeen}; {session.Stats}");
plugins?.Dispose();
pluginLog?.Dispose();
accountInUse = session.FailReason == "character error 0x1";
return session.State == SessionState.Closed && session.FailReason == null && scenarioOk ? 0 : 1;
}
private sealed class Args
{
public string Host = "", Account = "", PasswordEnv = "", Say = "Hello from RynthCore.Headless";
public string? Character, CapturePath, Scenario;
public readonly List<string> Plugins = new(), Commands = new(), EndCommands = new();
public string SuiteDir = HeadlessDefaults.SuiteDir;
public bool ShowPluginLog, ShowChat;
public int Port = 9000, StaySeconds = 15;
public bool PrintObjects;
}
private static Args? ParseArgs(string[] args)
{
var a = new Args();
for (int i = 0; i < args.Length; i++)
{
string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"{args[i]} needs a value");
switch (args[i])
{
case "--host": a.Host = Next(); break;
case "--port": a.Port = int.Parse(Next()); break;
case "--account": a.Account = Next(); break;
case "--password-env": a.PasswordEnv = Next(); break;
case "--launcher-account": a.Account = Next(); a.PasswordEnv = ""; break;
case "--character": a.Character = Next(); break;
case "--say": a.Say = Next(); break;
case "--stay": a.StaySeconds = int.Parse(Next()); break;
case "--objects": a.PrintObjects = true; break;
case "--capture": a.CapturePath = Next(); break;
case "--scenario": a.Scenario = Next(); break;
case "--plugin": a.Plugins.Add(Next()); break;
case "--suite-dir": a.SuiteDir = Next(); break;
case "--command": a.Commands.Add(Next()); break;
case "--end-command": a.EndCommands.Add(Next()); break;
case "--plugin-log": a.ShowPluginLog = true; break;
default: return null;
}
}
return a.Host.Length > 0 && a.Account.Length > 0 ? a : null;
}
private static int Usage()
{
Console.Error.WriteLine(" rynth-headless run --config FILE (several characters, see RunConfig.cs)");
Console.Error.WriteLine("usage: rynth-headless --host HOST [--port 9000] (--account NAME --password-env VAR | --launcher-account NAME)");
Console.Error.WriteLine(" [--character NAME] [--say TEXT] [--stay SECONDS] [--objects] [--capture FILE] [--scenario p1|p2|probe]");
Console.Error.WriteLine(" --launcher-account uses the password saved in the RynthCore launcher for that account on HOST:PORT.");
Console.Error.WriteLine(" Without --character the first character on the account is used.");
return 2;
}
}

View file

@ -0,0 +1,84 @@
// ============================================================================
// rynth-headless - RunConfig.cs
// `rynth-headless run --config bots.json`: several characters in one process.
//
// {
// "host": "127.0.0.1", "port": 9000,
// "suiteDir": "D:\\Bots\\suite", // RYNTHSUITE_DIR for the plugins (left out = %LOCALAPPDATA%\RynthCore\headless)
// "statusDir": "D:\\Bots\\status", // per-character status files ("" = off; left out = <RynthCore>\Logs\status)
// "plugins": [ "C:\\...\\RynthCore.Plugin.RynthAi.dll" ], // loaded for every character
// "sessions": [
// { "launcherAccount": "myaccount", "character": "My Character",
// "commands": [ "/ra start" ], "endCommands": [ "/ra stop" ],
// "staySeconds": 0, "reconnect": true }
// ]
// }
// Each session needs "launcherAccount" (password saved in the RynthCore launcher for that
// account on host:port) or "account" + "passwordEnv" (an environment variable's name).
// Passwords are never read from the config file. staySeconds 0 = until stopped (Ctrl+C).
// ============================================================================
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Headless.Cli;
internal sealed class RunConfig
{
public string Host { get; set; } = "";
public int Port { get; set; } = 9000;
/// <summary>The server name status files report (the launcher's profile name); empty = the world name.</summary>
public string ServerName { get; set; } = "";
public string SuiteDir { get; set; } = HeadlessDefaults.SuiteDir;
public string StatusDir { get; set; } = HeadlessDefaults.StatusDir;
public List<string> Plugins { get; set; } = new();
public List<SessionConfig> Sessions { get; set; } = new();
public static RunConfig Load(string path)
{
var cfg = JsonSerializer.Deserialize<RunConfig>(File.ReadAllText(path), new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
}) ?? throw new InvalidDataException("empty config");
if (cfg.Sessions.Count == 0) throw new InvalidDataException("config: no sessions");
foreach (SessionConfig s in cfg.Sessions)
{
// A session's own server settings win; the top-level ones are the default.
s.Host = string.IsNullOrEmpty(s.Host) ? cfg.Host : s.Host;
s.Port ??= cfg.Port;
s.ServerName = string.IsNullOrEmpty(s.ServerName) ? cfg.ServerName : s.ServerName;
if (s.Host.Length == 0) throw new InvalidDataException($"config: session {s.Account} has no host (and there is no top-level host)");
if (s.Account.Length == 0) s.Account = s.LauncherAccount;
if (s.Account.Length == 0) throw new InvalidDataException("config: a session has neither launcherAccount nor account");
if (s.LauncherAccount.Length == 0 && s.LauncherProfileId.Length == 0 && s.PasswordEnv.Length == 0)
throw new InvalidDataException($"config: session {s.Account} needs launcherProfileId, launcherAccount or passwordEnv");
}
var dup = cfg.Sessions.GroupBy(s => $"{s.Account}@{s.Host}:{s.Port}", StringComparer.OrdinalIgnoreCase).FirstOrDefault(g => g.Count() > 1);
if (dup != null) throw new InvalidDataException($"config: account {dup.Key} appears twice (ACE allows one character in the world per account)");
return cfg;
}
}
internal sealed class SessionConfig
{
public string LauncherAccount { get; set; } = "";
/// <summary>This character's server, when it isn't the top-level one (one process can serve several).</summary>
public string Host { get; set; } = "";
public int? Port { get; set; }
public string ServerName { get; set; } = "";
[JsonIgnore] public int ServerPort => Port ?? 9000;
/// <summary>The launcher's account profile id (its saved password); what the launcher itself writes.</summary>
public string LauncherProfileId { get; set; } = "";
public string Account { get; set; } = "";
public string PasswordEnv { get; set; } = "";
public string? Character { get; set; }
public List<string> Commands { get; set; } = new();
public List<string> EndCommands { get; set; } = new();
public List<string>? Plugins { get; set; }
public int StaySeconds { get; set; }
public bool Reconnect { get; set; } = true;
[JsonIgnore] public string Label => Character ?? Account;
}

View file

@ -0,0 +1,94 @@
// ============================================================================
// rynth-headless - Runner.cs
// `rynth-headless run --config bots.json`: every configured character in this one
// process, ticked round-robin on one thread (each bot's session, bridge and plugins
// only ever run on it, as plugins expect). The thread sleeps until any bot's socket has
// data or 15 ms pass. Ctrl+C stops every bot cleanly (end commands, logout); a second
// Ctrl+C closes the sessions at once.
// ============================================================================
using System.Diagnostics;
using RynthCore.Headless.Dat;
using RynthCore.Headless.Movement;
using RynthCore.Headless.Net;
namespace RynthCore.Headless.Cli;
internal static class Runner
{
public static int Run(string configPath, bool launcher = false, string? acFolder = null)
{
RunConfig cfg;
try { cfg = RunConfig.Load(configPath); }
catch (Exception ex) { Console.Error.WriteLine($"config: {ex.Message}"); return 2; }
if (launcher && cfg.Sessions.Count != 1)
{
Console.Error.WriteLine("config: --launcher runs exactly one character (the launcher starts one process per account)");
return 2;
}
var clock = Stopwatch.StartNew();
string T() => $"[{clock.Elapsed.TotalSeconds,8:F2}]";
object consoleGate = new();
void Out(string s) { lock (consoleGate) Console.WriteLine($"{T()} {s}"); }
// Plugin files go under the suite dir (RynthAi reads RYNTHSUITE_DIR once per load context).
Directory.CreateDirectory(cfg.SuiteDir);
Environment.SetEnvironmentVariable("RYNTHSUITE_DIR", cfg.SuiteDir);
string? ac = DatFile.FindAcFolder(acFolder);
using GeometryWalk? geo = ac != null ? GeometryWalk.Open(ac) : null;
SpellTable? spells = ac != null ? SpellTable.Load(ac, out _) : null;
Out($"{cfg.Sessions.Count} character(s) on {string.Join(", ", cfg.Sessions.Select(s => $"{s.Host}:{s.ServerPort}").Distinct())}; {(geo != null ? "walking on the dats in " + ac : "no dats: flat walking")}");
var bots = cfg.Sessions.Select((s, i) => new Bot(cfg, s, i, geo, spells, Out)).ToList();
if (cfg.StatusDir.Length > 0)
foreach (Bot b in bots) Out($"[{b.Label}] status files: {Path.Combine(cfg.StatusDir, "RynthCore." + b.ClientId + ".*")}");
LauncherSession? record = launcher ? new LauncherSession(cfg, cfg.Sessions[0]) : null;
using var stopEvent = new EventWaitHandle(false, EventResetMode.ManualReset,
RynthCore.App.HeadlessLaunch.StopEventName(Environment.ProcessId)); // the launcher sets it (Ctrl+C can't reach a hidden console)
bool stopAsked = false;
int ctrlC = 0;
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
if (++ctrlC == 1)
{
Out("stopping every character (Ctrl+C again to close at once)");
foreach (Bot b in bots) b.Stop();
}
};
// Logins are staggered 3 s apart, as the launcher staggers clients.
long start = clock.ElapsedMilliseconds;
var startAt = bots.Select((b, i) => start + i * 3000L).ToArray();
var links = new List<UdpLink>();
while (bots.Any(b => !b.Done) && ctrlC < 2)
{
links.Clear();
foreach (Bot b in bots)
if (b.Link != null) links.Add(b.Link);
UdpLink.WaitAny(links, 15);
long now = clock.ElapsedMilliseconds;
for (int i = 0; i < bots.Count; i++)
{
if (now < startAt[i]) continue;
try { bots[i].Tick(now); }
catch (Exception ex) { Out($"[{bots[i].Label}] tick failed: {ex.GetType().Name}: {ex.Message}"); }
}
record?.Tick(bots[0]);
if (!stopAsked && stopEvent.WaitOne(0))
{
stopAsked = true;
Out("stop asked (stop event): stopping every character");
foreach (Bot b in bots) b.Stop();
}
}
foreach (Bot b in bots) b.Dispose();
Out("all characters done");
return 0;
}
}

View file

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- rynth-headless: console runner for RynthCore.Headless (P0: the protocol spike). -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthCore.Headless.Cli</RootNamespace>
<AssemblyName>rynth-headless</AssemblyName>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RynthCore.Headless\RynthCore.Headless.csproj" />
</ItemGroup>
<ItemGroup>
<!-- The launcher's saved-password decryption (DPAPI), for the launcher-account option. -->
<Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Launcher\AccountPasswordProtection.cs" />
<!-- run with the launcher flag: the launcher's session record and character cache, as the engine writes them. -->
<Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Launcher\SessionStateStore.cs" />
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Launcher\CharacterCacheStore.cs" />
<!-- The stop event name the launcher sets (shared with it). -->
<Compile Include="..\RynthCore.App\HeadlessLaunch.cs" Link="Launcher\HeadlessLaunch.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games): the default status folder is the
engine's and the StatusAgent's, <RynthCore>\Logs\status (HeadlessDefaults.cs). Read only. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,340 @@
// ============================================================================
// rynth-headless - ScenarioP1.cs
// Live check of the P1 world model and actions (run with --scenario p1, an admin
// character on a test server: it uses @create). Each step prints PASS / FAIL / SKIP:
//
// world PlayerDescription applied, attributes/vitals/skills, pack list matches objects
// identify appraise a pack item -> identify reply
// use open a side pack -> ViewContents
// cast wield a caster if needed, Magic mode, cast a beneficial self spell -> UseDone
// plus an enchantment (or a fizzle error: the cast was processed either way)
// attack @create a monster, Melee mode (caster put away), attack -> AttackDone + combat notices
// pickup @create a pyreal on the ground, pick it up -> walk over, lands in the pack
// give give the pyreal to the monster -> the server answers (monsters refuse)
// drop drop it -> it leaves the pack
// @create needs open ground in front of the player, so the scenario first teleports to
// an open spot outside Holtburg (@teleloc) and at the end teleports back to where the
// character was. The caster is wielded again and the mode is back to NonCombat.
// ============================================================================
using RynthCore.Headless.Dat;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Net;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Cli;
internal sealed class ScenarioP1
{
private readonly ClientSession _s;
private readonly UdpLink _link;
private readonly Action<string> _out;
private readonly List<(string Step, string Result)> _results = new();
private WorldState W => _s.World;
private uint Me => _s.PlayerId;
private uint _lastUseDone = uint.MaxValue, _lastAttackDone = uint.MaxValue;
private readonly List<string> _errors = new();
private readonly List<CombatNotice> _combat = new();
private readonly List<Enchantment> _enchants = new();
private readonly List<(uint Id, bool Ok)> _identified = new();
private readonly List<uint> _opened = new();
private readonly List<WorldObject> _created = new();
public ScenarioP1(ClientSession s, UdpLink link, Action<string> output)
{
_s = s;
_link = link;
_out = output;
W.UseDone += e => { _lastUseDone = e; _out($" << UseDone 0x{e:X}"); };
W.AttackDone += e => { _lastAttackDone = e; _out($" << AttackDone 0x{e:X}"); };
W.Error += (c, t) => { _errors.Add($"0x{c:X} {t}"); _out($" << WeenieError 0x{c:X} {t}"); };
W.InventoryFailed += (i, e) => { _errors.Add($"save failed 0x{i:X8} 0x{e:X}"); _out($" << InventoryServerSaveFailed 0x{i:X8} err 0x{e:X}"); };
W.TransientMessage += t => _out($" << transient: {t}");
W.Combat += c => { _combat.Add(c); _out($" << combat 0x{c.EventType:X}: {c.Name} dmg {c.Damage} hp {c.HealthPercent:P0}"); };
W.EnchantmentAdded += e => { _enchants.Add(e); _out($" << enchantment +{e.SpellId} (layer {e.Layer}, {e.Duration:F0}s)"); };
W.Identified += (id, ok) => _identified.Add((id, ok));
W.ContainerOpened += c => _opened.Add(c);
W.ObjectCreated += o => _created.Add(o);
}
public bool Run()
{
SpellTable? spells = null;
string? ac = DatFile.FindAcFolder();
if (ac != null) spells = SpellTable.Load(ac, out _);
_out($"spell table: {(spells != null ? spells.ById.Count + " spells" : "not found")}");
StepWorld();
WorldPosition? home = W.PlayerObject?.Position;
StepTeleport(OpenGround, "teleport");
StepIdentify();
StepUse();
uint caster = StepCast(spells);
uint monster = SpawnNear(o => o.IsCreature && o.Name == "Drudge Skulker", "drudgeskulker");
uint pyreal = StepPickup();
StepGive(monster, pyreal);
StepDrop(pyreal);
StepAttack(caster, monster);
Restore(caster);
if (home is { } h)
StepTeleport($"0x{h.Cell:X8} {h.X:R} {h.Y:R} {h.Z:R} {h.Qw:R} {h.Qx:R} {h.Qy:R} {h.Qz:R}", "return");
_out("");
_out("P1 scenario results:");
foreach (var (step, result) in _results) _out($" {step,-9} {result}");
return _results.All(r => !r.Result.StartsWith("FAIL"));
}
// ── steps ───────────────────────────────────────────────────────────────
private void StepWorld()
{
Wait(() => W.Player.DescriptionReceived && W.PlayerObject != null, 5000);
PlayerState p = W.Player;
if (!p.DescriptionReceived) { Result("world", "FAIL no PlayerDescription"); return; }
_out($"attributes: {string.Join(" ", Enumerable.Range(1, 6).Select(a => p.BaseAttribute((uint)a)))}");
_out($"vitals: H {p.CurrentVital(Vital.Health)}/{p.BaseMaxVital(Vital.Health)} S {p.CurrentVital(Vital.Stamina)}/{p.BaseMaxVital(Vital.Stamina)} M {p.CurrentVital(Vital.Mana)}/{p.BaseMaxVital(Vital.Mana)} (base max)");
int pack = p.MainPackOrder.Count + p.SidePackOrder.Count;
int matched = p.MainPackOrder.Concat(p.SidePackOrder).Count(id => W.Get(id)?.ContainerId == Me);
int carried = W.Inventory().Count();
_out($"skills {p.SkillTable.Count}, spells {p.SpellBook.Count}, enchantments {p.ActiveEnchantments.Count}, pack {pack} (matched {matched}), equipped {p.EquippedItems.Count}, carried total {carried}, objects {W.Objects.Count}");
bool ok = p.AttributeTable.Count == 6 && p.SkillTable.Count > 0 && p.CurrentVital(Vital.Health) > 0 && matched == pack && pack > 0;
Result("world", ok ? $"PASS {pack} pack entries, {p.EquippedItems.Count} equipped, {carried} carried" : "FAIL model inconsistent");
}
private const string OpenGround = "0xA9B40029 133.603592 17.391838 94.005005 1 0 0 0";
private void StepTeleport(string where, string step)
{
uint lb = Convert.ToUInt32(where.Split(' ')[0], 16) >> 16;
WorldPosition? before = W.PlayerObject?.Position;
if (before is { } b0 && b0.Cell >> 16 == lb && step == "teleport") { Result(step, "PASS already there"); return; }
_out($">> @teleloc {where}");
_s.Say($"@teleloc {where}");
bool moved = Wait(() => W.PlayerObject?.Position is { } p && p.Cell >> 16 == lb, 15000);
Wait(() => false, 3000); // let the new landblock's objects arrive
Result(step, moved ? $"PASS now at 0x{W.PlayerObject!.Position!.Value.Cell:X8}, {W.Objects.Count} objects known" : "FAIL no position update");
}
private void StepIdentify()
{
uint item = W.Player.MainPackOrder.FirstOrDefault();
if (item == 0) { Result("identify", "SKIP no pack item"); return; }
_out($">> identify {W.Get(item)}");
_s.Identify(item);
bool got = Wait(() => _identified.Any(x => x.Id == item), 5000);
WorldObject? o = W.Get(item);
Result("identify", got && o?.Identified == true
? $"PASS {o.Name}: {o.Ints().Count} ints, {o.Strings().Count} strings"
: got ? "FAIL reply without success" : "FAIL no reply");
}
private void StepUse()
{
uint pack = W.Player.SidePackOrder.FirstOrDefault(id => W.Get(id)?.IsContainer == true);
if (pack == 0) { Result("use", "SKIP no side pack"); return; }
_out($">> use {W.Get(pack)}");
_lastUseDone = uint.MaxValue;
_s.Use(pack);
bool answered = Wait(() => _lastUseDone != uint.MaxValue || _opened.Contains(pack), 5000);
Wait(() => _opened.Contains(pack), 500);
int inside = W.Contents(pack).Count();
Result("use", answered && (_lastUseDone == 0 || _opened.Contains(pack))
? $"PASS used {W.Get(pack)?.Name}: UseDone 0x{_lastUseDone:X}{(_opened.Contains(pack) ? $", opened ({inside} items)" : "")}"
: $"FAIL UseDone {(_lastUseDone == uint.MaxValue ? "never came" : "0x" + _lastUseDone.ToString("X"))}");
}
/// <summary>Returns the caster that was wielded before the scenario (or that we wielded), 0 if none.</summary>
private uint StepCast(SpellTable? spells)
{
WorldObject? caster = WieldedCaster();
uint originalCaster = caster?.Id ?? 0;
if (caster == null)
{
caster = W.Inventory().FirstOrDefault(o => o.Desc.ValidLocations is { } v && (v & 0x1000000) != 0);
if (caster == null) { Result("cast", "SKIP no caster"); return 0; }
_out($">> wield {caster}");
_s.Wield(caster.Id, 0x1000000);
Wait(() => W.Get(caster.Id)?.WielderId == Me, 5000);
}
if (spells == null) { Result("cast", "SKIP no spell table"); return originalCaster != 0 ? originalCaster : caster.Id; }
// A cheap beneficial self enchantment the player knows.
SpellInfo? spell = W.Player.SpellBook.Select(spells.Get).Where(s => s != null && s.Beneficial && s.IsEnchantment && s.SelfTargeted)
.OrderBy(s => s!.Power).ThenBy(s => s!.BaseMana).FirstOrDefault();
if (spell == null) { Result("cast", "SKIP no known self buff"); return originalCaster != 0 ? originalCaster : caster.Id; }
_out(">> combat mode Magic");
_s.SetCombatMode(CombatMode.Magic);
Wait(() => CombatModeIs(CombatMode.Magic), 5000);
_out($">> cast {spell.Name} ({spell.Id}) on self");
_lastUseDone = uint.MaxValue;
int enchBefore = _enchants.Count, errBefore = _errors.Count;
_s.Cast(spell.Id, Me);
bool done = Wait(() => _lastUseDone != uint.MaxValue, 20000);
Wait(() => _enchants.Count > enchBefore, 1000);
bool buffed = _enchants.Skip(enchBefore).Any(e => e.SpellId == spell.Id);
string errs = string.Join("; ", _errors.Skip(errBefore));
Result("cast", done && (buffed || _lastUseDone == 0 || errs.Length > 0)
? $"PASS {spell.Name}: {(buffed ? "enchantment applied" : "no enchantment")}, UseDone 0x{_lastUseDone:X}{(errs.Length > 0 ? ", " + errs : "")}"
: $"FAIL UseDone {(done ? "0x" + _lastUseDone.ToString("X") : "never came")}");
return originalCaster != 0 ? originalCaster : caster.Id;
}
private void StepAttack(uint caster, uint monster)
{
if (monster == 0 || W.Get(monster) == null) { Result("attack", "SKIP could not @create a monster"); return; }
_out($">> target {W.Get(monster)} at {W.Distance(Me, monster):F1} m");
_s.QueryHealth(monster);
// Melee is refused with a caster wielded: put it in the pack first.
if (caster != 0 && W.Get(caster)?.WielderId == Me)
{
_s.SetCombatMode(CombatMode.NonCombat);
Wait(() => CombatModeIs(CombatMode.NonCombat), 3000);
_out(">> put the caster away");
_s.MoveItem(caster, Me, 0);
Wait(() => W.Get(caster)?.WielderId == 0, 5000);
}
_out(">> combat mode Melee");
_s.SetCombatMode(CombatMode.Melee);
Wait(() => CombatModeIs(CombatMode.Melee), 5000);
int notices = _combat.Count, swings = 0, dones = 0;
for (int i = 0; i < 8 && W.Get(monster) != null && !Killed(); i++)
{
_lastAttackDone = uint.MaxValue;
_out($">> melee attack #{i + 1}");
_s.MeleeAttack(monster, AttackHeight.Medium, 1.0f);
swings++;
if (Wait(() => _lastAttackDone != uint.MaxValue, 10000)) dones++;
Wait(() => false, 300);
}
bool Killed() => _combat.Skip(notices).Any(c => c.EventType == WorldEvent.KillerNotification);
int got = _combat.Count - notices;
Result("attack", dones > 0 && got > 0
? $"PASS {swings} swings, {dones} AttackDone, {got} combat notices{(Killed() ? ", killed it" : "")}"
: $"FAIL swings {swings}, AttackDone {dones}, notices {got}");
_s.SetCombatMode(CombatMode.NonCombat);
Wait(() => CombatModeIs(CombatMode.NonCombat), 3000);
}
private uint StepPickup()
{
uint pyreal = SpawnNear(o => o.WeenieClassId == 273 && o.ContainerId == 0 && o.Position != null, "273");
if (pyreal == 0) { Result("pickup", "SKIP could not @create a pyreal"); return 0; }
float? d0 = W.Distance(Me, pyreal);
_out($">> pick up {W.Get(pyreal)} at {d0:F1} m");
_s.PickUp(pyreal);
bool got = Wait(() => W.Get(pyreal)?.ContainerId == Me, 20000);
Result("pickup", got ? $"PASS picked up from {d0:F1} m (walked {(_walked ? "yes" : "no")})" : "FAIL not in the pack");
return got ? pyreal : 0;
}
private bool _walked;
private void StepGive(uint monster, uint item)
{
if (item == 0) { Result("give", "SKIP nothing to give"); return; }
uint target = monster != 0 && W.Get(monster) != null ? monster : 0;
if (target == 0) { Result("give", "SKIP no living target"); return; }
bool answered = false;
int errBefore = _errors.Count;
for (int attempt = 1; attempt <= 5; attempt++)
{
// Busy (0x1D) right after the pickup: wait for the animation and ask again.
errBefore = _errors.Count;
_out($">> give {W.Get(item)} to {W.Get(target)}{(attempt > 1 ? $" (attempt {attempt})" : "")}");
_s.Give(target, item, 1);
answered = Wait(() => _errors.Count > errBefore || W.Get(item)?.ContainerId == target, 20000);
Wait(() => false, 300);
if (!_errors.Skip(errBefore).Any(e => e.StartsWith("0x1D"))) break;
Wait(() => false, 1000);
}
bool given = W.Get(item)?.ContainerId == target;
Result("give", answered
? $"PASS server answered: {(given ? "accepted" : "refused (" + string.Join("; ", _errors.Skip(errBefore)) + ")")}"
: "FAIL no answer");
}
private void StepDrop(uint item)
{
if (item == 0 || W.Get(item)?.ContainerId != Me) { Result("drop", "SKIP nothing to drop"); return; }
bool dropped = false;
for (int attempt = 1; attempt <= 5 && !dropped; attempt++)
{
// Right after a pickup the player is still busy (the pickup animation's return): retry.
int errBefore = _errors.Count;
_out($">> drop {W.Get(item)}{(attempt > 1 ? $" (attempt {attempt})" : "")}");
_s.Drop(item);
dropped = Wait(() => (W.Get(item) is { } o && o.ContainerId == 0 && !W.Player.MainPackOrder.Contains(item)) || _errors.Count > errBefore, 10000)
&& W.Get(item) is { } d && d.ContainerId == 0;
if (!dropped) Wait(() => false, 1000);
}
Result("drop", dropped ? "PASS left the pack" : "FAIL still carried");
}
private void Restore(uint caster)
{
if (caster != 0 && W.Get(caster) is { } c && c.WielderId != Me)
{
_out($">> wield {c} again");
_s.Wield(caster, 0x1000000);
Wait(() => W.Get(caster)?.WielderId == Me, 5000);
}
_s.SetCombatMode(CombatMode.NonCombat);
Wait(() => false, 1000);
}
// ── helpers ─────────────────────────────────────────────────────────────
private WorldObject? WieldedCaster()
=> W.Objects.Values.FirstOrDefault(o => o.WielderId == Me && (o.WieldedLocation & 0x1000000) != 0);
private bool CombatModeIs(uint mode) => W.PlayerObject is { } me && me.TryGetInt(40, out int m) && m == mode;
/// <summary>@creates something and returns the first new object matching, trying each name in turn.</summary>
private uint SpawnNear(Func<WorldObject, bool> match, params string[] names)
{
foreach (string name in names)
{
int before = _created.Count;
_out($">> @create {name}");
_s.Say($"@create {name}");
WorldObject? found = null;
Wait(() => (found = _created.Skip(before).FirstOrDefault(match)) != null, 5000);
if (found != null) return found.Id;
}
return 0;
}
private void Result(string step, string result)
{
_results.Add((step, result));
_out($"== {step}: {result}");
}
/// <summary>Pumps the session until the condition holds or the timeout passes.</summary>
private bool Wait(Func<bool> done, int timeoutMs)
{
long end = Environment.TickCount64 + timeoutMs;
while (Environment.TickCount64 < end && !_s.Finished)
{
if (done()) return true;
_link.Wait(15);
_s.Tick();
if (_s.Moving) _walked = true;
}
return done();
}
}
internal static class WorldObjectDebug
{
public static IReadOnlyCollection<uint> Ints(this WorldObject o)
=> Enumerable.Range(0, 1000).Where(k => o.TryGetInt((uint)k, out _)).Select(k => (uint)k).ToList();
public static IReadOnlyCollection<uint> Strings(this WorldObject o)
=> Enumerable.Range(0, 100).Where(k => o.TryGetString((uint)k, out _)).Select(k => (uint)k).ToList();
}

View file

@ -0,0 +1,277 @@
// ============================================================================
// rynth-headless - ScenarioP2.cs
// Live check of P2 movement (run with --scenario p2, an admin character on a test
// server, the AC dats present). Each step prints PASS / FAIL / SKIP:
//
// dungeon walk legs in the character's (indoor) spot: every leg ends in a cell the
// cell index agrees with, the server never corrects us
// teleport to open ground outside Holtburg (@teleloc)
// route run a 4-leg loop of waypoints on the terrain: heights follow the ground,
// land cells right, no corrections
// building walk in through the nearest outdoor doorway: the cell becomes the building's
// portal find the nearest portal object, use it: the server asks us over, we walk,
// it teleports us (new landblock), LoginComplete goes out
// return teleport back to where the character was
// ============================================================================
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Walking;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Movement;
using RynthCore.Headless.Net;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Cli;
internal sealed class ScenarioP2
{
private const string OpenGround = "0xA9B40029 133.603592 17.391838 94.005005 1 0 0 0";
private readonly ClientSession _s;
private readonly UdpLink _link;
private readonly GeometryWalk _geo;
private readonly Action<string> _out;
private readonly List<(string Step, string Result)> _results = new();
private int _corrections;
private (bool Ok, string Why)? _finished;
private WorldState W => _s.World;
public ScenarioP2(ClientSession s, UdpLink link, GeometryWalk geo, Action<string> output)
{
_s = s;
_link = link;
_geo = geo;
_out = output;
W.PlayerCorrected += p => { _corrections++; _out($" << server moved us to 0x{p.Cell:X8} ({p.X:F1},{p.Y:F1},{p.Z:F2})"); };
_s.MoveFinished += (ok, why) => _finished = (ok, why);
W.Error += (c, t) => _out($" << WeenieError 0x{c:X} {t}");
W.TransientMessage += t => _out($" << transient: {t}");
}
public bool Run()
{
Wait(() => W.PlayerObject?.Position != null, 5000);
WorldPosition? home = W.PlayerObject?.Position;
StepDungeon();
Teleport(OpenGround, "teleport");
StepRoute();
StepBuilding();
StepPortal();
if (home is { } h) Teleport($"0x{h.Cell:X8} {h.X:R} {h.Y:R} {h.Z:R} {h.Qw:R} {h.Qx:R} {h.Qy:R} {h.Qz:R}", "return");
_out("");
_out("P2 scenario results:");
foreach (var (step, result) in _results) _out($" {step,-9} {result}");
return _results.All(r => !r.Result.StartsWith("FAIL"));
}
// ── steps ───────────────────────────────────────────────────────────────
private void StepDungeon()
{
if (W.PlayerObject?.Position is not { } start || !EnvCell.IsIndoor(start.Cell)) { Result("dungeon", "SKIP not indoors"); return; }
int legs = 0, consistent = 0, arrived = 0, before = _corrections;
var rng = new Random(5);
for (int i = 0; i < 8; i++)
{
WorldPosition p = W.PlayerObject!.Position!.Value;
float ang = (float)(rng.NextDouble() * Math.PI * 2);
if (Walk(Offset(p, MathF.Cos(ang) * 6, MathF.Sin(ang) * 6), 10_000)) arrived++;
legs++;
WorldPosition q = W.PlayerObject!.Position!.Value;
var found = _geo.Indoor.FindCell(q.Cell >> 16, q.X, q.Y, q.Z);
bool ok = found?.cellId == q.Cell;
if (ok) consistent++;
_out($" leg {i + 1}: {(_finished?.Ok == true ? "arrived" : _finished?.Why)} at 0x{q.Cell:X8} ({q.X:F1},{q.Y:F1},{q.Z:F2}){(ok ? "" : $" - cell index says {found?.cellId:X8}")}");
}
// Back to the start so the character ends where it was.
Walk(start, 15_000);
int corrected = _corrections - before;
Result("dungeon", consistent == legs && corrected == 0
? $"PASS {legs} legs ({arrived} reached, the rest stopped by walls), all cells consistent, no corrections"
: $"FAIL {consistent}/{legs} consistent cells, {corrected} corrections");
}
private void StepRoute()
{
if (W.PlayerObject?.Position is not { } p0 || EnvCell.IsIndoor(p0.Cell)) { Result("route", "SKIP not outdoors"); return; }
// An open 25 m square near here: every leg walkable in a straight line (checked with the same
// geometry, offline). Walk to its first corner (the planner finds the way), then run the loop.
List<WorldPosition>? points = null;
for (float ring = 0; ring <= 160 && points == null; ring += 16)
{
int around = ring == 0 ? 1 : (int)(ring / 4);
for (int k = 0; k < around && points == null; k++)
{
float a = k * MathF.PI * 2 / around;
WorldPosition c = Offset(p0, MathF.Cos(a) * ring, MathF.Sin(a) * ring);
c = c with { Z = _geo.Terrain.GetStandingZ(c.Cell >> 16, c.X, c.Y) };
var cand = new List<WorldPosition>();
WorldPosition cur = c;
bool ok = _geo.Walker.CanStand(c.Cell, new System.Numerics.Vector3(c.X, c.Y, c.Z));
foreach (var (e, n) in new[] { (0f, 25f), (25f, 0f), (0f, -25f), (-25f, 0f) })
{
if (!ok) break;
var r = _geo.Walker.Step(cur.Cell, new System.Numerics.Vector3(cur.X, cur.Y, cur.Z), e, n);
if (r.Blocked || r.Slid || EnvCell.IsIndoor(r.Cell)) { ok = false; break; }
cur = cur with { Cell = r.Cell, X = r.Position.X, Y = r.Position.Y, Z = r.Position.Z };
cand.Add(cur);
}
if (ok)
{
_out($">> open loop {ring:F0} m away at 0x{c.Cell:X8} ({c.X:F0},{c.Y:F0}); walking there");
if (!Walk(c, 60_000)) { _out($" could not reach it ({_finished?.Why})"); continue; }
points = cand;
}
}
}
if (points == null) { Result("route", "SKIP no open 25 m loop within 160 m"); return; }
p0 = W.PlayerObject!.Position!.Value;
int before = _corrections, samples = 0, onGround = 0;
_finished = null;
_s.WalkPath(points);
long end = Environment.TickCount64 + 60_000;
while (_finished == null && Environment.TickCount64 < end && !_s.Finished)
{
Pump(100);
if (W.PlayerObject?.Position is { } q && !EnvCell.IsIndoor(q.Cell))
{
samples++;
float g = _geo.Terrain.GetStandingZ(q.Cell >> 16, q.X, q.Y);
if (q.Z >= g - 0.01f && q.Z < g + 3f && q.Cell == Walker.OutdoorCell(q.Cell >> 16, q.X, q.Y)) onGround++;
}
}
WorldPosition last = W.PlayerObject!.Position!.Value;
float back = Distance(last, p0);
int corrected = _corrections - before;
Result("route", _finished?.Ok == true && corrected == 0 && onGround == samples
? $"PASS 100 m loop, {samples} samples on the ground with the right land cells, ended {back:F1} m from the start"
: $"FAIL finished {_finished?.Ok} ({_finished?.Why}), {onGround}/{samples} on ground, {corrected} corrections");
}
private void StepBuilding()
{
if (W.PlayerObject?.Position is not { } p || EnvCell.IsIndoor(p.Cell)) { Result("building", "SKIP not outdoors"); return; }
uint lb = p.Cell >> 16;
// The nearest outdoor doorway whose threshold the walker can reach from the ground.
var doors = new List<(EnvCell Cell, System.Numerics.Vector3 Centre, System.Numerics.Vector2 Out, float D)>();
foreach (EnvCell c in _geo.Indoor.LoadLandblock(lb))
{
if ((c.Flags & 1) == 0) continue;
foreach (CellPortal cp in c.Portals.Where(x => x.LeadsOutdoors && x.Polygon.Length >= 3))
{
var centre = cp.Polygon.Aggregate(System.Numerics.Vector3.Zero, (s, q) => s + q) / cp.Polygon.Length;
var n = CellDat.Normal(cp.Polygon);
var flat = System.Numerics.Vector2.Normalize(new System.Numerics.Vector2(n.X, n.Y));
if (float.IsNaN(flat.X)) continue;
var outward = cp.PortalSide ? flat : -flat;
float d = MathF.Sqrt((centre.X - p.X) * (centre.X - p.X) + (centre.Y - p.Y) * (centre.Y - p.Y));
// Skip windows (sill more than a step above the ground outside).
float ground = _geo.Terrain.GetStandingZ(lb, centre.X + outward.X * 0.6f, centre.Y + outward.Y * 0.6f);
if (cp.Polygon.Min(q => q.Z) - ground > 0.55f) continue;
doors.Add((c, centre, outward, d));
}
}
foreach (var door in doors.OrderBy(d => d.D).Take(6))
{
var outside = door.Centre with { X = door.Centre.X + door.Out.X * 3, Y = door.Centre.Y + door.Out.Y * 3 };
var inside = door.Centre with { X = door.Centre.X - door.Out.X * 1.5f, Y = door.Centre.Y - door.Out.Y * 1.5f };
_out($">> try the doorway of 0x{door.Cell.Id:X8}, {door.D:F0} m away");
Walk(Local(lb, outside.X, outside.Y, p), 20_000);
Walk(Local(lb, inside.X, inside.Y, p), 10_000);
WorldPosition q = W.PlayerObject!.Position!.Value;
if (EnvCell.IsIndoor(q.Cell))
{
bool agrees = _geo.Indoor.FindCell(lb, q.X, q.Y, q.Z)?.cellId == q.Cell;
Walk(Local(lb, outside.X, outside.Y, p), 10_000); // and out again
WorldPosition o = W.PlayerObject!.Position!.Value;
Result("building", agrees && !EnvCell.IsIndoor(o.Cell)
? $"PASS walked into 0x{q.Cell:X8} and back out to 0x{o.Cell:X8}"
: $"FAIL inside 0x{q.Cell:X8} (index agrees {agrees}), after leaving 0x{o.Cell:X8}");
return;
}
_out($" stayed outside ({_finished?.Why})");
}
Result("building", doors.Count == 0 ? "SKIP no doorways here" : "FAIL could not walk into any of the nearest doorways");
}
private void StepPortal()
{
if (W.PlayerObject?.Position is not { } p) { Result("portal", "SKIP no position"); return; }
WorldObject? portal = W.Objects.Values
.Where(o => (o.Desc.DescriptionFlags & 0x40000) != 0 && o.Position != null && o.Position.Value.Cell >> 16 == p.Cell >> 16)
.OrderBy(o => Distance(o.Position!.Value, p)).FirstOrDefault();
if (portal == null) { Result("portal", "SKIP no portal in this landblock"); return; }
uint lb0 = p.Cell >> 16;
_out($">> use {portal} at {Distance(portal.Position!.Value, p):F0} m");
int before = _corrections;
_s.Use(portal.Id);
bool moved = Wait(() => W.PlayerObject?.Position is { } q && q.Cell >> 16 != lb0, 30_000);
Wait(() => false, 3000);
WorldPosition dest = W.PlayerObject!.Position!.Value;
Result("portal", moved
? $"PASS {portal.Name} took us to 0x{dest.Cell:X8} ({_corrections - before} position updates from the server)"
: $"FAIL still in 0x{lb0:X4}xxxx after 30 s ({_finished?.Why})");
}
private void Teleport(string where, string step)
{
uint lb = Convert.ToUInt32(where.Split(' ')[0], 16) >> 16;
_out($">> @teleloc {where}");
_s.Say($"@teleloc {where}");
bool moved = Wait(() => W.PlayerObject?.Position is { } p && p.Cell >> 16 == lb, 15_000);
Wait(() => false, 3000);
Result(step, moved ? $"PASS at 0x{W.PlayerObject!.Position!.Value.Cell:X8}" : "FAIL no position update");
}
// ── helpers ─────────────────────────────────────────────────────────────
private bool Walk(WorldPosition to, int timeoutMs)
{
_finished = null;
_s.WalkTo(to);
Wait(() => _finished != null, timeoutMs);
return _finished?.Ok == true;
}
private static WorldPosition Offset(WorldPosition p, float east, float north)
=> EnvCell.IsIndoor(p.Cell) ? p with { X = p.X + east, Y = p.Y + north } : ClientSession.Relocate(p, p.X + east, p.Y + north);
private static WorldPosition Local(uint lb, float x, float y, WorldPosition like)
=> like with { Cell = Walker.OutdoorCell(lb, x, y), X = x, Y = y };
private static float Distance(WorldPosition a, WorldPosition b)
{
(float dx, float dy) = ClientSession.Delta(a, b);
return MathF.Sqrt(dx * dx + dy * dy);
}
private void Result(string step, string result)
{
_results.Add((step, result));
_out($"== {step}: {result}");
}
private void Pump(int ms)
{
long end = Environment.TickCount64 + ms;
while (Environment.TickCount64 < end && !_s.Finished)
{
_link.Wait(15);
_s.Tick();
}
}
private bool Wait(Func<bool> done, int timeoutMs)
{
long end = Environment.TickCount64 + timeoutMs;
while (Environment.TickCount64 < end && !_s.Finished)
{
if (done()) return true;
_link.Wait(15);
_s.Tick();
}
return done();
}
}