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

@ -71,7 +71,7 @@ internal static class CrashDumpWriters
return result;
}
private static string? TryGetCommandLine(int pid)
internal static string? TryGetCommandLine(int pid)
{
IntPtr h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
if (h == IntPtr.Zero) return null;

View file

@ -390,6 +390,24 @@
ToolTip.Tip="Added to the end of every launch's command line, after the account, password and server the profiles set. It can't contain -a, -v, -h, -p or -rodat: set those in the account and server profiles. One line."
AcceptsReturn="False"
TextWrapping="Wrap" />
<TextBlock Text="Headless client (experimental)" Foreground="#26C1A6" FontWeight="SemiBold" Margin="0,6,0,0" />
<TextBlock Text="For accounts set to Headless (experimental): no game window, rynth-headless.exe logs in and runs the 64-bit plugins below (empty = the RynthAi that comes with RynthCore). ACE servers only."
TextWrapping="Wrap"
Foreground="#9AA8B3" />
<TextBlock Text="rynth-headless.exe" Foreground="#EAF0F4" />
<TextBox x:Name="HeadlessExePathTextBox"
Watermark="Empty = Headless\rynth-headless.exe beside the launcher" />
<TextBlock Text="Headless plugins (64-bit DLLs, one per line)" Foreground="#EAF0F4" />
<TextBox x:Name="HeadlessPluginPathsTextBox"
Watermark="Empty = Headless\plugins\RynthAi (comes with RynthCore)"
ToolTip.Tip="Loaded by every Headless account. Empty = the 64-bit plugins that come with RynthCore, in Headless\plugins beside the launcher (RynthAi). rynth-headless is a 64-bit process: list only x64 builds here, never the ones in the Plugins tab."
AcceptsReturn="True"
TextWrapping="NoWrap"
MinHeight="56" />
<Button x:Name="StopHeadlessButton"
Content="Log out headless clients"
ToolTip.Tip="A headless client has no window to close: this asks every running rynth-headless.exe to log its character out and exit (closed after 20 s if it doesn't). With AutoLaunch on, uncheck the account first or it is started again."
HorizontalAlignment="Left" />
<Button x:Name="SavePathsButton"
Content="Save Runtime Paths"
HorizontalAlignment="Left" />

View file

@ -49,6 +49,12 @@ internal partial class MainWindow : Window
private readonly ObservableCollection<string> _sessionItems = [];
private readonly ObservableCollection<string> _pluginDllPaths = [];
private readonly HashSet<int> _launchedSessionPids = [];
// rynth-headless.exe processes (InjectionMode.Headless): those this launcher started (until
// DetectQuickExits drops them), and those the last FindClientProcesses saw. They count as
// clients for sessions, account keys and auto-launch; acclient-only steps skip them.
private readonly HashSet<int> _launchedHeadlessPids = [];
private readonly HashSet<int> _headlessClientPids = [];
private readonly Dictionary<string, DateTime> _headlessRefusalNoticeTimesUtc = new(StringComparer.OrdinalIgnoreCase);
// Per-PID metadata for crash detection: which account this client belongs
// to and when we launched it. Used by the auto-relaunch circuit breaker
// to distinguish "exited normally after a long session" from "quick exit".
@ -256,6 +262,7 @@ internal partial class MainWindow : Window
HeaderLaunchButton.Click += async (_, _) => await LaunchCheckedTargetsAsync();
AutoLaunchHeaderCheckBox.IsCheckedChanged += (_, _) => SaveAutoLaunchPreference();
SavePathsButton.Click += (_, _) => SaveRuntimePaths();
StopHeadlessButton.Click += (_, _) => StopHeadlessClients();
SaveBehaviorButton.Click += (_, _) => SaveLaunchBehavior();
InjectRunningAcButton.Click += async (_, _) => await InjectRunningAcAsync();
RefreshSessionsButton.Click += (_, _) => RefreshSessionState();
@ -385,6 +392,8 @@ internal partial class MainWindow : Window
? _settings.EnginePath
: _injector.TryResolveEnginePath(null) ?? string.Empty;
LaunchArgumentsTextBox.Text = _settings.LaunchArguments;
HeadlessExePathTextBox.Text = _settings.HeadlessExePath;
HeadlessPluginPathsTextBox.Text = string.Join(Environment.NewLine, _settings.HeadlessPluginPaths ?? []);
// A whole-line override saved by an older launcher (with -a/-v/-h) would now ride along
// on every account: launches refuse it, so say so up front.
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(_settings.LaunchArguments, out _) is string extraProblem)
@ -1228,20 +1237,32 @@ internal partial class MainWindow : Window
"set the account back to RynthCore or Decal: once no account uses it, the launcher takes the " +
"bridge out of Decal's list again (uninstalling RynthCore does too).");
var headlessItem = new ComboBoxItem { Content = "Headless (experimental)", Tag = InjectionMode.Headless };
global::Avalonia.Controls.ToolTip.SetTip(headlessItem,
"EXPERIMENTAL. No game window: the launcher starts rynth-headless.exe, RynthCore's own headless " +
"client, for this account. ACE servers only (not GDLE). " +
"Plugins: the 64-bit ones listed under Runtime > Headless client; with that list empty, the RynthAi " +
"that comes with RynthCore. The plugins in the Plugins tab and Decal don't run in it, and nothing is drawn: " +
"give RynthAi its orders with the account's on-login commands (for example /ra start). " +
"It logs in, runs the plugins and shows in the launcher like any other client; closing it from the launcher logs the character out first.");
dropdown.Items.Add(rynthItem);
dropdown.Items.Add(decalItem);
dropdown.Items.Add(bridgeItem);
dropdown.Items.Add(headlessItem);
// If the account is set to a Decal mode but Decal isn't installed, fall back to
// RynthCore in the UI so the user can't accidentally launch into a
// disabled mode. We don't mutate the saved profile until they click.
InjectionMode effectiveMode = (account.InjectionMode != InjectionMode.RynthCore && !decalAvailable)
// Headless needs no Decal, so it stays as it is.
InjectionMode effectiveMode = ((account.InjectionMode is InjectionMode.Decal or InjectionMode.DecalBridge) && !decalAvailable)
? InjectionMode.RynthCore
: account.InjectionMode;
dropdown.SelectedItem = effectiveMode switch
{
InjectionMode.Decal => decalItem,
InjectionMode.DecalBridge => bridgeItem,
InjectionMode.Headless => headlessItem,
_ => rynthItem,
};
@ -1257,6 +1278,9 @@ internal partial class MainWindow : Window
AppendActivity(mode == InjectionMode.DecalBridge
? $"{account.DisplayName}: injection method set to Decal + RynthCore (experimental). " +
"Adding the RynthCore Decal bridge to Decal's filter list for all users (once; Windows may ask for administrator permission)."
: mode == InjectionMode.Headless
? $"{account.DisplayName}: injection method set to Headless (experimental): launches start rynth-headless.exe " +
"with the plugins under Runtime > Headless client (none listed = the RynthAi that comes with RynthCore). ACE servers only, no game window."
: $"{account.DisplayName}: injection method set to {mode}.");
if (mode == InjectionMode.DecalBridge)
_ = EnableDecalBridgeAsync();
@ -1616,6 +1640,8 @@ internal partial class MainWindow : Window
_settings.AcClientPath = AcClientPathTextBox.Text?.Trim() ?? string.Empty;
_settings.EnginePath = EnginePathTextBox.Text?.Trim() ?? string.Empty;
_settings.LaunchArguments = LaunchArgumentsTextBox.Text?.Trim() ?? string.Empty;
_settings.HeadlessExePath = HeadlessExePathTextBox.Text?.Trim() ?? string.Empty;
_settings.HeadlessPluginPaths = ReadHeadlessPluginPathsBox();
SaveSettings();
RefreshSummary();
if (appendActivity)
@ -1714,76 +1740,130 @@ internal partial class MainWindow : Window
if (_operationBusy)
return;
// Headless accounts start rynth-headless.exe (LaunchOneHeadlessAsync), not acclient.exe:
// the client checks below (client and engine paths, Extra Launch Arguments, the engine
// plugin, Decal, the Decal bridge) are about the other accounts only. When they fail in
// a batch with Headless accounts, the Headless accounts still launch.
List<LaunchAccountProfile> headlessAccounts = accountsToLaunch.Where(a => a.InjectionMode == InjectionMode.Headless).ToList();
List<LaunchAccountProfile> clientAccounts = accountsToLaunch.Where(a => a.InjectionMode != InjectionMode.Headless).ToList();
string acPath = AcClientPathTextBox.Text?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(acPath) || !File.Exists(acPath))
{
AppendActivity("Launch blocked: AC client path is missing or invalid.");
return;
}
string enginePath = EnginePathTextBox.Text?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(enginePath))
enginePath = _injector.TryResolveEnginePath(null) ?? string.Empty;
if (string.IsNullOrWhiteSpace(enginePath))
{
AppendActivity("Launch blocked: engine path is missing and no default engine DLL could be resolved.");
return;
}
// Extra Launch Arguments go after each account's own arguments, for manual and automatic
// launches alike. They used to replace the whole line instead (and only manually, one
// account at a time); ExtraArgumentsProblem refuses what an old override would carry.
if (AcLaunchArgumentBuilder.ExtraArgumentsProblem(LaunchArgumentsTextBox.Text, out string extraArguments) is string extraProblem)
{
DateTime nowUtc = DateTime.UtcNow;
if (!isAutomaticLaunch || nowUtc - _extraArgumentsNoticeUtc >= AutoLaunchNeedsPasswordLogCooldown)
{
_extraArgumentsNoticeUtc = nowUtc;
AppendActivity($"Launch blocked: {extraProblem}");
}
return;
}
string enginePath = string.Empty;
string extraArguments = string.Empty;
bool shouldInject = AutoInjectAfterLaunchCheckBox.IsChecked == true;
string? decalInjectPath = null;
// Engine plugin must be selected when at least one chosen account is
// RynthCore-mode AND auto-inject is on. Decal-mode accounts don't need
// it because they don't load the engine.
bool anyRynthCoreMode = accountsToLaunch.Any(a => a.InjectionMode is InjectionMode.RynthCore or InjectionMode.DecalBridge);
if (shouldInject && anyRynthCoreMode && !GetSelectedPluginIds().Contains("rynthcore-engine", StringComparer.OrdinalIgnoreCase))
if (clientAccounts.Count > 0)
{
AppendActivity("Launch blocked: RynthCore Engine must stay selected in Runtime Loadout when auto-inject is enabled for any RynthCore-mode account.");
return;
}
string? clientBlock = null; // why the acclient accounts can't launch
bool logClientBlock = true;
// Pre-resolve Decal Inject.dll once if any account needs it.
bool anyDecalMode = accountsToLaunch.Any(a => a.InjectionMode is InjectionMode.Decal or InjectionMode.DecalBridge);
string? decalInjectPath = anyDecalMode && shouldInject
? DecalLocator.TryGetInjectDllPath()
: null;
if (shouldInject && anyDecalMode && decalInjectPath == null)
{
AppendActivity("Launch blocked: one or more accounts are set to Decal mode but Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent\\AgentPath\\Inject.dll missing).");
return;
}
if (string.IsNullOrWhiteSpace(acPath) || !File.Exists(acPath))
clientBlock = "AC client path is missing or invalid.";
// "Decal + RynthCore" accounts: make sure the Decal bridge is registered for this
// Windows user (idempotent; opt-in - only these accounts ever trigger it).
// Registered where THIS PC's AC client reads Decal's filter list, then checked: a
// client that wouldn't load the bridge runs the old coexistence path (no overlay, then
// a crash), so such a launch is blocked with the reason.
if (shouldInject && accountsToLaunch.Any(a => a.InjectionMode == InjectionMode.DecalBridge))
{
string decalAcPath = DecalLocator.TryGetDecalAcClientPath() ?? acPath;
if (!await EnsureDecalBridgeAsync(decalAcPath, interactive: !isAutomaticLaunch))
if (clientBlock == null)
{
AppendActivity("Launch blocked: a Decal + RynthCore client would not load the Decal bridge on this PC (see the lines above, or Recovery Actions > Check Decal bridge). " +
"Pick RynthCore or Decal for those accounts until it passes.");
return;
enginePath = EnginePathTextBox.Text?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(enginePath))
enginePath = _injector.TryResolveEnginePath(null) ?? string.Empty;
if (string.IsNullOrWhiteSpace(enginePath))
clientBlock = "engine path is missing and no default engine DLL could be resolved.";
}
// Extra Launch Arguments go after each account's own arguments, for manual and automatic
// launches alike. They used to replace the whole line instead (and only manually, one
// account at a time); ExtraArgumentsProblem refuses what an old override would carry.
if (clientBlock == null &&
AcLaunchArgumentBuilder.ExtraArgumentsProblem(LaunchArgumentsTextBox.Text, out extraArguments) is string extraProblem)
{
clientBlock = extraProblem;
DateTime nowUtc = DateTime.UtcNow;
logClientBlock = !isAutomaticLaunch || nowUtc - _extraArgumentsNoticeUtc >= AutoLaunchNeedsPasswordLogCooldown;
if (logClientBlock)
_extraArgumentsNoticeUtc = nowUtc;
}
// Engine plugin must be selected when at least one chosen account is
// RynthCore-mode AND auto-inject is on. Decal-mode accounts don't need
// it because they don't load the engine.
bool anyRynthCoreMode = clientAccounts.Any(a => a.InjectionMode is InjectionMode.RynthCore or InjectionMode.DecalBridge);
if (clientBlock == null && shouldInject && anyRynthCoreMode &&
!GetSelectedPluginIds().Contains("rynthcore-engine", StringComparer.OrdinalIgnoreCase))
{
clientBlock = "RynthCore Engine must stay selected in Runtime Loadout when auto-inject is enabled for any RynthCore-mode account.";
}
// Pre-resolve Decal Inject.dll once if any account needs it.
bool anyDecalMode = clientAccounts.Any(a => a.InjectionMode is InjectionMode.Decal or InjectionMode.DecalBridge);
if (clientBlock == null && shouldInject && anyDecalMode)
{
decalInjectPath = DecalLocator.TryGetInjectDllPath();
if (decalInjectPath == null)
clientBlock = "one or more accounts are set to Decal mode but Decal is not installed (HKLM\\SOFTWARE\\Decal\\Agent\\AgentPath\\Inject.dll missing).";
}
// "Decal + RynthCore" accounts: make sure the Decal bridge is registered for this
// Windows user (idempotent; opt-in - only these accounts ever trigger it).
// Registered where THIS PC's AC client reads Decal's filter list, then checked: a
// client that wouldn't load the bridge runs the old coexistence path (no overlay, then
// a crash), so such a launch is blocked with the reason.
if (clientBlock == null && shouldInject && clientAccounts.Any(a => a.InjectionMode == InjectionMode.DecalBridge))
{
string decalAcPath = DecalLocator.TryGetDecalAcClientPath() ?? acPath;
if (!await EnsureDecalBridgeAsync(decalAcPath, interactive: !isAutomaticLaunch))
{
clientBlock = "a Decal + RynthCore client would not load the Decal bridge on this PC (see the lines above, or Recovery Actions > Check Decal bridge). " +
"Pick RynthCore or Decal for those accounts until it passes.";
}
}
if (clientBlock != null)
{
if (logClientBlock)
{
AppendActivity(headlessAccounts.Count > 0
? $"Launch blocked for the accounts that aren't Headless: {clientBlock} The Headless accounts launch anyway."
: $"Launch blocked: {clientBlock}");
}
clientAccounts.Clear();
}
}
// rynth-headless.exe must be there (Runtime > Headless client; default <launcher>\Headless).
string headlessExePath = string.Empty;
List<string> headlessPlugins = [];
if (headlessAccounts.Count > 0)
{
headlessExePath = HeadlessLaunch.ResolveExePath(HeadlessExePathTextBox.Text, AppContext.BaseDirectory);
// An empty box = the 64-bit plugins the installer ships in Headless\plugins (RynthAi).
headlessPlugins = HeadlessLaunch.ResolvePluginPaths(ReadHeadlessPluginPathsBox(), AppContext.BaseDirectory);
if (!File.Exists(headlessExePath))
{
foreach (LaunchAccountProfile account in headlessAccounts)
{
NoteHeadlessRefusal(account, isAutomaticLaunch,
$"{HeadlessLaunch.ExeName} not found at {headlessExePath}. Set its path under Runtime > Headless client.");
}
headlessAccounts.Clear();
}
// Refused before the First Login dialog could ask for a password it then can't use.
headlessAccounts.RemoveAll(account =>
{
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server?.Emulator != AcEmulatorKind.Gdle)
return false;
NoteHeadlessRefusal(account, isAutomaticLaunch,
$"Headless runs on ACE servers only, and {server.DisplayName} is a GDLE server. Pick RynthCore or Decal for this account.");
return true;
});
}
if (clientAccounts.Count + headlessAccounts.Count == 0)
return;
if (clientAccounts.Count + headlessAccounts.Count < accountsToLaunch.Count)
accountsToLaunch = accountsToLaunch.Where(a => clientAccounts.Contains(a) || headlessAccounts.Contains(a)).ToList();
// No usable password: the client would refuse to start ("You can only run the game from
// the launcher program") and exit within seconds. A manual launch asks for it (and the
// account) in the First Login dialog; an automatic one skips the account.
@ -1817,7 +1897,9 @@ internal partial class MainWindow : Window
try
{
SetOperationState(true);
_launchSettings.Apply(acPath, _settings.AllowMultipleClients, _settings.SkipIntroVideos, AppendActivity);
// acclient's own settings (multiple clients, intro videos); nothing a Headless launch reads.
if (accountsToLaunch.Any(a => a.InjectionMode != InjectionMode.Headless))
_launchSettings.Apply(acPath, _settings.AllowMultipleClients, _settings.SkipIntroVideos, AppendActivity);
AppendActivity($"Preparing {launchLabel}.");
HashSet<string> activeAccountKeys = GetActiveAccountKeys();
@ -1843,11 +1925,25 @@ internal partial class MainWindow : Window
var prepared = new List<(LaunchAccountProfile Account, string Args, string Summary, LaunchContextRecord Context)>();
foreach (LaunchAccountProfile account in accountsToLaunch)
{
if (!TryGetLaunchArgumentsForAccount(
bool headless = account.InjectionMode == InjectionMode.Headless;
string launchArguments = string.Empty;
string launchSummary;
if (headless)
{
// No acclient command line (it would carry the password): rynth-headless reads
// the password itself, by profile id (HeadlessLaunch).
if (HeadlessLaunchProblem(account) is string headlessProblem)
{
NoteHeadlessRefusal(account, isAutomaticLaunch, headlessProblem);
continue;
}
launchSummary = _launchArgumentBuilder.Describe(ResolveServerForAccount(account)!, account) + " (headless)";
}
else if (!TryGetLaunchArgumentsForAccount(
account,
extraArguments,
out string launchArguments,
out string launchSummary,
out launchArguments,
out launchSummary,
out string error))
{
AppendActivity($"Launch blocked for {account.DisplayName}: {error}");
@ -1866,7 +1962,9 @@ internal partial class MainWindow : Window
LaunchContextRecord launchContext = BuildLaunchContext(account, contextServer);
// Best-effort legacy write — last writer wins. The PID-specific
// writes inside the launch task are the authoritative path.
LaunchContextStore.WriteLegacy(launchContext);
// (Not for Headless: only an engine inside acclient reads it.)
if (!headless)
LaunchContextStore.WriteLegacy(launchContext);
if (!string.IsNullOrWhiteSpace(accountKey))
activeAccountKeys.Add(accountKey);
@ -1886,7 +1984,13 @@ internal partial class MainWindow : Window
var p = prepared[i];
Task launchTask;
if (!shouldInject)
if (p.Account.InjectionMode == InjectionMode.Headless)
{
// rynth-headless.exe whether or not auto-inject is on (there is nothing to inject).
launchTask = LaunchOneHeadlessAsync(p.Account, ResolveServerForAccount(p.Account), headlessExePath,
HeadlessLaunch.AcFolderFor(acPath), headlessPlugins, p.Summary, p.Context);
}
else if (!shouldInject)
{
launchTask = LaunchOneNoInjectAsync(p.Account, acPath, p.Args, p.Summary, p.Context);
}
@ -2165,6 +2269,293 @@ internal partial class MainWindow : Window
}
}
// ── Headless accounts (InjectionMode.Headless) ─────────────────────────
// One rynth-headless.exe per account, with a run config the launcher writes
// (HeadlessLaunch). No acclient, so none of its steps apply: no prefs swap,
// window title or placement, graphics readiness, injection or heartbeat log.
// The process writes its own session_<pid>.json (--launcher), so the session
// poll sees it like any client once FindClientProcesses lists it.
/// <summary>
/// Starts rynth-headless.exe for <paramref name="account"/>: writes the run config
/// (%APPDATA%\RynthCore\headless\launch_&lt;profile id&gt;.json, no password in it), starts
/// the process without a window, writes its launch context and pending session record, and
/// tracks the pid like the other launch paths (exit watch, quick-exit crash accounting).
/// </summary>
private async Task LaunchOneHeadlessAsync(
LaunchAccountProfile account,
LaunchServerProfile? server,
string exePath,
string? acFolder,
IReadOnlyList<string> plugins,
string launchSummary,
LaunchContextRecord launchContext)
{
string accountKey = BuildAccountKey(launchContext.AccountName, launchContext.ServerName);
LauncherDiag.Info($"LaunchOneHeadless ENTRY account='{launchContext.AccountName}' exe='{exePath}' plugins={plugins.Count} sessionPids={_launchedSessionPids.Count} pidInfo={_launchedPidInfo.Count}");
if (server == null)
{
AppendActivity($"Launch blocked for {account.DisplayName}: {AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0)}");
return;
}
var spec = new HeadlessRunSpec
{
Host = server.Host,
Port = server.Port,
ServerName = server.Name,
SuiteDir = _settings.HeadlessSuiteDir,
StatusDir = _settings.HeadlessStatusDir,
Plugins = plugins.ToList(),
Sessions =
{
new HeadlessSessionSpec
{
LauncherProfileId = account.Id,
Account = account.AccountName,
// "" = no auto-login for acclient; rynth-headless has no character screen to stop at, so it picks.
Character = string.IsNullOrWhiteSpace(launchContext.TargetCharacter) ? null : launchContext.TargetCharacter,
Commands = launchContext.OnLoginCommands?.ToList() ?? [],
StaySeconds = 0,
Reconnect = true,
},
},
};
string configPath = HeadlessLaunch.ConfigPath(AppSettingsStore.SettingsDirectoryPath, account.Id);
int? pid = null;
Exception? launchEx = null;
await Task.Run(() =>
{
try
{
HeadlessLaunch.WriteConfig(configPath, HeadlessLaunch.BuildConfigJson(spec));
var psi = new ProcessStartInfo(exePath)
{
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = Path.GetDirectoryName(exePath) ?? string.Empty
};
foreach (string arg in HeadlessLaunch.BuildArguments(configPath, acFolder))
psi.ArgumentList.Add(arg);
using Process? proc = Process.Start(psi);
if (proc != null)
{
// As the injected paths do from their suspended-launch callback. The process
// overwrites the session record with its own as soon as it is connecting.
LaunchContextStore.WriteForProcess(proc.Id, launchContext);
WritePendingSessionState(proc.Id, launchContext);
pid = proc.Id;
}
}
catch (Exception ex)
{
launchEx = ex;
}
});
if (launchEx != null || pid is not int trackedPid)
{
RecordCrash(accountKey);
string why = launchEx?.Message ?? "the process did not start";
AppendActivity($"Headless launch failed for {launchSummary}: {why}");
LauncherDiag.Info($"LaunchOneHeadless failed account='{launchContext.AccountName}': {why}");
return;
}
_launchedSessionPids.Add(trackedPid);
_launchedHeadlessPids.Add(trackedPid);
_launchedPidInfo[trackedPid] = (accountKey, DateTime.UtcNow);
RegisterPidExitWatch(trackedPid);
AppendActivity($"Headless launch complete for {launchSummary} (PID {trackedPid}).");
LauncherDiag.Info($"LaunchOneHeadless EXIT account='{launchContext.AccountName}' pid={trackedPid} config='{configPath}'");
}
/// <summary>Why <paramref name="account"/> can't run headless now (null = it can).</summary>
private string? HeadlessLaunchProblem(LaunchAccountProfile account)
{
LaunchServerProfile? server = ResolveServerForAccount(account);
if (server == null)
return AccountServerRules.NoServerMessage(account, _settings.ServerProfiles.Count > 0);
if (server.Emulator == AcEmulatorKind.Gdle)
return $"Headless runs on ACE servers only, and {server.DisplayName} is a GDLE server. Pick RynthCore or Decal for this account.";
if (string.IsNullOrWhiteSpace(server.Host) || server.Port <= 0)
return $"the server profile {server.DisplayName} needs a host and a port.";
if (AcLaunchArgumentBuilder.AccountNameProblem(account.AccountName, AcEmulatorKind.Ace) is string nameProblem)
return nameProblem;
// rynth-headless decrypts the saved password itself; check now that this Windows user can.
if (account.PasswordNeedsReentry ||
(!string.IsNullOrEmpty(account.PasswordProtected) && !AccountPasswordProtection.CanUnprotect(account.PasswordProtected)))
{
account.PasswordNeedsReentry = true;
return LaunchAccountProfile.PasswordNeedsReentryMessage(account.AccountName);
}
return null;
}
/// <summary>Logs why a Headless launch of <paramref name="account"/> was refused; automatic launches at most every few minutes.</summary>
private void NoteHeadlessRefusal(LaunchAccountProfile account, bool isAutomaticLaunch, string problem)
{
DateTime nowUtc = DateTime.UtcNow;
if (isAutomaticLaunch &&
_headlessRefusalNoticeTimesUtc.TryGetValue(account.Id, out DateTime lastUtc) &&
nowUtc - lastUtc < AutoLaunchNeedsPasswordLogCooldown)
{
return;
}
_headlessRefusalNoticeTimesUtc[account.Id] = nowUtc;
AppendActivity($"{(isAutomaticLaunch ? "Auto launch skipped" : "Launch blocked")} for {account.DisplayName} (Headless): {problem}");
}
/// <summary>The Runtime tab's headless plugin box: one DLL path per line, blank lines and surrounding quotes dropped.</summary>
private List<string> ReadHeadlessPluginPathsBox() =>
(HeadlessPluginPathsTextBox.Text ?? string.Empty)
.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Trim().Trim('"').Trim())
.Where(line => line.Length > 0)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
/// <summary>
/// acclient.exe and rynth-headless.exe processes: every client the launcher tracks sessions,
/// account keys and auto-launch against. Also refreshes <see cref="_headlessClientPids"/>.
/// Steps that only apply to acclient (window, injection, heartbeat log) filter with
/// <see cref="IsHeadlessPid"/> / <see cref="AcClientsOnly"/>. The caller disposes the array.
/// </summary>
private Process[] FindClientProcesses()
{
Process[] acClients = _injector.FindTargetProcesses();
Process[] headless;
try { headless = Process.GetProcessesByName(HeadlessLaunch.ProcessName); }
catch { headless = []; }
_headlessClientPids.Clear();
foreach (Process p in headless)
{
try { _headlessClientPids.Add(p.Id); } catch { }
}
return headless.Length == 0 ? acClients : [.. acClients, .. headless];
}
/// <summary>True for a rynth-headless process (seen in the last enumeration, or launched as one here).</summary>
private bool IsHeadlessPid(int pid) => _headlessClientPids.Contains(pid) || _launchedHeadlessPids.Contains(pid);
/// <summary>
/// A rynth-headless.exe (from the last FindClientProcesses) already running this account's launch
/// config. One a previous launcher started isn't in <see cref="_launchedHeadlessPids"/>, and its
/// session records carry the headless client's own per-character ids, so HasTrackedPresence misses
/// it: auto launch then started a second one for the same account, which died at once on the
/// first one's open log (2026-10-30/31), and could otherwise have logged the account in twice.
/// </summary>
private bool HeadlessAlreadyRunning(LaunchAccountProfile account)
{
if (_headlessClientPids.Count == 0) return false;
string config = HeadlessLaunch.ConfigPath(AppSettingsStore.SettingsDirectoryPath, account.Id);
foreach (int pid in _headlessClientPids)
{
string? cmd = CrashDumpWriters.TryGetCommandLine(pid);
if (cmd != null && cmd.Contains(config, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// Runtime > Headless client > Log out headless clients: a headless client has no window to close,
/// so every running rynth-headless gets the stop request (<see cref="EndClientProcess"/>: log out,
/// exit, killed after the grace time).
/// </summary>
private void StopHeadlessClients()
{
Process[] clients = FindClientProcesses();
int asked = 0;
try
{
foreach (Process p in clients)
{
int pid;
try { pid = p.Id; } catch { continue; }
if (!_headlessClientPids.Contains(pid))
continue;
try
{
EndClientProcess(p, pid);
asked++;
}
catch (Exception ex)
{
AppendActivity($"PID {pid} (headless): could not stop it: {ex.Message}");
}
}
}
finally
{
foreach (Process p in clients) p.Dispose();
}
AppendActivity(asked == 0
? "No headless client is running."
: $"Asked {asked} headless client(s) to log out." +
(_settings.AutoLaunch ? " AutoLaunch is on: checked accounts are started again." : ""));
}
private Process[] AcClientsOnly(Process[] targets) =>
_headlessClientPids.Count == 0 && _launchedHeadlessPids.Count == 0
? targets
: targets.Where(p => { try { return !IsHeadlessPid(p.Id); } catch { return false; } }).ToArray();
/// <summary>
/// Ends a client the launcher has decided to take down. acclient: killed at once. rynth-headless:
/// asked to log every character out and exit (its stop event), and killed after
/// <see cref="HeadlessLaunch.StopGrace"/> if it is still running; killed at once when it has no
/// stop event. Throws as Process.Kill does.
/// </summary>
private void EndClientProcess(Process process, int pid)
{
if (!IsHeadlessPid(pid))
{
process.Kill();
return;
}
if (!HeadlessLaunch.TrySignalStop(pid))
{
AppendActivity($"PID {pid} (headless) has no stop channel; killing it.");
process.Kill();
return;
}
DateTime startedUtc = GetProcessStartTimeUtc(process);
AppendActivity($"PID {pid} (headless): asked to log out and exit; killed in {HeadlessLaunch.StopGrace.TotalSeconds:0} s if still running.");
_ = KillHeadlessAfterGraceAsync(pid, startedUtc);
}
private async Task KillHeadlessAfterGraceAsync(int pid, DateTime startedUtc)
{
await Task.Delay(HeadlessLaunch.StopGrace);
try
{
using Process p = Process.GetProcessById(pid);
// The same process (not a recycled pid): name and start time match.
if (p.HasExited ||
!string.Equals(p.ProcessName, HeadlessLaunch.ProcessName, StringComparison.OrdinalIgnoreCase) ||
Math.Abs((GetProcessStartTimeUtc(p) - startedUtc).TotalSeconds) > 1)
{
return;
}
AppendActivity($"PID {pid} (headless) still running {HeadlessLaunch.StopGrace.TotalSeconds:0} s after the stop request; killing it.");
LauncherDiag.Info($"HEADLESS: PID {pid} ignored the stop request for {HeadlessLaunch.StopGrace.TotalSeconds:0} s - killed.");
p.Kill();
}
catch (ArgumentException)
{
// Already gone.
}
catch (Exception ex)
{
AppendActivity($"PID {pid} (headless): kill after the stop request failed: {ex.Message}");
}
}
/// <summary>
/// Shows the First Login dialog for <paramref name="account"/> (no usable password). True when
/// the player entered one: the profile is updated and saved (password encrypted at once).
@ -3103,7 +3494,7 @@ internal partial class MainWindow : Window
int running = RynthCoreClientsRunning();
if (running > 0)
{
AppendActivity($"Close your {running} game client(s) running RynthCore or its Decal bridge first: the update replaces files they have open.");
AppendActivity($"Close your {running} game client(s) running RynthCore or its Decal bridge (headless ones included) first: the update replaces files they have open.");
RefreshUpdateCard();
return;
}
@ -3149,6 +3540,17 @@ internal partial class MainWindow : Window
catch { }
finally { p.Dispose(); }
}
// Headless clients (rynth-headless.exe) run RynthCore code and plugins from the install
// too; no module check needed (and an x86 launcher can't list an x64 process's modules).
try
{
foreach (Process p in Process.GetProcessesByName(HeadlessLaunch.ProcessName))
{
n++;
p.Dispose();
}
}
catch { }
return n;
}
@ -3360,7 +3762,9 @@ internal partial class MainWindow : Window
Process[] targets;
try
{
targets = _injector.FindTargetProcesses();
// rynth-headless.exe too: its session file would otherwise be deleted as stale every
// tick, and auto-launch would start the account again and again.
targets = FindClientProcesses();
}
catch (Exception ex)
{
@ -3369,11 +3773,15 @@ internal partial class MainWindow : Window
}
HashSet<int> activePids = targets.Select(process => process.Id).ToHashSet();
// acclient.exe only: window, injection and heartbeat-log steps below.
Process[] acTargets = AcClientsOnly(targets);
LaunchContextStore.DeleteStaleProcessFiles(activePids);
SessionStateStore.DeleteStaleProcessFiles(activePids);
Dictionary<int, LaunchContextRecord> activeContexts = LaunchContextStore.ReadForActiveProcesses(activePids);
Dictionary<int, SessionStateRecord> activeSessions = SessionStateStore.ReadForActiveProcesses(activePids);
DetectQuickExits(activePids);
// After DetectQuickExits (which asks whether an exited pid was headless): a recycled pid starts fresh.
_launchedHeadlessPids.RemoveWhere(pid => !activePids.Contains(pid));
// Audit trail for vanished PIDs: log each removal so a "did the
// launcher kill this client?" question has a concrete answer. The
@ -3415,16 +3823,24 @@ internal partial class MainWindow : Window
}
}
AcStatusText.Text = targets.Length switch
int headlessCount = targets.Length - acTargets.Length;
AcStatusText.Text = (targets.Length switch
{
0 => "No running AC clients detected.",
1 => "1 AC client is running.",
_ => $"{targets.Length} AC clients are running."
};
}) + (headlessCount > 0 ? $" ({headlessCount} headless)" : string.Empty);
_sessionItems.Clear();
foreach (Process process in targets.OrderBy(p => p.Id))
{
// Headless: no window, no D3D device. Listed, but none of the window steps apply.
if (IsHeadlessPid(process.Id))
{
_sessionItems.Add($"PID {process.Id} | {DescribeSessionOrigin(process, activeContexts, activeSessions)} | headless");
continue;
}
bool graphicsReady = _injector.TryDescribeGraphicsReadiness(process, out string status);
string readiness = graphicsReady ? "graphics ready" : SimplifyReadinessStatus(status);
string origin = DescribeSessionOrigin(process, activeContexts, activeSessions);
@ -3441,9 +3857,11 @@ internal partial class MainWindow : Window
UpdateLaunchTargetStatuses(targets, activeContexts, activeSessions);
MaybeQueueAutoLaunch(activeContexts, activeSessions);
MaybeAutoInjectExternalClients(targets, activePids, activeContexts, activeSessions);
MaybeKillStuckClients(targets, activeContexts, activeSessions);
MaybeRestartWedgedClients(targets, activeContexts, activeSessions);
// acclient only: injection, the not-responding window check and the engine heartbeat log
// mean nothing for rynth-headless (it reconnects by itself; the stop event ends it).
MaybeAutoInjectExternalClients(acTargets, activePids, activeContexts, activeSessions);
MaybeKillStuckClients(acTargets, activeContexts, activeSessions);
MaybeRestartWedgedClients(acTargets, activeContexts, activeSessions);
// Dispose this tick's Process handles. FindTargetProcesses() allocates fresh
// System.Diagnostics.Process objects (each holds a native OS handle); on the 2s
@ -3469,6 +3887,8 @@ internal partial class MainWindow : Window
/// heuristic would falsely reap working Decal sessions)
/// - <see cref="SessionStateRecord.IsLoggedIn"/> is still false
/// - Time-since-launch exceeds the configured timeout
/// Headless clients (rynth-headless) are never passed in (RefreshSessionState filters
/// them) and their profiles say Headless, not RynthCore.
/// </summary>
private void MaybeKillStuckClients(
IReadOnlyList<Process> targets,
@ -3565,7 +3985,7 @@ internal partial class MainWindow : Window
try
{
AppendActivity($"Killing stuck PID {pid} ({accountName}) — {reason} and window is not responding.");
process.Kill();
EndClientProcess(process, pid); // a headless client is asked to stop first (never reaches here today)
_launchedSessionPids.Remove(pid);
_launchedPidInfo.Remove(pid);
@ -3904,7 +4324,7 @@ internal partial class MainWindow : Window
AppendActivity($"Wedge restart: killing PID {pid} ({accountName ?? "?"}) — {reason}."
+ (_settings.AutoLaunch ? " Auto-launch will relaunch it." : " AutoLaunch is OFF — enable it for automatic relaunch."));
LauncherDiag.Info($"WEDGE: PID {pid} ({accountName ?? "?"}) killed — {reason}");
process.Kill();
EndClientProcess(process, pid); // a headless client is asked to stop first (never reaches here today)
_launchedSessionPids.Remove(pid);
_launchedPidInfo.Remove(pid);
@ -4068,6 +4488,18 @@ internal partial class MainWindow : Window
{
try
{
// Headless: no acclient command line; rynth-headless gets a run config (no password in it).
if (account.InjectionMode == InjectionMode.Headless)
{
if (server.Emulator == AcEmulatorKind.Gdle)
return $"Headless runs on ACE servers only, and {server.DisplayName} is a GDLE server.";
if (AcLaunchArgumentBuilder.NeedsPassword(account))
return AcLaunchArgumentBuilder.MissingPasswordMessage(account.AccountName);
return $"{HeadlessLaunch.ExeName} " + string.Join(" ", HeadlessLaunch.BuildArguments(
HeadlessLaunch.ConfigPath(AppSettingsStore.SettingsDirectoryPath, account.Id),
HeadlessLaunch.AcFolderFor(AcClientPathTextBox.Text)).Select(a => a.Contains(' ') ? $"\"{a}\"" : a));
}
// Never decrypts: a saved password shows as the mask. Extra Launch Arguments follow,
// as they do at launch.
string masked = _launchArgumentBuilder.BuildMaskedArguments(server, account);
@ -4085,16 +4517,17 @@ internal partial class MainWindow : Window
private HashSet<string> GetActiveAccountKeys()
{
Process[] targets = _injector.FindTargetProcesses();
Process[] targets = FindClientProcesses();
HashSet<int> activePids = targets.Select(process => process.Id).ToHashSet();
// Processes whose window is gone but whose OS process is still alive
// (slow native shutdown, crash dump collection, etc.) should not block
// relaunch for their account. Only applies to PIDs that completed at
// least one login — startup-phase clients keep blocking normally.
// Headless clients never have a window: they count while they run.
foreach (Process p in targets)
{
if (!_everLoggedInPids.Contains(p.Id))
if (!_everLoggedInPids.Contains(p.Id) || IsHeadlessPid(p.Id))
continue;
try
{
@ -4295,6 +4728,11 @@ internal partial class MainWindow : Window
LauncherDiag.Info($"DetectQuickExits: PID {entry.Key} ({entry.Value.AccountKey}) uptime={uptime.TotalSeconds:F1}s -> RecordCrash. crashHist now {hist}.");
RecoverFailedPrefsSwap(entry.Key, entry.Value.AccountKey, uptime);
}
else if (!string.IsNullOrEmpty(entry.Value.AccountKey) && _launchedHeadlessPids.Contains(entry.Key))
{
// Headless: no acclient ran, so the live UserPreferences.ini isn't this account's.
LauncherDiag.Info($"DetectQuickExits: PID {entry.Key} ({entry.Value.AccountKey}) uptime={uptime.TotalSeconds:F1}s -> normal close (headless, no prefs snapshot).");
}
else if (!string.IsNullOrEmpty(entry.Value.AccountKey))
{
LauncherDiag.Info($"DetectQuickExits: PID {entry.Key} ({entry.Value.AccountKey}) uptime={uptime.TotalSeconds:F1}s -> normal close, snapshotting prefs.");
@ -4894,7 +5332,7 @@ internal partial class MainWindow : Window
foreach (LaunchAccountProfile account in GetCheckedLaunchAccounts())
{
LaunchServerProfile? server = ResolveServerForAccount(account);
if (HasTrackedPresence(account, server, activeContexts, activeSessions))
if (HasTrackedPresence(account, server, activeContexts, activeSessions) || HeadlessAlreadyRunning(account))
continue;
// No server profile (deleted, or never picked): never launched on another server.
@ -5031,7 +5469,7 @@ internal partial class MainWindow : Window
// Dispose the Process[] only if WE allocated it here (standalone call). When
// called from RefreshSessionState the array is passed in and that caller owns it.
bool ownTargets = targets is null;
targets ??= _injector.FindTargetProcesses();
targets ??= FindClientProcesses(); // headless clients have session files too
HashSet<int> activePids = targets.Select(process => process.Id).ToHashSet();
activeContexts ??= LaunchContextStore.ReadForActiveProcesses(activePids);

View file

@ -69,6 +69,8 @@
<Compile Include="..\RynthCore.App\AppSettings.cs" Link="Shared\AppSettings.cs" />
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
<Compile Include="..\RynthCore.App\HeadlessAccountModes.cs" Link="Shared\HeadlessAccountModes.cs" />
<Compile Include="..\RynthCore.App\HeadlessLaunch.cs" Link="Shared\HeadlessLaunch.cs" />
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
<!-- The plugin API of the engine installed with this launcher (RynthUpdater.InstalledEngineApi). -->
<Compile Include="..\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Shared\PluginContractVersion.cs" />

View file

@ -82,6 +82,25 @@ internal sealed class AppSettings
/// </summary>
public string? AppliedInstallerPluginRegistration { get; set; }
// ── Headless accounts (InjectionMode.Headless, experimental; HeadlessLaunch) ──
// Plain values with "use the default" defaults: launchers without Headless ignore them.
/// rynth-headless.exe. Empty = &lt;launcher folder&gt;\Headless\rynth-headless.exe.
public string HeadlessExePath { get; set; } = string.Empty;
/// Plugin DLLs every Headless account loads. x64 builds (rynth-headless is a 64-bit
/// process), not the x86 ones in PluginDllPaths. Empty = the ones the installer ships in
/// &lt;launcher folder&gt;\Headless\plugins (HeadlessLaunch.DefaultPluginPaths: RynthAi).
public List<string> HeadlessPluginPaths { get; set; } = [];
/// The plugins' RynthSuite folder (the run config's suiteDir). Empty = rynth-headless's default,
/// %LOCALAPPDATA%\RynthCore\headless.
public string HeadlessSuiteDir { get; set; } = string.Empty;
/// Where rynth-headless writes per-character status files (statusDir). Empty = its default,
/// &lt;RynthCore&gt;\Logs\status (the game clients' and the StatusAgent's folder).
public string HeadlessStatusDir { get; set; } = string.Empty;
public List<LaunchServerProfile> ServerProfiles { get; set; } = [];
public List<LaunchAccountProfile> AccountProfiles { get; set; } = [];

View file

@ -15,7 +15,8 @@ internal static class AppSettingsStore
Converters =
{
// Before the general enum converter: InjectionMode is written so that every
// launcher can read it ("Decal + RynthCore" lives in decal-accounts.json).
// launcher can read it ("Decal + RynthCore" lives in decal-accounts.json,
// Headless in headless-accounts.json).
new SharedInjectionModeConverter(),
new JsonStringEnumConverter()
}
@ -30,6 +31,13 @@ internal static class AppSettingsStore
private static string SettingsPath => Path.Combine(SettingsDirectory, "appsettings.json");
private static string BackupPath => SettingsPath + ".bak";
private static string DecalAccountsPath => DecalAccountModes.PathIn(SettingsDirectory);
private static string HeadlessAccountsPath => HeadlessAccountModes.PathIn(SettingsDirectory);
/// <summary>
/// The folder appsettings.json lives in (%APPDATA%\RynthCore, or <see cref="DirectoryOverride"/>).
/// Other launcher files that tests redirect along with it go here too (the headless run configs).
/// </summary>
internal static string SettingsDirectoryPath => SettingsDirectory;
/// <summary>
/// Set when the last Load() hit a corrupt/unreadable file (quarantined it,
@ -42,7 +50,8 @@ internal static class AppSettingsStore
/// <summary>
/// Set when the last Load() moved "Decal + RynthCore" accounts out of appsettings.json
/// into decal-accounts.json (a file written by a pre-release Decal bridge build), or found
/// decal-accounts.json unreadable. Null otherwise.
/// decal-accounts.json unreadable; the same for Headless accounts and headless-accounts.json.
/// Null otherwise.
/// </summary>
public static string? LastMigrationNote { get; private set; }
@ -65,9 +74,10 @@ internal static class AppSettingsStore
LastMigrationNote = null;
LastPasswordMigrationNote = null;
LastPasswordProblemNote = null;
// Passwords after the Decal accounts: a save before ApplyDecalAccounts would drop
// decal-accounts.json (every account still reads as RynthCore at that point).
AppSettings settings = ApplyDecalAccounts(LoadShared());
// Passwords after the Decal and Headless accounts: a save before ApplyAccountModeFiles
// would drop decal-accounts.json and headless-accounts.json (every account still reads
// as RynthCore at that point).
AppSettings settings = ApplyAccountModeFiles(LoadShared());
MigratePasswords(settings);
return settings;
}
@ -208,36 +218,47 @@ internal static class AppSettingsStore
}
/// <summary>
/// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json (those that
/// appsettings.json still lists as RynthCore). An appsettings.json that itself says
/// "DecalBridge" (written by a pre-release bridge build) is rewritten at once, .bak
/// included, so no launcher finds that value there again.
/// Puts back the "Decal + RynthCore" accounts listed in decal-accounts.json and the Headless
/// accounts listed in headless-accounts.json (those that appsettings.json still lists as
/// RynthCore; an id in both files is Decal + RynthCore). An appsettings.json that itself says
/// "DecalBridge" (written by a pre-release bridge build) or "Headless" is rewritten at once,
/// .bak included, so no launcher finds that value there again.
/// </summary>
private static AppSettings ApplyDecalAccounts(AppSettings settings)
private static AppSettings ApplyAccountModeFiles(AppSettings settings)
{
List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>();
int legacy = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge);
int legacyDecal = accounts.Count(a => a.InjectionMode == InjectionMode.DecalBridge);
int legacyHeadless = accounts.Count(a => a.InjectionMode == InjectionMode.Headless);
HashSet<string> ids = DecalAccountModes.ReadIds(DecalAccountsPath, out string? error);
if (error != null)
LastMigrationNote = error;
HashSet<string> decalIds = DecalAccountModes.ReadIds(DecalAccountsPath, out string? decalError);
HashSet<string> headlessIds = HeadlessAccountModes.ReadIds(HeadlessAccountsPath, out string? headlessError);
if (decalError != null || headlessError != null)
LastMigrationNote = string.Join(" ", new[] { decalError, headlessError }.Where(e => e != null));
foreach (LaunchAccountProfile account in accounts)
if (DecalAccountModes.IsDecalBridge(ids, account.Id, account.InjectionMode))
account.InjectionMode = InjectionMode.DecalBridge;
if (legacy > 0)
{
if (DecalAccountModes.IsDecalBridge(decalIds, account.Id, account.InjectionMode))
account.InjectionMode = InjectionMode.DecalBridge;
else if (HeadlessAccountModes.IsHeadless(headlessIds, account.Id, account.InjectionMode))
account.InjectionMode = InjectionMode.Headless;
}
if (legacyDecal + legacyHeadless > 0)
{
var moved = new List<string>(2);
if (legacyDecal > 0)
moved.Add($"{legacyDecal} \"Decal + RynthCore\" account(s) to {DecalAccountModes.FileName}");
if (legacyHeadless > 0)
moved.Add($"{legacyHeadless} Headless account(s) to {HeadlessAccountModes.FileName}");
string what = string.Join(" and ", moved);
try
{
Save(settings);
File.Copy(SettingsPath, BackupPath, overwrite: true);
LastMigrationNote = $"Moved {legacy} \"Decal + RynthCore\" account(s) from appsettings.json to " +
$"{DecalAccountModes.FileName}, so older launchers can still read appsettings.json.";
LastMigrationNote = $"Moved {what} from appsettings.json, so older launchers can still read appsettings.json.";
}
catch (Exception ex)
{
LastMigrationNote = $"Could not move \"Decal + RynthCore\" accounts to {DecalAccountModes.FileName} " +
$"({ex.GetType().Name}: {ex.Message}); the next save retries.";
LastMigrationNote = $"Could not move {what} ({ex.GetType().Name}: {ex.Message}); the next save retries.";
}
}
return settings;
@ -245,13 +266,15 @@ internal static class AppSettingsStore
public static void Save(AppSettings settings)
{
// "Decal + RynthCore" accounts go to decal-accounts.json first; appsettings.json
// lists them as RynthCore (SharedInjectionModeConverter).
// "Decal + RynthCore" accounts go to decal-accounts.json and Headless accounts to
// headless-accounts.json first; appsettings.json lists both as RynthCore
// (SharedInjectionModeConverter).
Directory.CreateDirectory(SettingsDirectory);
List<LaunchAccountProfile> accounts = settings.AccountProfiles ?? new List<LaunchAccountProfile>();
DecalAccountModes.WriteIds(DecalAccountsPath,
(settings.AccountProfiles ?? new List<LaunchAccountProfile>())
.Where(a => a.InjectionMode == InjectionMode.DecalBridge)
.Select(a => a.Id));
accounts.Where(a => a.InjectionMode == InjectionMode.DecalBridge).Select(a => a.Id));
HeadlessAccountModes.WriteIds(HeadlessAccountsPath,
accounts.Where(a => a.InjectionMode == InjectionMode.Headless).Select(a => a.Id));
// Atomic write: serialize to a temp file, then swap it in. A crash or
// power cut mid-write can no longer truncate the live file (which holds
@ -266,9 +289,9 @@ internal static class AppSettingsStore
}
/// <summary>
/// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge is
/// written as <see cref="DecalAccountModes.SharedMode"/> (decal-accounts.json holds the real
/// choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore
/// InjectionMode in appsettings.json. Writes only names every launcher knows: DecalBridge and
/// Headless are written as <see cref="AccountModeSidecar.SharedMode"/> (decal-accounts.json and
/// headless-accounts.json hold the real choice). Reads names and numbers; a name or number this build doesn't know reads as RynthCore
/// instead of making the whole file unreadable.
/// </summary>
private sealed class SharedInjectionModeConverter : JsonConverter<InjectionMode>
@ -288,7 +311,9 @@ internal static class AppSettingsStore
public override void Write(Utf8JsonWriter writer, InjectionMode value, JsonSerializerOptions options)
{
InjectionMode shared = value == InjectionMode.DecalBridge ? DecalAccountModes.SharedMode : value;
InjectionMode shared = value is InjectionMode.DecalBridge or InjectionMode.Headless
? AccountModeSidecar.SharedMode
: value;
writer.WriteStringValue(shared.ToString());
}
}

View file

@ -21,38 +21,80 @@ namespace RynthCore.App;
/// An entry only counts while appsettings.json still says RynthCore for that account: an older
/// launcher that switched the account to Decal (or that deleted it) wins, and the next save of a
/// newer launcher drops the stale entry. Shared with the injector (LaunchCommand).
/// "Headless" accounts follow the same rules in a file of their own (HeadlessAccountModes.cs).
/// </summary>
internal static class DecalAccountModes
{
public const string FileName = "decal-accounts.json";
/// <summary>What appsettings.json says for a "Decal + RynthCore" account.</summary>
public const InjectionMode SharedMode = InjectionMode.RynthCore;
public const InjectionMode SharedMode = AccountModeSidecar.SharedMode;
private const int SchemaVersion = 1;
private const string Note =
private static readonly AccountModeSidecar Sidecar = new(
FileName,
"DecalBridgeAccountIds",
"Accounts the RynthCore launcher runs as \"Decal + RynthCore\" (experimental). " +
"appsettings.json lists them as RynthCore, so launchers without that mode can still read it. " +
"Delete this file to set them all back to RynthCore.";
"Delete this file to set them all back to RynthCore.");
private sealed class FileModel
{
public int Version { get; set; } = SchemaVersion;
public string Note { get; set; } = DecalAccountModes.Note;
public List<string> DecalBridgeAccountIds { get; set; } = new();
}
private static readonly JsonSerializerOptions WriteOptions = new() { WriteIndented = true };
public static string PathIn(string settingsDirectory) => Path.Combine(settingsDirectory, FileName);
public static string PathIn(string settingsDirectory) => Sidecar.PathIn(settingsDirectory);
/// <summary>
/// The account ids listed in <paramref name="path"/>. An absent file is an empty set; an
/// unreadable one too, with the reason in <paramref name="error"/> (the accounts then run
/// as appsettings.json says, which is RynthCore).
/// </summary>
public static HashSet<string> ReadIds(string path, out string? error)
public static HashSet<string> ReadIds(string path, out string? error) => Sidecar.ReadIds(path, out error);
/// <summary>
/// True when an account that appsettings.json lists with <paramref name="sharedMode"/> is a
/// "Decal + RynthCore" account: it is in <paramref name="ids"/> and still says RynthCore.
/// </summary>
public static bool IsDecalBridge(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
AccountModeSidecar.Lists(ids, accountId, sharedMode);
/// <summary>
/// Records <paramref name="ids"/> as the "Decal + RynthCore" accounts. Writes only when the
/// list changed; with no accounts left, the file is removed. Atomic (temp file + swap).
/// </summary>
public static void WriteIds(string path, IEnumerable<string> ids) => Sidecar.WriteIds(path, ids);
}
/// <summary>
/// One file beside appsettings.json listing the account ids that really run in a mode older
/// launchers don't know (appsettings.json says <see cref="SharedMode"/> for them). Used by
/// DecalAccountModes (decal-accounts.json) and HeadlessAccountModes (headless-accounts.json).
/// Each mode has a file of its own, so a launcher that knows only one of them never rewrites the
/// other's list. File: { "Version": 1, "Note": "...", "&lt;IdsProperty&gt;": [ "id", ... ] }.
/// </summary>
internal sealed class AccountModeSidecar
{
/// <summary>What appsettings.json says for an account listed in a sidecar.</summary>
public const InjectionMode SharedMode = InjectionMode.RynthCore;
private const int SchemaVersion = 1;
private static readonly JsonWriterOptions WriteOptions = new() { Indented = true };
public AccountModeSidecar(string fileName, string idsProperty, string note)
{
FileName = fileName;
IdsProperty = idsProperty;
Note = note;
}
public string FileName { get; }
public string IdsProperty { get; }
public string Note { get; }
public string PathIn(string settingsDirectory) => Path.Combine(settingsDirectory, FileName);
/// <summary>True when <paramref name="accountId"/> is in <paramref name="ids"/> and appsettings.json still says RynthCore for it.</summary>
public static bool Lists(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
sharedMode == SharedMode && !string.IsNullOrEmpty(accountId) && ids.Contains(accountId);
/// <summary>The ids listed in <paramref name="path"/>: absent = none; unreadable = none, with the reason in <paramref name="error"/>.</summary>
public HashSet<string> ReadIds(string path, out string? error)
{
error = null;
var ids = new HashSet<string>(StringComparer.Ordinal);
@ -60,10 +102,26 @@ internal static class DecalAccountModes
{
if (!File.Exists(path))
return ids;
FileModel? model = JsonSerializer.Deserialize<FileModel>(File.ReadAllText(path));
foreach (string id in model?.DecalBridgeAccountIds ?? new List<string>())
using JsonDocument document = JsonDocument.Parse(File.ReadAllText(path));
JsonElement root = document.RootElement;
if (root.ValueKind == JsonValueKind.Null)
return ids;
if (root.ValueKind != JsonValueKind.Object)
throw new JsonException($"expected an object, found {root.ValueKind}");
if (!root.TryGetProperty(IdsProperty, out JsonElement list) || list.ValueKind == JsonValueKind.Null)
return ids;
if (list.ValueKind != JsonValueKind.Array)
throw new JsonException($"{IdsProperty}: expected a list, found {list.ValueKind}");
foreach (JsonElement item in list.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
continue;
if (item.ValueKind != JsonValueKind.String)
throw new JsonException($"{IdsProperty}: expected text, found {item.ValueKind}");
string? id = item.GetString();
if (!string.IsNullOrWhiteSpace(id))
ids.Add(id);
}
}
catch (Exception ex)
{
@ -75,17 +133,10 @@ internal static class DecalAccountModes
}
/// <summary>
/// True when an account that appsettings.json lists with <paramref name="sharedMode"/> is a
/// "Decal + RynthCore" account: it is in <paramref name="ids"/> and still says RynthCore.
/// Records <paramref name="ids"/>. Writes only when the list changed; with no accounts left,
/// the file is removed. Atomic (temp file + swap).
/// </summary>
public static bool IsDecalBridge(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
sharedMode == SharedMode && !string.IsNullOrEmpty(accountId) && ids.Contains(accountId);
/// <summary>
/// Records <paramref name="ids"/> as the "Decal + RynthCore" accounts. Writes only when the
/// list changed; with no accounts left, the file is removed. Atomic (temp file + swap).
/// </summary>
public static void WriteIds(string path, IEnumerable<string> ids)
public void WriteIds(string path, IEnumerable<string> ids)
{
List<string> sorted = ids.Where(id => !string.IsNullOrWhiteSpace(id))
.Distinct(StringComparer.Ordinal)
@ -107,7 +158,18 @@ internal static class DecalAccountModes
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(new FileModel { DecalBridgeAccountIds = sorted }, WriteOptions));
using (var stream = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new Utf8JsonWriter(stream, WriteOptions))
{
writer.WriteStartObject();
writer.WriteNumber("Version", SchemaVersion);
writer.WriteString("Note", Note);
writer.WriteStartArray(IdsProperty);
foreach (string id in sorted)
writer.WriteStringValue(id);
writer.WriteEndArray();
writer.WriteEndObject();
}
File.Move(tmp, path, overwrite: true);
}
}

View file

@ -0,0 +1,43 @@
using System.Collections.Generic;
namespace RynthCore.App;
/// <summary>
/// Which accounts run headless (<see cref="InjectionMode.Headless"/>: rynth-headless.exe instead
/// of acclient.exe), kept in <c>headless-accounts.json</c> next to appsettings.json and keyed by
/// account profile id. The same arrangement as "Decal + RynthCore" (DecalAccountModes, which
/// explains why): appsettings.json lists a Headless account as RynthCore, so every launcher and
/// the injector can still read it, and this file says which of those are really Headless. An
/// entry only counts while appsettings.json still says RynthCore for that account.
///
/// A file of its own rather than a second list in decal-accounts.json: a launcher that knows the
/// Decal bridge but not Headless rewrites decal-accounts.json with only its own list, and would
/// drop the Headless one. It never touches this file. (Such a launcher launches a Headless
/// account as RynthCore in acclient.exe, which is what its appsettings.json entry says.)
/// </summary>
internal static class HeadlessAccountModes
{
public const string FileName = "headless-accounts.json";
/// <summary>What appsettings.json says for a Headless account.</summary>
public const InjectionMode SharedMode = AccountModeSidecar.SharedMode;
private static readonly AccountModeSidecar Sidecar = new(
FileName,
"HeadlessAccountIds",
"Accounts the RynthCore launcher runs headless (rynth-headless.exe, experimental). " +
"appsettings.json lists them as RynthCore, so launchers without that mode can still read it. " +
"Delete this file to set them all back to RynthCore.");
public static string PathIn(string settingsDirectory) => Sidecar.PathIn(settingsDirectory);
/// <summary>The account ids listed in <paramref name="path"/> (absent or unreadable = none; see <paramref name="error"/>).</summary>
public static HashSet<string> ReadIds(string path, out string? error) => Sidecar.ReadIds(path, out error);
/// <summary>True when an account appsettings.json lists with <paramref name="sharedMode"/> is a Headless account.</summary>
public static bool IsHeadless(IReadOnlySet<string> ids, string? accountId, InjectionMode sharedMode) =>
AccountModeSidecar.Lists(ids, accountId, sharedMode);
/// <summary>Records <paramref name="ids"/> as the Headless accounts (only when changed; none left = file removed).</summary>
public static void WriteIds(string path, IEnumerable<string> ids) => Sidecar.WriteIds(path, ids);
}

View file

@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading;
namespace RynthCore.App;
/// <summary>One character of a headless run config (one "sessions" entry).</summary>
internal sealed class HeadlessSessionSpec
{
/// <summary>LaunchAccountProfile.Id: rynth-headless --launcher reads that profile's saved password.</summary>
public string LauncherProfileId { get; set; } = string.Empty;
public string Account { get; set; } = string.Empty;
/// <summary>The character to log in; null/empty = rynth-headless picks.</summary>
public string? Character { get; set; }
/// <summary>Chat commands sent after login (the account's OnLogin commands for that character).</summary>
public List<string> Commands { get; set; } = new();
/// <summary>0 = stay until stopped.</summary>
public int StaySeconds { get; set; }
public bool Reconnect { get; set; } = true;
}
/// <summary>What one rynth-headless process runs: the server, the plugins and its characters.</summary>
internal sealed class HeadlessRunSpec
{
public string Host { get; set; } = string.Empty;
public int Port { get; set; }
/// <summary>The launcher's server profile Name (what session files and the account keys use).</summary>
public string ServerName { get; set; } = string.Empty;
/// <summary>Empty = left out, so rynth-headless uses its default.</summary>
public string SuiteDir { get; set; } = string.Empty;
/// <summary>Empty = left out, so rynth-headless uses its default.</summary>
public string StatusDir { get; set; } = string.Empty;
public List<string> Plugins { get; set; } = new();
public List<HeadlessSessionSpec> Sessions { get; set; } = new();
}
/// <summary>
/// The launcher side of <see cref="InjectionMode.Headless"/>, without the UI: where
/// rynth-headless.exe is, the run config the launcher writes for an account, its command line,
/// and the stop channel. BCL only: rynth-headless (src\RynthCore.Headless.Cli) compiles this file
/// too, so both sides agree on the stop event's name.
///
/// The launcher runs one rynth-headless process per Headless account:
/// rynth-headless.exe run --config %APPDATA%\RynthCore\headless\launch_&lt;profile id&gt;.json
/// --launcher [--ac-folder &lt;AC folder&gt;]
/// --launcher: the process writes sessions\session_&lt;its pid&gt;.json and the character cache as the
/// engine does, and reads the account's password from appsettings.json by launcherProfileId (the
/// config never holds a password). Stopping: <see cref="TrySignalStop"/>, then a kill after
/// <see cref="StopGrace"/> if it is still running.
/// </summary>
internal static class HeadlessLaunch
{
/// <summary>Process name (Process.GetProcessesByName) of the headless client.</summary>
public const string ProcessName = "rynth-headless";
public const string ExeName = ProcessName + ".exe";
/// <summary>Default install folder of rynth-headless.exe, beside the launcher.</summary>
public const string DefaultFolderName = "Headless";
/// <summary>Folder under the launcher's settings folder holding the run configs.</summary>
public const string ConfigFolderName = "headless";
/// <summary>
/// Folder under the Headless folder with the 64-bit plugin builds the installer ships, one folder
/// per plugin with its dependencies: Headless\plugins\&lt;Name&gt;\RynthCore.Plugin.&lt;Name&gt;.dll.
/// </summary>
public const string PluginsFolderName = "plugins";
/// <summary>How long a stop request may take (every character logs out) before the launcher kills the process.</summary>
public static readonly TimeSpan StopGrace = TimeSpan.FromSeconds(20);
/// <summary>
/// Name of the stop event of rynth-headless process <paramref name="pid"/> (a manual-reset
/// EventWaitHandle the process creates). Set = every character logs out cleanly, then it exits.
/// </summary>
public static string StopEventName(int pid) => $@"Local\RynthHeadless.Stop.{pid}";
/// <summary>
/// Asks rynth-headless process <paramref name="pid"/> to log out and exit. False when it has no
/// stop event (not a rynth-headless, too old, still starting, or gone): the caller kills it then.
/// </summary>
public static bool TrySignalStop(int pid)
{
if (!OperatingSystem.IsWindows())
return false;
try
{
if (!EventWaitHandle.TryOpenExisting(StopEventName(pid), out EventWaitHandle? stop))
return false;
using (stop)
return stop.Set();
}
catch
{
return false;
}
}
/// <summary>
/// rynth-headless.exe: <paramref name="configured"/> (AppSettings.HeadlessExePath, environment
/// variables expanded) when set, else &lt;<paramref name="launcherDirectory"/>&gt;\Headless\rynth-headless.exe.
/// </summary>
public static string ResolveExePath(string? configured, string launcherDirectory)
{
string path = (configured ?? string.Empty).Trim().Trim('"');
if (path.Length > 0)
return Environment.ExpandEnvironmentVariables(path);
return Path.Combine(launcherDirectory, DefaultFolderName, ExeName);
}
/// <summary>
/// The shipped 64-bit plugins: every &lt;<paramref name="launcherDirectory"/>&gt;\Headless\plugins\&lt;Name&gt;\RynthCore.Plugin.&lt;Name&gt;.dll
/// that exists, by name. Empty when the install has none (an older install, a dev launcher).
/// </summary>
public static List<string> DefaultPluginPaths(string launcherDirectory)
{
var found = new List<string>();
try
{
string root = Path.Combine(launcherDirectory, DefaultFolderName, PluginsFolderName);
if (!Directory.Exists(root))
return found;
foreach (string dir in Directory.GetDirectories(root))
{
string dll = Path.Combine(dir, $"RynthCore.Plugin.{Path.GetFileName(dir)}.dll");
if (File.Exists(dll))
found.Add(dll);
}
}
catch
{
// Unreadable folder: no default plugins.
}
found.Sort(StringComparer.OrdinalIgnoreCase);
return found;
}
/// <summary>
/// The plugins a Headless account loads: <paramref name="configured"/> (AppSettings.HeadlessPluginPaths,
/// blank entries dropped) when it names any, else the shipped ones (<see cref="DefaultPluginPaths"/>).
/// </summary>
public static List<string> ResolvePluginPaths(IEnumerable<string>? configured, string launcherDirectory)
{
var list = new List<string>();
foreach (string entry in configured ?? Array.Empty<string>())
{
string path = (entry ?? string.Empty).Trim().Trim('"').Trim();
if (path.Length > 0)
list.Add(path);
}
return list.Count > 0 ? list : DefaultPluginPaths(launcherDirectory);
}
/// <summary>The run config for account profile <paramref name="profileId"/>, under <paramref name="settingsDirectory"/>\headless.</summary>
public static string ConfigPath(string settingsDirectory, string profileId)
{
var name = new StringBuilder(profileId.Length);
foreach (char c in profileId)
name.Append(Array.IndexOf(Path.GetInvalidFileNameChars(), c) >= 0 ? '_' : c);
if (name.Length == 0)
name.Append("account");
return Path.Combine(settingsDirectory, ConfigFolderName, $"launch_{name}.json");
}
/// <summary>
/// The --ac-folder value: the folder of the AC client path, or null when none is set (the
/// argument is left out then).
/// </summary>
public static string? AcFolderFor(string? acClientPath)
{
string path = (acClientPath ?? string.Empty).Trim().Trim('"');
if (path.Length == 0)
return null;
string? dir = Path.GetDirectoryName(path);
return string.IsNullOrWhiteSpace(dir) ? null : dir;
}
/// <summary>
/// The run config as rynth-headless reads it (camelCase JSON). There is no password field:
/// with --launcher the process reads it from appsettings.json by launcherProfileId.
/// </summary>
public static string BuildConfigJson(HeadlessRunSpec spec)
{
ArgumentNullException.ThrowIfNull(spec);
using var stream = new MemoryStream();
using (var w = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteString("host", spec.Host ?? string.Empty);
w.WriteNumber("port", spec.Port);
w.WriteString("serverName", spec.ServerName ?? string.Empty);
if (!string.IsNullOrWhiteSpace(spec.SuiteDir))
w.WriteString("suiteDir", spec.SuiteDir.Trim());
if (!string.IsNullOrWhiteSpace(spec.StatusDir))
w.WriteString("statusDir", spec.StatusDir.Trim());
w.WriteStartArray("plugins");
foreach (string plugin in spec.Plugins ?? new List<string>())
if (!string.IsNullOrWhiteSpace(plugin))
w.WriteStringValue(plugin.Trim());
w.WriteEndArray();
w.WriteStartArray("sessions");
foreach (HeadlessSessionSpec s in spec.Sessions ?? new List<HeadlessSessionSpec>())
{
w.WriteStartObject();
w.WriteString("launcherProfileId", s.LauncherProfileId ?? string.Empty);
w.WriteString("account", s.Account ?? string.Empty);
if (string.IsNullOrWhiteSpace(s.Character))
w.WriteNull("character");
else
w.WriteString("character", s.Character.Trim());
w.WriteStartArray("commands");
foreach (string command in s.Commands ?? new List<string>())
if (!string.IsNullOrWhiteSpace(command))
w.WriteStringValue(command);
w.WriteEndArray();
w.WriteNumber("staySeconds", Math.Max(0, s.StaySeconds));
w.WriteBoolean("reconnect", s.Reconnect);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
/// <summary>Writes <paramref name="configJson"/> to <paramref name="path"/> (UTF-8, no BOM; temp file + swap).</summary>
public static void WriteConfig(string path, string configJson)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = path + ".tmp";
File.WriteAllText(tmp, configJson, new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
}
/// <summary>
/// rynth-headless's arguments, one per entry (for ProcessStartInfo.ArgumentList, which quotes
/// them): run --config FILE --launcher [--ac-folder DIR].
/// </summary>
public static List<string> BuildArguments(string configPath, string? acFolder)
{
var args = new List<string> { "run", "--config", configPath, "--launcher" };
if (!string.IsNullOrWhiteSpace(acFolder))
{
args.Add("--ac-folder");
args.Add(acFolder);
}
return args;
}
}

View file

@ -20,4 +20,11 @@ internal enum InjectionMode
/// registers for this Windows user before the launch (DecalBridgeRegistration;
/// docs/DECAL_BRIDGE_PLAN.md).</summary>
DecalBridge = 2,
/// <summary>No acclient.exe: the launcher starts rynth-headless.exe (our own headless client,
/// src\RynthCore.Headless.Cli) for the account, with the x64 plugins set in
/// AppSettings.HeadlessPluginPaths (HeadlessLaunch). Experimental, ACE servers only.
/// appsettings.json lists such an account as RynthCore; headless-accounts.json says which
/// are really Headless (HeadlessAccountModes).</summary>
Headless = 3,
}

View file

@ -0,0 +1,281 @@
// ============================================================================
// RynthCore.Geometry - Cells/CellDat.cs
// Reads indoor cells from the dats: each EnvCell's frame, its cell portals
// (which cell is on the other side of which doorway polygon) and static
// objects, and the Environment's CellStruct for it (render polygons with the
// doorway polygons, physics polygons with the floors). Polygons come out
// landblock-local.
//
// Formats as in ACE (EnvCell.Unpack, Environment/CellStruct.Unpack,
// Polygon.Unpack, BSP trees); the polygon, vertex and BSP readers were ported
// from RynthAi's Raycasting/DungeonLOS.cs, which reads the same structures
// for the dungeon map and missile LOS.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/CellDat.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Cells;
/// <summary>EnvCell / Environment readers. Stateless; see <see cref="IndoorWorld"/> for a cached, thread-safe front end.</summary>
public static class CellDat
{
/// <summary>A walkable floor: ACE's PhysicsGlobals.FloorZ (cos 48.4 degrees).</summary>
public const float FloorZ = 0.66417414f;
/// <summary>
/// Every EnvCell of landblock <paramref name="landblock"/> (0xXXYY, or any cell id 0xXXYYnnnn of it),
/// ascending by id, with geometry attached. A cell whose record does not parse is skipped; one whose
/// Environment/CellStruct does not parse is kept with <see cref="EnvCell.GeometryOk"/> false.
/// </summary>
public static List<EnvCell> LoadLandblock(DatDatabase cellDat, DatDatabase portalDat, uint landblock)
{
if (landblock > 0xFFFF) landblock >>= 16;
var envCache = new Dictionary<uint, Dictionary<uint, RawCellStruct>>();
var cells = new List<EnvCell>();
foreach (uint id in cellDat.GetLandblockCellIds(landblock))
{
byte[]? data = cellDat.GetFileData(id);
if (data == null) continue;
EnvCell? c = ParseEnvCell(data);
if (c == null) continue;
c.Id = id;
if (!envCache.TryGetValue(c.EnvironmentId, out var structs))
{
byte[]? env = portalDat.GetFileData(c.EnvironmentId);
structs = env == null ? new() : ParseEnvironmentSafe(env);
envCache[c.EnvironmentId] = structs;
}
if (structs.TryGetValue(c.CellStructure, out RawCellStruct? cs))
Attach(c, cs);
c.ComputeBounds();
cells.Add(c);
}
return cells;
}
/// <summary>A point in the cell's own frame to landblock-local.</summary>
public static Vector3 ToLandblock(EnvCell c, Vector3 local) => Vector3.Transform(local, c.Rotation) + c.Origin;
private static void Attach(EnvCell c, RawCellStruct cs)
{
c.GeometryOk = cs.PhysicsOk;
foreach (var poly in cs.Physics)
{
var w = poly.Select(v => ToLandblock(c, v)).ToArray();
Vector3 n = Normal(w);
if (n.Z >= FloorZ) c.Floors.Add(w); else c.Walls.Add(w);
}
foreach (var p in c.Portals)
if (cs.Render.TryGetValue(p.PolygonId, out var poly))
p.Polygon = poly.Select(v => ToLandblock(c, v)).ToArray();
}
/// <summary>Unit normal by the vertex order (ACE Polygon.make_plane: sum of fan cross products).</summary>
public static Vector3 Normal(IReadOnlyList<Vector3> v)
{
Vector3 n = Vector3.Zero;
for (int i = 1; i < v.Count - 1; i++)
n += Vector3.Cross(v[i] - v[0], v[i + 1] - v[0]);
float len = n.Length();
return len < 1e-6f ? Vector3.Zero : n / len;
}
// -- EnvCell ---------------------------------------------------------------
private static EnvCell? ParseEnvCell(byte[] data)
{
try
{
using var r = new BinaryReader(new MemoryStream(data));
var c = new EnvCell();
r.ReadUInt32(); // id
c.Flags = r.ReadUInt32();
r.ReadUInt32(); // id again
byte numSurfaces = r.ReadByte();
byte numPortals = r.ReadByte();
ushort numVisible = r.ReadUInt16();
for (int i = 0; i < numSurfaces; i++) r.ReadUInt16();
c.EnvironmentId = 0x0D000000u | r.ReadUInt16();
c.CellStructure = r.ReadUInt16();
c.Origin = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
c.Rotation = new Quaternion(x, y, z, w);
for (int i = 0; i < numPortals; i++)
c.Portals.Add(new CellPortal { Flags = r.ReadUInt16(), PolygonId = r.ReadUInt16(), OtherCell = r.ReadUInt16(), OtherPortal = r.ReadUInt16() });
for (int i = 0; i < numVisible; i++) c.VisibleCells.Add(r.ReadUInt16());
if ((c.Flags & 0x2) != 0)
{
uint n = r.ReadUInt32();
for (uint i = 0; i < n && i < 4096; i++)
{
// A stab's frame is landblock-local, like the cell's own (not relative to the cell).
var s = new Stab { Id = r.ReadUInt32(), Origin = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()) };
float sw = r.ReadSingle(), sx = r.ReadSingle(), sy = r.ReadSingle(), sz = r.ReadSingle();
s.Rotation = new Quaternion(sx, sy, sz, sw);
c.Stabs.Add(s);
}
}
return c;
}
catch (EndOfStreamException) { return null; }
}
// -- Environment / CellStruct ----------------------------------------------
private sealed class RawCellStruct
{
public Dictionary<ushort, Vector3[]> Render = new();
public List<Vector3[]> Physics = new();
public bool PhysicsOk;
}
// A damaged Environment must not take the landblock down: keep what parsed before the damage.
private static Dictionary<uint, RawCellStruct> ParseEnvironmentSafe(byte[] data)
{
var result = new Dictionary<uint, RawCellStruct>();
try { ParseEnvironment(data, result); }
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException) { }
return result;
}
private static void ParseEnvironment(byte[] data, Dictionary<uint, RawCellStruct> result)
{
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); // id
uint n = r.ReadUInt32();
for (uint i = 0; i < n && i < 512; i++)
{
uint key = r.ReadUInt32();
var cs = ParseCellStruct(r, ms, out bool toEnd);
if (cs == null) break;
result[key] = cs;
if (!toEnd) break; // stream position unknown after this one
}
}
private static RawCellStruct? ParseCellStruct(BinaryReader r, MemoryStream ms, out bool toEnd)
{
toEnd = false;
uint numPolys = r.ReadUInt32(), numPhys = r.ReadUInt32(), numPortals = r.ReadUInt32();
if (numPolys > 5000 || numPhys > 5000) return null;
var verts = ReadVertexArray(r, ms);
if (verts == null) return null;
var cs = new RawCellStruct();
foreach (var (key, ids) in ReadPolygons(r, ms, numPolys))
cs.Render[key] = Resolve(ids, verts);
for (uint i = 0; i < numPortals; i++) r.ReadUInt16();
Align(ms);
if (!SkipBsp(r, ms, Bsp.Cell)) return cs;
foreach (var (_, ids) in ReadPolygons(r, ms, numPhys))
{
var p = Resolve(ids, verts);
if (p.Length >= 3) cs.Physics.Add(p);
}
cs.PhysicsOk = cs.Physics.Count > 0;
if (!SkipBsp(r, ms, Bsp.Physics)) return cs;
if (ms.Position + 4 <= ms.Length && r.ReadUInt32() != 0 && !SkipBsp(r, ms, Bsp.Drawing)) return cs;
Align(ms);
toEnd = true;
return cs;
}
internal static Vector3[] Resolve(List<ushort> ids, Dictionary<ushort, Vector3> verts)
{
var list = new List<Vector3>(ids.Count);
foreach (var id in ids) if (verts.TryGetValue(id, out var v)) list.Add(v);
return list.ToArray();
}
private static void Align(MemoryStream ms)
{
long a = (ms.Position + 3) & ~3L;
if (a <= ms.Length) ms.Position = a;
}
internal static Dictionary<ushort, Vector3>? ReadVertexArray(BinaryReader r, MemoryStream ms)
{
if (r.ReadInt32() != 1) return null;
uint n = r.ReadUInt32();
if (n > 50000) return null;
var verts = new Dictionary<ushort, Vector3>();
for (uint i = 0; i < n; i++)
{
ushort key = r.ReadUInt16();
ushort numUv = r.ReadUInt16();
var v = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
ms.Seek(12 + numUv * 8L, SeekOrigin.Current); // normal + UVs
verts[key] = v;
}
return verts;
}
internal static List<(ushort, List<ushort>)> ReadPolygons(BinaryReader r, MemoryStream ms, uint count)
{
var polys = new List<(ushort, List<ushort>)>();
for (uint i = 0; i < count; i++)
{
ushort key = r.ReadUInt16();
byte numPts = r.ReadByte();
byte stippling = r.ReadByte();
int sides = r.ReadInt32();
r.ReadInt16(); r.ReadInt16(); // surfaces
if (numPts == 0 || numPts > 50) throw new InvalidDataException("bad polygon");
var ids = new List<ushort>(numPts);
for (int v = 0; v < numPts; v++) ids.Add((ushort)r.ReadInt16());
if ((stippling & 0x04) == 0) ms.Seek(numPts, SeekOrigin.Current);
if (sides == 2 && (stippling & 0x08) == 0) ms.Seek(numPts, SeekOrigin.Current);
polys.Add((key, ids));
}
return polys;
}
private enum Bsp { Cell, Physics, Drawing }
private const uint PORT = 0x504F5254, LEAF = 0x4C454146, BPnn = 0x42506E6E, BPIn = 0x4250496E, BpIN = 0x4270494E,
BpnN = 0x42706E4E, BPIN = 0x4250494E, BPnN = 0x42506E4E, BPFL = 0x4250464C, BPOL = 0x42504F4C, BpIn = 0x4270496E;
private static bool SkipBsp(BinaryReader r, MemoryStream ms, Bsp t)
{
if (ms.Position + 4 > ms.Length) return false;
uint tag = r.ReadUInt32();
if (tag == LEAF || tag == PORT)
{
r.ReadInt32(); // leaf index
if (t == Bsp.Physics)
{
r.ReadInt32(); // solid
ms.Seek(16, SeekOrigin.Current); // sphere
uint np = r.ReadUInt32();
if (np > 100000) return false;
ms.Seek(np * 2L, SeekOrigin.Current);
}
return ms.Position <= ms.Length;
}
ms.Seek(16, SeekOrigin.Current); // splitting plane
switch (tag)
{
case BPnn: case BPIn: case BpIN: case BpnN:
if (!SkipBsp(r, ms, t)) return false;
break;
case BPIN: case BPnN:
if (!SkipBsp(r, ms, t) || !SkipBsp(r, ms, t)) return false;
break;
case BPFL: case BPOL: case BpIn:
break;
default:
return false;
}
if (t == Bsp.Cell) return true;
ms.Seek(16, SeekOrigin.Current); // sphere
if (t == Bsp.Physics) return true;
uint n = r.ReadUInt32();
if (n > 100000) return false;
ms.Seek(n * 2L, SeekOrigin.Current);
return ms.Position <= ms.Length;
}
}

View file

@ -0,0 +1,123 @@
// ============================================================================
// RynthCore.Geometry - Cells/EnvCell.cs
// The indoor cell model: an EnvCell (dungeon / building interior cell) with
// its frame, cell portals (doorway polygons and the cell beyond), static
// objects, and its physics polygons split into floors and walls, all in
// landblock-local coordinates. Filled by CellDat.LoadLandblock.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/CellDat.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
namespace RynthCore.Geometry.Cells;
/// <summary>A doorway of an EnvCell: the polygon you walk through and the cell on its other side.</summary>
public sealed class CellPortal
{
/// <summary>Raw portal flags (0x2 = PortalSide).</summary>
public ushort Flags;
/// <summary>Key into the CellStruct's render polygons.</summary>
public ushort PolygonId;
/// <summary>Low 16 bits of the cell on the other side; <see cref="Outdoors"/> (0xFFFF) = leads outdoors.</summary>
public ushort OtherCell;
public ushort OtherPortal;
/// <summary>The doorway polygon, landblock-local (empty when the CellStruct did not have it).</summary>
public Vector3[] Polygon = Array.Empty<Vector3>();
/// <summary><see cref="OtherCell"/> value of a portal that leads outdoors.</summary>
public const ushort Outdoors = 0xFFFF;
public bool LeadsOutdoors => OtherCell == Outdoors;
/// <summary>
/// ACE's CellPortal.PortalSide (flag 0x2 clear): the cell behind the portal is on the front of
/// <see cref="Polygon"/> (the side its vertex-order normal, <see cref="CellDat.Normal"/>, points to) and
/// this cell on its back; when false, the other way round. Checked against the cells' floor plans for
/// every doorway of dungeon 0x6146 (GeometryTests "cells").
/// </summary>
public bool PortalSide => (Flags & 0x2) == 0;
}
/// <summary>A static object placed in a cell: a GfxObj (0x01..) or a Setup (0x02..).</summary>
public sealed class Stab
{
public uint Id;
/// <summary>Landblock-local (like the cell's own frame, not relative to the cell).</summary>
public Vector3 Origin;
public Quaternion Rotation;
}
/// <summary>
/// One indoor cell (0xLLLL0100..0xLLLLFFFD). Every position and polygon is landblock-local
/// (the same frame as ACE positions: x, y in 0..192 for the landblock, z absolute).
/// </summary>
public sealed class EnvCell
{
/// <summary>Full cell id 0xLLLLCCCC.</summary>
public uint Id;
public uint Flags;
public uint EnvironmentId;
public ushort CellStructure;
/// <summary>The cell frame, landblock-local; the CellStruct's vertices are rotated by
/// <see cref="Rotation"/> then offset by <see cref="Origin"/>.</summary>
public Vector3 Origin;
public Quaternion Rotation;
public List<CellPortal> Portals = new();
public List<ushort> VisibleCells = new();
public List<Stab> Stabs = new();
/// <summary>Physics polygons facing up (normal.Z &gt;= <see cref="CellDat.FloorZ"/>), landblock-local.</summary>
public List<Vector3[]> Floors = new();
/// <summary>Every other physics polygon (walls, ceilings, steep slopes), landblock-local.</summary>
public List<Vector3[]> Walls = new();
/// <summary>The Environment's CellStruct for this cell was found and has physics polygons.</summary>
public bool GeometryOk;
/// <summary>XY bounds of <see cref="Floors"/> (empty bounds when there are no floors).</summary>
public float MinX = float.MaxValue, MinY = float.MaxValue, MaxX = float.MinValue, MaxY = float.MinValue;
/// <summary>The low word: the cell number inside its landblock.</summary>
public ushort Short => (ushort)(Id & 0xFFFF);
/// <summary>The landblock key 0xXXYY.</summary>
public uint Landblock => Id >> 16;
/// <summary>The full id of the cell behind <paramref name="p"/> (meaningless when it leads outdoors).</summary>
public uint Neighbour(CellPortal p) => (Id & 0xFFFF0000u) | p.OtherCell;
/// <summary>Is a cell low word an indoor (EnvCell) number?</summary>
public static bool IsIndoor(uint cellId)
{
uint low = cellId & 0xFFFF;
return low >= 0x0100 && low <= 0xFFFD;
}
internal bool BoundsContain(float x, float y, float margin) =>
x >= MinX - margin && x <= MaxX + margin && y >= MinY - margin && y <= MaxY + margin;
/// <summary>
/// Is (x, y) inside the cell's plan seen from above: over one of its floors, or under one of its other
/// physics polygons that has area from above (ceilings, steep slopes), within <paramref name="eps"/>?
/// </summary>
public bool CoversXY(float x, float y, float eps = 0.05f)
{
foreach (var f in Floors)
if (Geo.InsideXY(f, x, y, eps)) return true;
foreach (var w in Walls)
if (Geo.AreaXY(w) > 0.01f && Geo.InsideXY(w, x, y, eps)) return true;
return false;
}
internal void ComputeBounds()
{
MinX = MinY = float.MaxValue; MaxX = MaxY = float.MinValue;
foreach (var f in Floors)
foreach (var v in f)
{
MinX = MathF.Min(MinX, v.X); MaxX = MathF.Max(MaxX, v.X);
MinY = MathF.Min(MinY, v.Y); MaxY = MathF.Max(MaxY, v.Y);
}
}
public override string ToString() => $"EnvCell {Id:X8} ({Floors.Count} floors, {Walls.Count} walls, {Portals.Count} portals)";
}

View file

@ -0,0 +1,216 @@
// ============================================================================
// RynthCore.Geometry - Cells/Geo.cs
// Small geometry helpers for the indoor queries: 2D tests on the floor plan
// (point in polygon seen from above, distances, plane height) and the 3D
// segment-through-polygon test used to cross cell portals.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/Geometry.cs (3a8075a);
// SegmentCrossesToward, DistToPolygon and SphereRestZ are new (2026-10-28).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
namespace RynthCore.Geometry.Cells;
/// <summary>Small geometry helpers: 2D tests on the floor plan, 3D segment-through-polygon.</summary>
public static class Geo
{
/// <summary>Is (x, y) inside the polygon's outline seen from above (edges count as inside within eps)?</summary>
public static bool InsideXY(IReadOnlyList<Vector3> poly, float x, float y, float eps = 0.01f)
{
bool inside = false;
int n = poly.Count;
for (int i = 0, j = n - 1; i < n; j = i++)
{
Vector3 a = poly[i], b = poly[j];
if ((a.Y > y) != (b.Y > y))
{
float xc = (b.X - a.X) * (y - a.Y) / (b.Y - a.Y) + a.X;
if (x < xc) inside = !inside;
}
}
if (inside || eps <= 0) return inside;
return DistToOutlineXY(poly, x, y) <= eps;
}
/// <summary>Distance from (x, y) to the polygon's outline seen from above (0 inside when filled).</summary>
public static float DistXY(IReadOnlyList<Vector3> poly, float x, float y, bool filled)
{
if (filled && poly.Count >= 3 && AreaXY(poly) > 1e-4f && InsideXY(poly, x, y, 0)) return 0;
return DistToOutlineXY(poly, x, y);
}
public static float DistToOutlineXY(IReadOnlyList<Vector3> poly, float x, float y)
{
float best = float.MaxValue;
int n = poly.Count;
for (int i = 0, j = n - 1; i < n; j = i++)
best = MathF.Min(best, DistToSegXY(poly[j].X, poly[j].Y, poly[i].X, poly[i].Y, x, y));
return best;
}
public static float DistToSegXY(float ax, float ay, float bx, float by, float px, float py)
{
float dx = bx - ax, dy = by - ay;
float len2 = dx * dx + dy * dy;
float t = len2 < 1e-12f ? 0 : Math.Clamp(((px - ax) * dx + (py - ay) * dy) / len2, 0, 1);
float ex = ax + t * dx - px, ey = ay + t * dy - py;
return MathF.Sqrt(ex * ex + ey * ey);
}
public static float AreaXY(IReadOnlyList<Vector3> poly)
{
float a = 0;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
a += poly[j].X * poly[i].Y - poly[i].X * poly[j].Y;
return MathF.Abs(a) * 0.5f;
}
/// <summary>Height of a (non-vertical) planar polygon's plane at (x, y).</summary>
public static float PlaneZ(IReadOnlyList<Vector3> poly, float x, float y)
{
Vector3 n = CellDat.Normal(poly);
if (MathF.Abs(n.Z) < 1e-4f) return poly[0].Z;
Vector3 p = poly[0];
return p.Z - (n.X * (x - p.X) + n.Y * (y - p.Y)) / n.Z;
}
/// <summary>Does the segment a-b pass through the planar polygon (edges included within eps)?</summary>
public static bool SegmentCrosses(IReadOnlyList<Vector3> poly, Vector3 a, Vector3 b, float eps = 0.02f)
{
if (poly.Count < 3) return false;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero) return false;
float da = Vector3.Dot(n, a - poly[0]), db = Vector3.Dot(n, b - poly[0]);
if ((da > 0 && db > 0) || (da < 0 && db < 0)) return false;
float denom = da - db;
if (MathF.Abs(denom) < 1e-7f) return false; // in the plane: not a crossing
return HitsInside(poly, n, a + (b - a) * (da / denom), eps);
}
/// <summary>
/// Does the segment a-b go through the planar polygon in one direction: from its back to its front
/// (<paramref name="towardFront"/>; the front is the side the vertex-order normal points to, see
/// <see cref="CellDat.Normal"/>) or front to back? A point within <paramref name="planeTol"/> of the
/// plane still counts as on the side it is coming from, so stepping a path sample by sample, each
/// crossing is seen once, by the step that ends clearly beyond the plane.
/// </summary>
public static bool SegmentCrossesToward(IReadOnlyList<Vector3> poly, Vector3 a, Vector3 b, bool towardFront,
float eps = 0.02f, float planeTol = 0.0005f)
{
if (poly.Count < 3) return false;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero) return false;
float s = towardFront ? 1f : -1f;
float da = s * Vector3.Dot(n, a - poly[0]), db = s * Vector3.Dot(n, b - poly[0]);
if (da > planeTol || db <= planeTol) return false;
float t = da >= 0 ? 0 : da / (da - db); // where it meets the plane
return HitsInside(poly, n, a + (b - a) * t, eps);
}
/// <summary>
/// Is <paramref name="p"/> clearly on one side of the planar polygon (its front when
/// <paramref name="front"/>, else its back), at most <paramref name="maxDist"/> from the plane, and does it
/// drop onto the polygon itself (not beside it) along the normal?
/// </summary>
public static bool BeyondThrough(IReadOnlyList<Vector3> poly, Vector3 p, bool front, float maxDist,
float eps = 0.02f, float planeTol = 0.0005f)
{
if (poly.Count < 3) return false;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero) return false;
float d = Vector3.Dot(n, p - poly[0]);
float side = front ? d : -d;
if (side <= planeTol || side > maxDist) return false;
return HitsInside(poly, n, p - n * d, eps);
}
// Is p (on the polygon's plane) inside it? Tested in the plane, dropping the normal's dominant axis.
private static bool HitsInside(IReadOnlyList<Vector3> poly, Vector3 n, Vector3 p, float eps)
{
int drop = DominantAxis(n);
var flat = new Vector3[poly.Count];
for (int i = 0; i < flat.Length; i++) flat[i] = Flatten(poly[i], drop);
Vector3 fp = Flatten(p, drop);
return InsideXY(flat, fp.X, fp.Y, eps);
}
/// <summary>3D distance from <paramref name="p"/> to the planar polygon (its surface, edges and corners).</summary>
public static float DistToPolygon(IReadOnlyList<Vector3> poly, Vector3 p)
{
Vector3 n = CellDat.Normal(poly);
if (n != Vector3.Zero)
{
float d = Vector3.Dot(n, p - poly[0]);
Vector3 q = p - n * d;
int drop = DominantAxis(n);
var flat = new Vector3[poly.Count];
for (int i = 0; i < flat.Length; i++) flat[i] = Flatten(poly[i], drop);
Vector3 fq = Flatten(q, drop);
if (InsideXY(flat, fq.X, fq.Y, 0)) return MathF.Abs(d);
}
float best = float.MaxValue;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
best = MathF.Min(best, DistToSegment(poly[j], poly[i], p));
return best;
}
public static float DistToSegment(Vector3 a, Vector3 b, Vector3 p)
{
Vector3 ab = b - a;
float len2 = ab.LengthSquared();
float t = len2 < 1e-12f ? 0 : Math.Clamp(Vector3.Dot(p - a, ab) / len2, 0, 1);
return Vector3.Distance(a + ab * t, p);
}
/// <summary>
/// Where a sphere of radius <paramref name="radius"/> above (x, y) comes to rest on the polygon when
/// lowered onto it: the height of the sphere's bottom (centre - radius), or null when the polygon is not
/// under the sphere. On a flat floor that is the floor height; on a slope with normal n it is
/// radius * (1 / n.Z - 1) above the plane (the sphere touches uphill of its centre); near an edge or a
/// corner the sphere rests on that.
/// </summary>
public static float? SphereRestZ(IReadOnlyList<Vector3> poly, float x, float y, float radius)
{
if (poly.Count < 3) return null;
// A height at which the sphere's centre is within radius of the polygon: the polygon's own height
// at the point of it nearest (x, y) seen from above.
float lo;
if (InsideXY(poly, x, y, 0)) lo = PlaneZ(poly, x, y);
else
{
float best = float.MaxValue; lo = 0;
for (int i = 0, j = poly.Count - 1; i < poly.Count; j = i++)
{
Vector3 a = poly[j], b = poly[i];
float dx = b.X - a.X, dy = b.Y - a.Y, len2 = dx * dx + dy * dy;
float t = len2 < 1e-12f ? 0 : Math.Clamp(((x - a.X) * dx + (y - a.Y) * dy) / len2, 0, 1);
float ex = a.X + t * dx - x, ey = a.Y + t * dy - y, d = MathF.Sqrt(ex * ex + ey * ey);
if (d < best) { best = d; lo = a.Z + t * (b.Z - a.Z); }
}
if (best > radius) return null;
}
// Distance from the centre to the polygon is convex in the centre's height, so the heights within
// radius form an interval holding lo; its top is where the sphere rests.
float hi = float.MinValue;
foreach (var v in poly) hi = MathF.Max(hi, v.Z);
hi += radius + 0.01f;
for (int it = 0; it < 40 && hi - lo > 1e-4f; it++)
{
float mid = 0.5f * (lo + hi);
if (DistToPolygon(poly, new Vector3(x, y, mid)) <= radius) lo = mid; else hi = mid;
}
return lo - radius;
}
private static int DominantAxis(Vector3 n) =>
MathF.Abs(n.X) > MathF.Abs(n.Y) ? (MathF.Abs(n.X) > MathF.Abs(n.Z) ? 0 : 2) : (MathF.Abs(n.Y) > MathF.Abs(n.Z) ? 1 : 2);
private static Vector3 Flatten(Vector3 v, int drop) => drop switch
{
0 => new Vector3(v.Y, v.Z, 0),
1 => new Vector3(v.X, v.Z, 0),
_ => new Vector3(v.X, v.Y, 0),
};
}

View file

@ -0,0 +1,217 @@
// ============================================================================
// RynthCore.Geometry - Cells/Indoor.cs
// An indoor world for walk planning: a set of EnvCells plus solid footprints
// (walls, static objects, NPCs) and portal objects to keep clear of. Queries:
// floor height in a cell, doorways between cells, a floor-following trace of
// a straight segment through cell portals, and clearance from solids.
// For the cached per-landblock queries (FindCell, TrackCell) see IndoorWorld.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/Indoor.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
namespace RynthCore.Geometry.Cells;
/// <summary>Something solid seen from above: a polygon outline (or a disc), between two heights.</summary>
public sealed class Footprint
{
public Vector3[] Poly = Array.Empty<Vector3>();
/// <summary>The outline has area: inside counts as touching.</summary>
public bool Filled;
/// <summary>A disc when <see cref="Poly"/> is empty.</summary>
public Vector2 Center; public float Radius;
public float ZMin, ZMax;
public string Source = "";
public float MinX, MinY, MaxX, MaxY;
public float Dist(float x, float y) =>
Poly.Length == 0 ? MathF.Max(0, Vector2.Distance(Center, new Vector2(x, y)) - Radius) : Geo.DistXY(Poly, x, y, Filled);
/// <summary>Does it stand in the way of someone whose feet are at z (step over below +0.45, head at +1.8)?</summary>
public bool Blocks(float z) => ZMax > z + Indoor.StepUp && ZMin < z + Indoor.BodyHeight;
public void Bounds()
{
if (Poly.Length == 0) { MinX = Center.X - Radius; MaxX = Center.X + Radius; MinY = Center.Y - Radius; MaxY = Center.Y + Radius; return; }
MinX = Poly.Min(v => v.X); MaxX = Poly.Max(v => v.X); MinY = Poly.Min(v => v.Y); MaxY = Poly.Max(v => v.Y);
}
public static Footprint FromPolygon(Vector3[] p, string source)
{
var f = new Footprint { Poly = p, Filled = Geo.AreaXY(p) > 0.01f, ZMin = p.Min(v => v.Z), ZMax = p.Max(v => v.Z), Source = source };
f.Bounds();
return f;
}
public static Footprint Disc(float x, float y, float r, float zmin, float zmax, string source)
{
var f = new Footprint { Center = new Vector2(x, y), Radius = r, ZMin = zmin, ZMax = zmax, Source = source };
f.Bounds();
return f;
}
}
/// <summary>A portal object inside the network: walking into it uses it, so the walks keep clear of all but their own.</summary>
public sealed class PortalZone
{
public string Guid = "";
public string Name = "";
public uint Cell;
public Vector3 Pos;
/// <summary>Its collision radius.</summary>
public float Radius;
}
/// <summary>The indoor world walks are planned in: cells, solid things, portal objects.</summary>
public sealed class Indoor
{
public const float StepUp = 0.45f;
public const float BodyHeight = 1.8f;
/// <summary>Largest height change between neighbouring floor samples.</summary>
public const float StepZ = 0.45f;
public readonly Dictionary<uint, EnvCell> Cells = new();
public readonly List<Footprint> Solids = new();
public readonly List<PortalZone> Portals = new();
public float AgentRadius = 0.5f;
public readonly List<string> Notes = new();
public EnvCell Cell(uint id) => Cells[id];
/// <summary>
/// The floor height of a cell at (x, y), or null when (x, y) is not on its floor. With several floors
/// there, the one nearest <paramref name="near"/>; without <paramref name="near"/>, the first found.
/// </summary>
public static float? FloorZ(EnvCell c, float x, float y, float? near = null, float eps = 0.01f)
{
float? best = null;
foreach (var f in c.Floors)
{
if (!Geo.InsideXY(f, x, y, eps)) continue;
float z = Geo.PlaneZ(f, x, y);
if (best == null || (near != null && MathF.Abs(z - near.Value) < MathF.Abs(best.Value - near.Value))) best = z;
}
return best;
}
/// <summary>The portal polygons of cell a that open into cell b.</summary>
public static IEnumerable<Vector3[]> Doorways(EnvCell a, uint b)
{
ushort bs = (ushort)(b & 0xFFFF);
foreach (var p in a.Portals)
if (p.OtherCell == bs && p.Polygon.Length >= 3) yield return p.Polygon;
}
public static uint Full(EnvCell from, ushort other) => (from.Id & 0xFFFF0000u) | other;
/// <summary>
/// Follows the straight segment a-b along the floor from cell <paramref name="start"/>, sampling every
/// <paramref name="step"/>: every sample must be on the floor of the cell it is in, and the walk may only
/// change cell where the segment passes through a doorway (cell portal) between the two. Returns the cells
/// visited, or null with a reason when the segment leaves the floor or goes through a wall.
/// </summary>
public List<uint>? Trace(Vector3 a, Vector3 b, uint start, out string why, float step = 0.05f) =>
Trace(Cells, a, b, start, out why, step);
/// <summary><see cref="Trace(Vector3, Vector3, uint, out string, float)"/> over any cell set.</summary>
public static List<uint>? Trace(IReadOnlyDictionary<uint, EnvCell> cellsById, Vector3 a, Vector3 b, uint start, out string why, float step = 0.05f)
{
why = "";
var cells = new List<uint> { start };
if (!cellsById.TryGetValue(start, out EnvCell? cur)) { why = $"cell {start:X8} is not loaded"; return null; }
float len = Vector2.Distance(new Vector2(a.X, a.Y), new Vector2(b.X, b.Y));
int n = Math.Max(1, (int)MathF.Ceiling(len / step));
Vector3 prev = a;
float prevZ = FloorZ(cur, a.X, a.Y, a.Z, 0.02f) ?? float.NaN;
if (float.IsNaN(prevZ)) { why = $"start ({a.X:F2},{a.Y:F2}) is not on the floor of {start:X8}"; return null; }
for (int i = 1; i <= n; i++)
{
Vector3 p = Vector3.Lerp(a, b, i / (float)n);
// A doorway crossed between the last sample and this one moves us into the next cell.
EnvCell? next = null;
float lift = 0.6f;
var pa = new Vector3(prev.X, prev.Y, prevZ + lift);
foreach (var cp in cur.Portals)
{
if (cp.OtherCell == 0xFFFF || cp.Polygon.Length < 3) continue;
uint oid = Full(cur, cp.OtherCell);
if (!cellsById.TryGetValue(oid, out var other)) continue;
float? oz = FloorZ(other, p.X, p.Y, prevZ, 0.02f);
if (oz == null || MathF.Abs(oz.Value - prevZ) > StepZ) continue;
if (Geo.SegmentCrosses(cp.Polygon, pa, new Vector3(p.X, p.Y, oz.Value + lift))) { next = other; break; }
}
if (next != null)
{
cur = next;
cells.Add(cur.Id);
prevZ = FloorZ(cur, p.X, p.Y, prevZ, 0.02f)!.Value;
}
else
{
float? z = FloorZ(cur, p.X, p.Y, prevZ, 0.02f);
if (z == null) { why = $"({p.X:F2},{p.Y:F2}) is off the floor of {cur.Id:X8}"; return null; }
if (MathF.Abs(z.Value - prevZ) > StepZ) { why = $"({p.X:F2},{p.Y:F2}) height jump {prevZ:F2} -> {z:F2} in {cur.Id:X8}"; return null; }
prevZ = z.Value;
}
prev = p;
}
return cells;
}
/// <summary>The nearest solid thing (that blocks at the floor height z) to (x, y), within limit.</summary>
public float SolidDist(float x, float y, float z, float limit, out Footprint? which)
{
which = null;
float best = limit;
if (_buckets == null) Index();
int bx0 = (int)MathF.Floor((x - limit) / Bucket), bx1 = (int)MathF.Floor((x + limit) / Bucket);
int by0 = (int)MathF.Floor((y - limit) / Bucket), by1 = (int)MathF.Floor((y + limit) / Bucket);
var seen = new HashSet<Footprint>();
for (int bx = bx0; bx <= bx1; bx++)
for (int by = by0; by <= by1; by++)
{
if (!_buckets!.TryGetValue((bx, by), out var list)) continue;
foreach (var f in list)
{
if (!seen.Add(f)) continue;
if (x < f.MinX - best || x > f.MaxX + best || y < f.MinY - best || y > f.MaxY + best) continue;
if (!f.Blocks(z)) continue;
float d = f.Dist(x, y);
if (d < best) { best = d; which = f; }
}
}
return best;
}
private const float Bucket = 4f;
private Dictionary<(int, int), List<Footprint>>? _buckets;
/// <summary>A coarse spatial index of the solids (call again after changing <see cref="Solids"/>).</summary>
public void Index()
{
_buckets = new();
foreach (var f in Solids)
for (int bx = (int)MathF.Floor(f.MinX / Bucket); bx <= (int)MathF.Floor(f.MaxX / Bucket); bx++)
for (int by = (int)MathF.Floor(f.MinY / Bucket); by <= (int)MathF.Floor(f.MaxY / Bucket); by++)
{
if (!_buckets.TryGetValue((bx, by), out var l)) _buckets[(bx, by)] = l = new List<Footprint>();
l.Add(f);
}
}
/// <summary>Clearance from portal objects other than <paramref name="except"/>: distance minus the portal's radius.</summary>
public float PortalDist(float x, float y, float z, string? except, out PortalZone? which)
{
which = null;
float best = float.MaxValue;
foreach (var p in Portals)
{
if (p.Guid == except || MathF.Abs(p.Pos.Z - z) > 2.5f) continue;
float d = Vector2.Distance(new Vector2(p.Pos.X, p.Pos.Y), new Vector2(x, y)) - p.Radius;
if (d < best) { best = d; which = p; }
}
return best;
}
}

View file

@ -0,0 +1,303 @@
// ============================================================================
// RynthCore.Geometry - Cells/IndoorWorld.cs
// The indoor cell index: EnvCells loaded per landblock on first use and kept
// (one load per landblock, thread-safe), with the queries a client needs to
// keep its indoor cell id right:
// FindCell - which cell a landblock-local position stands in;
// FloorZ - the floor height of a cell at (x, y);
// TrackCell - the cell after moving a -> b, following cell portals;
// Floors / Walls / ObjectPolygons - the cell's geometry for collision.
//
// Why it matters: ACE trusts the client's cell id for indoor positions and
// never corrects it, so a wrong cell id is not fixed up by the server.
// Indoor cell ids are 0x0100..0xFFFD in the landblock's low word; a cell
// portal whose OtherCell is 0xFFFF leads outdoors.
//
// Written for RynthCore (MIT) on 2026-10-28, on the EnvCell readers and the
// Trace walk moved from RynthSuite Tools/RynthNav.TownNet (3a8075a).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
namespace RynthCore.Geometry.Cells;
/// <summary>
/// Indoor cells by landblock, loaded lazily from the dats and cached. All coordinates are landblock-local
/// (ACE position frame). Safe to share between threads: each landblock is loaded once (other callers for
/// the same landblock wait for that load) and the loaded cells are never changed afterwards.
/// </summary>
public sealed class IndoorWorld
{
/// <summary>FindCell: a floor up to this far above the feet still counts (steps, rounding).</summary>
public const float FindAbove = 0.5f;
/// <summary>FindCell: floors further below the feet than this are ignored.</summary>
public const float FindBelow = 3.0f;
/// <summary>TrackCell: sample spacing along the move.</summary>
public const float TrackStep = 0.05f;
/// <summary>TrackCell: the move is tested this far above the feet, so it passes through doorways, not their sills.</summary>
public const float PortalLift = 0.6f;
private const float FloorEps = 0.02f; // edge tolerance of floor point-in-polygon tests
private const float TieZ = 0.02f; // floors this close in height are the same level
private const float InCellEps = 0.05f; // TrackCell: still in the cell this close to its outline
private const float SlopedDoorwayReach = 2.0f; // TrackCell: how far past a sloping doorway's plane it still counts
private readonly DatDatabase _cellDat;
private readonly DatDatabase _portalDat;
private readonly ConcurrentDictionary<uint, Lazy<Landblock>> _landblocks = new();
/// <summary>Models for the cells' static objects (shared cache).</summary>
public ModelReader Models { get; }
public IndoorWorld(DatDatabase cellDat, DatDatabase portalDat, ModelReader? models = null)
{
_cellDat = cellDat;
_portalDat = portalDat;
Models = models ?? new ModelReader(portalDat);
}
private sealed class Landblock
{
public readonly IReadOnlyList<EnvCell> Cells;
public readonly Dictionary<uint, EnvCell> ById;
public Landblock(List<EnvCell> cells)
{
Cells = cells;
ById = cells.ToDictionary(c => c.Id);
}
}
private static uint Key(uint landblockOrCell) => landblockOrCell > 0xFFFF ? landblockOrCell >> 16 : landblockOrCell;
private Landblock Get(uint landblockOrCell) =>
_landblocks.GetOrAdd(Key(landblockOrCell), lb => new Lazy<Landblock>(
() => new Landblock(CellDat.LoadLandblock(_cellDat, _portalDat, lb)),
LazyThreadSafetyMode.ExecutionAndPublication)).Value;
/// <summary>
/// The EnvCells of a landblock (0xXXYY, or any cell id 0xXXYYnnnn of it), ascending by id; empty for a
/// landblock with no indoor cells. Loaded on first use and cached.
/// </summary>
public IReadOnlyList<EnvCell> LoadLandblock(uint landblock) => Get(landblock).Cells;
/// <summary>Forgets a landblock's cells (they are loaded again on next use).</summary>
public void Unload(uint landblock) => _landblocks.TryRemove(Key(landblock), out _);
/// <summary>The cell with full id <paramref name="cellId"/>, or null when it is not an indoor cell in the dats.</summary>
public EnvCell? GetCell(uint cellId)
{
if (!EnvCell.IsIndoor(cellId)) return null;
return Get(cellId).ById.TryGetValue(cellId, out var c) ? c : null;
}
/// <summary>
/// The indoor cell a landblock-local position (x, y, z = feet) stands in, and its floor height there.
/// <para>
/// Every cell floor polygon whose outline (seen from above) contains (x, y) is a candidate if its height
/// there is at most <see cref="FindAbove"/> above z and at most <see cref="FindBelow"/> below it; the
/// highest candidate wins (the floor nearest at-or-below the feet). Floors at the same height (within
/// 2 cm, e.g. two cells meeting at a doorway) are settled by the point being strictly inside, then by
/// its distance from the polygon's edge.
/// </para>
/// <para>
/// Overhangs: where cells are stacked (a bridge or upper floor above a lower room), a floor more than
/// 0.5 m above the feet is ignored, so someone under a bridge stays in the lower cell, and someone on
/// the bridge gets the bridge cell because it is the highest floor at or below their feet. A floor less
/// than 0.5 m above the feet (a thin overhang right above someone's head is never that low; a step is)
/// would win, and someone falling past several stacked floors gets the highest one at or below them.
/// More than 3 m above any floor (high in the air, or off the floor plan) gives null.
/// </para>
/// </summary>
public (uint cellId, float floorZ)? FindCell(uint landblock, float x, float y, float z)
{
EnvCell? best = null;
float bestZ = 0, bestMargin = 0;
foreach (var c in Get(landblock).Cells)
{
if (!c.BoundsContain(x, y, FloorEps)) continue;
foreach (var f in c.Floors)
{
if (!Geo.InsideXY(f, x, y, FloorEps)) continue;
float fz = Geo.PlaneZ(f, x, y);
if (fz > z + FindAbove || fz < z - FindBelow) continue;
float edge = Geo.DistToOutlineXY(f, x, y);
float margin = Geo.InsideXY(f, x, y, 0) ? edge : -edge;
bool better = best == null
|| fz > bestZ + TieZ
|| (fz >= bestZ - TieZ && margin > bestMargin);
if (better) { best = c; bestZ = fz; bestMargin = margin; }
}
}
return best == null ? null : (best.Id, bestZ);
}
/// <summary>
/// The floor height of cell <paramref name="cellId"/> at (x, y), or null when (x, y) is not over its floor
/// (or the cell is unknown). Where the cell has several floors over (x, y), the one nearest
/// <paramref name="near"/>, or the highest when <paramref name="near"/> is null.
/// </summary>
public float? FloorZ(uint cellId, float x, float y, float? near = null)
{
var c = GetCell(cellId);
return c == null ? null : CellFloorZ(c, x, y, near, FloorEps);
}
/// <summary><see cref="FloorZ(uint, float, float, float?)"/> for a cell already in hand.</summary>
public static float? CellFloorZ(EnvCell c, float x, float y, float? near = null, float eps = FloorEps)
{
float? best = null;
foreach (var f in c.Floors)
{
if (!Geo.InsideXY(f, x, y, eps)) continue;
float z = Geo.PlaneZ(f, x, y);
bool better = best == null || (near != null
? MathF.Abs(z - near.Value) < MathF.Abs(best.Value - near.Value)
: z > best.Value);
if (better) best = z;
}
return best;
}
/// <summary>
/// The height of the feet of someone standing in cell <paramref name="cellId"/> at (x, y), whose body
/// touches the floor with a sphere of radius <paramref name="radius"/> (the human Setup 0x02000001 uses
/// 0.48 m; see <see cref="ModelReader"/>). This is the z ACE reports for a grounded creature: equal to
/// <see cref="FloorZ"/> on flat floor, but above the floor plane on a slope (radius * (1 / n.Z - 1),
/// about 0.12 m on a 37 degree ramp) and where a ramp meets a flat floor. Null when (x, y) is not over
/// the cell's floor.
/// <para>The sphere rests on the highest floor polygon under it among those at the level picked by
/// <see cref="FloorZ"/> (with <paramref name="near"/>): from 0.5 m below to <see cref="FindAbove"/>
/// above that floor.</para>
/// </summary>
public float? StandZ(uint cellId, float x, float y, float radius, float? near = null)
{
var c = GetCell(cellId);
return c == null ? null : CellStandZ(c, x, y, radius, near);
}
/// <summary><see cref="StandZ"/> for a cell already in hand.</summary>
public static float? CellStandZ(EnvCell c, float x, float y, float radius, float? near = null)
{
float? level = CellFloorZ(c, x, y, near);
if (level == null) return null;
float best = level.Value;
foreach (var f in c.Floors)
{
float? rz = Geo.SphereRestZ(f, x, y, radius);
if (rz == null || rz.Value < level.Value - 0.5f || rz.Value > level.Value + FindAbove) continue;
best = MathF.Max(best, rz.Value);
}
return best;
}
/// <summary>
/// The cell someone is in after moving in a straight line from <paramref name="a"/> to <paramref name="b"/>
/// (landblock-local feet positions), starting in indoor cell <paramref name="fromCell"/>.
/// <para>
/// The move is sampled every <see cref="TrackStep"/> and tested <see cref="PortalLift"/> above the feet.
/// Each step that passes through one of the current cell's portal polygons outward (toward the side
/// <see cref="CellPortal.PortalSide"/> gives the other cell) moves into the cell behind it, any number
/// of cells along the way. A point exactly on a doorway's plane (within 0.5 mm) stays in the cell it
/// came from, so a stop right in a doorway does not flip cells.
/// </para>
/// <para>
/// Against ACE (dungeon 0x6146): for 19476 pairs of captured positions in neighbouring cells up to 4 m
/// apart, 19473 end in the other position's cell; the 3 others end at one position that lies 2 mm on
/// the near side of a doorway's plane although ACE puts it in the far cell.
/// </para>
/// Returns:
/// <list type="bullet">
/// <item>the final cell's id (<paramref name="fromCell"/> itself when no portal was crossed);</item>
/// <item>0 when the move goes out through a portal whose OtherCell is 0xFFFF: the walker is outdoors and
/// the caller computes the outdoor land cell from the position;</item>
/// <item><paramref name="fromCell"/> when the move cannot be followed: a sample leaves the current cell's
/// floor plan (its physics polygons seen from above) without passing a portal - through a wall, or
/// geometry missing - or <paramref name="fromCell"/> is not a known indoor cell. Treat that as "blocked or
/// unknown": keep the old cell, and re-check with <see cref="FindCell"/> if in doubt.</item>
/// </list>
/// </summary>
public uint TrackCell(uint fromCell, Vector3 a, Vector3 b)
{
if (!EnvCell.IsIndoor(fromCell)) return fromCell;
var lb = Get(fromCell);
if (!lb.ById.TryGetValue(fromCell, out var cur)) return fromCell;
float len = Vector3.Distance(a, b);
int n = Math.Max(1, (int)MathF.Ceiling(len / TrackStep));
var lift = new Vector3(0, 0, PortalLift);
Vector3 prev = a;
for (int i = 1; i <= n; i++)
{
Vector3 p = Vector3.Lerp(a, b, i / (float)n);
EnvCell? next = null;
foreach (var cp in cur.Portals)
{
if (cp.Polygon.Length < 3) continue;
if (!Geo.SegmentCrossesToward(cp.Polygon, prev + lift, p + lift, cp.PortalSide)) continue;
if (cp.LeadsOutdoors) return 0;
if (lb.ById.TryGetValue(cur.Neighbour(cp), out var other)) { next = other; break; }
}
if (next != null)
{
// A sloping doorway (a tunnel mouth under a slanted roof, dungeon 0x6346) is crossed this high
// above the feet before the floor beyond it starts: until it does, stay on this cell's floor.
if (next.CoversXY(p.X, p.Y, InCellEps) || !cur.CoversXY(p.X, p.Y, InCellEps)) cur = next;
}
else if (!cur.CoversXY(p.X, p.Y, InCellEps))
{
// Off this floor: into the cell behind a sloping doorway passed (above the feet) earlier.
EnvCell? beyond = BeyondSlopedDoorway(lb, cur, p, p + lift);
if (beyond == null) return fromCell;
cur = beyond;
}
prev = p;
}
return cur.Id;
}
// The neighbour whose floor plan covers p, behind one of cur's doorways that the feet or the lifted point
// are already through: beyond the doorway's plane (by less than a step) and over the doorway itself, not
// the wall beside it. Walking down under a sloping doorway the lifted point passes it first; walking up
// out from under it, the feet do.
private static EnvCell? BeyondSlopedDoorway(Landblock lb, EnvCell cur, Vector3 p, Vector3 lifted)
{
foreach (var cp in cur.Portals)
{
if (cp.Polygon.Length < 3 || cp.LeadsOutdoors) continue;
if (!lb.ById.TryGetValue(cur.Neighbour(cp), out var other)) continue;
if (!other.CoversXY(p.X, p.Y, InCellEps)) continue;
if (Geo.BeyondThrough(cp.Polygon, lifted, cp.PortalSide, SlopedDoorwayReach)
|| Geo.BeyondThrough(cp.Polygon, p, cp.PortalSide, SlopedDoorwayReach))
return other;
}
return null;
}
/// <summary>The cell's floor polygons (walkable physics polygons), landblock-local; empty for an unknown cell.</summary>
public IReadOnlyList<Vector3[]> Floors(uint cellId) => GetCell(cellId)?.Floors ?? (IReadOnlyList<Vector3[]>)Array.Empty<Vector3[]>();
/// <summary>The cell's other physics polygons (walls, ceilings, steep slopes), landblock-local; empty for an unknown cell.</summary>
public IReadOnlyList<Vector3[]> Walls(uint cellId) => GetCell(cellId)?.Walls ?? (IReadOnlyList<Vector3[]>)Array.Empty<Vector3[]>();
/// <summary>The physics polygons of the cell's static objects, placed landblock-local (objects without physics give none).</summary>
public IEnumerable<Vector3[]> ObjectPolygons(uint cellId)
{
var c = GetCell(cellId);
if (c == null) yield break;
foreach (var s in c.Stabs)
foreach (var p in Models.Get(s.Id).Place(s.Origin, s.Rotation))
yield return p;
}
/// <summary>The cells next to <paramref name="cellId"/> through its portals (full ids; outdoors not included).</summary>
public IEnumerable<uint> Neighbours(uint cellId)
{
var c = GetCell(cellId);
if (c == null) yield break;
foreach (var p in c.Portals)
if (!p.LeadsOutdoors) yield return c.Neighbour(p);
}
}

View file

@ -0,0 +1,88 @@
// ============================================================================
// RynthCore.Geometry - Collision/CollisionTri.cs
// One solid triangle of the outdoor world (a face of a static object, a
// building shell, a building cell or a piece of scenery), landblock-local,
// with its unit normal by vertex order and the id of what it came from; and
// the segment-vs-triangle test the collision queries use.
//
// Logic from RynthSuite Tools/RynthNav.Baker/CollisionGeometry.cs (d4ae46a),
// Tri and Tri.Hit. Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
namespace RynthCore.Geometry.Collision;
/// <summary>
/// A solid triangle, landblock-local (x, y in the frame of the landblock that was queried, z absolute).
/// <see cref="Normal"/> is the unit normal by vertex order (A, B, C counter-clockwise seen from the side it
/// points to; for a fanned polygon, the whole polygon's normal as ACE's Polygon.make_plane computes it).
/// <see cref="Source"/> is the model id (GfxObj 0x01.. / Setup 0x02..) it belongs to, or the EnvCell id
/// (0xXXYY01nn..) for a building cell's own walls and floors.
/// </summary>
public readonly record struct CollisionTri(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal, uint Source)
{
/// <summary>Can it be stood on: normal.Z at least ACE's FloorZ (0.66417414, about 48 degrees)?</summary>
public bool Walkable => Normal.Z >= CellDat.FloorZ;
public float MinX => MathF.Min(A.X, MathF.Min(B.X, C.X));
public float MaxX => MathF.Max(A.X, MathF.Max(B.X, C.X));
public float MinY => MathF.Min(A.Y, MathF.Min(B.Y, C.Y));
public float MaxY => MathF.Max(A.Y, MathF.Max(B.Y, C.Y));
public float MinZ => MathF.Min(A.Z, MathF.Min(B.Z, C.Z));
public float MaxZ => MathF.Max(A.Z, MathF.Max(B.Z, C.Z));
/// <summary>The same triangle moved by <paramref name="d"/>.</summary>
public CollisionTri Shifted(Vector3 d) => this with { A = A + d, B = B + d, C = C + d };
/// <summary>
/// Segment <paramref name="p0"/> to <paramref name="p1"/> against the triangle, from either side
/// (Moller-Trumbore). <paramref name="t"/> is the fraction along the segment, 0..1.
/// </summary>
public bool Hit(Vector3 p0, Vector3 p1, out float t)
{
t = 0;
Vector3 d = p1 - p0, e1 = B - A, e2 = C - A;
Vector3 h = Vector3.Cross(d, e2);
float det = Vector3.Dot(e1, h);
if (MathF.Abs(det) < 1e-12f) return false;
float inv = 1f / det;
Vector3 s = p0 - A;
float u = Vector3.Dot(s, h) * inv;
if (u < 0 || u > 1) return false;
Vector3 q = Vector3.Cross(s, e1);
float v = Vector3.Dot(d, q) * inv;
if (v < 0 || u + v > 1) return false;
t = Vector3.Dot(e2, q) * inv;
return t >= 0 && t <= 1;
}
/// <summary>Is (x, y) inside the triangle seen from above (within <paramref name="eps"/> metres of it)?</summary>
public bool ContainsXY(float x, float y, float eps = 0.001f)
{
float d1 = Edge(A, B, x, y), d2 = Edge(B, C, x, y), d3 = Edge(C, A, x, y);
bool neg = d1 < 0 || d2 < 0 || d3 < 0, pos = d1 > 0 || d2 > 0 || d3 > 0;
if (!(neg && pos)) return true;
return Geo.DistToSegXY(A.X, A.Y, B.X, B.Y, x, y) <= eps
|| Geo.DistToSegXY(B.X, B.Y, C.X, C.Y, x, y) <= eps
|| Geo.DistToSegXY(C.X, C.Y, A.X, A.Y, x, y) <= eps;
}
/// <summary>The height of the triangle's plane at (x, y); NaN for a vertical triangle.</summary>
public float PlaneZ(float x, float y)
{
if (MathF.Abs(Normal.Z) < 1e-6f) return float.NaN;
return A.Z - (Normal.X * (x - A.X) + Normal.Y * (y - A.Y)) / Normal.Z;
}
/// <summary>Distance seen from above from (x, y) to the triangle (0 inside).</summary>
public float DistXY(float x, float y)
{
if (ContainsXY(x, y, 0)) return 0;
return MathF.Min(Geo.DistToSegXY(A.X, A.Y, B.X, B.Y, x, y),
MathF.Min(Geo.DistToSegXY(B.X, B.Y, C.X, C.Y, x, y), Geo.DistToSegXY(C.X, C.Y, A.X, A.Y, x, y)));
}
private static float Edge(Vector3 a, Vector3 b, float x, float y) => (b.X - a.X) * (y - a.Y) - (b.Y - a.Y) * (x - a.X);
}

View file

@ -0,0 +1,97 @@
// ============================================================================
// RynthCore.Geometry - Collision/ModelTriangles.cs
// A placed model as collision triangles, with the shape ACE's
// PhysicsObj.FindObjCollisions collides with: the physics polygons of its
// parts when any part has a physics BSP; otherwise a Setup's collision
// cylinders, or failing those its spheres, each as a closed 8-sided prism.
// Also: a polygon (an EnvCell wall or floor) fanned into triangles.
//
// Logic from RynthSuite Tools/RynthNav.Baker/CollisionGeometry.cs (d4ae46a),
// AppendModel / AddPolys / AddPrism. Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Scenery;
namespace RynthCore.Geometry.Collision;
internal sealed class ModelTriangles
{
private readonly ModelReader _models;
private readonly DatDatabase _portal;
private readonly ConcurrentDictionary<uint, SetupBounds?> _bounds = new();
public ModelTriangles(ModelReader models, DatDatabase portal)
{
_models = models;
_portal = portal;
}
/// <summary>Setups that collide with cylinders or spheres read from the end of their record (diagnostics).</summary>
public int TailReads;
/// <summary>Adds model <paramref name="model"/> placed at <paramref name="origin"/> / <paramref name="rotation"/> / <paramref name="scale"/>.</summary>
public void Append(uint model, Vector3 origin, Quaternion rotation, float scale, List<CollisionTri> into)
{
var shape = _models.Get(model);
if (shape.Polygons.Count > 0)
{
foreach (var poly in shape.Place(origin, rotation, scale)) AppendPolygon(poly, model, into);
return;
}
if ((model >> 24) != 0x02) return;
var b = _bounds.GetOrAdd(model, id => SetupBounds.Read(_portal, id));
if (b == null) return;
if (b.FromTail && (b.Cylinders.Count > 0 || b.Spheres.Count > 0)) Interlocked.Increment(ref TailReads);
Vector3 World(Vector3 p) => Vector3.Transform(p, rotation) + origin;
if (b.Cylinders.Count > 0)
foreach (var c in b.Cylinders)
AppendPrism(c.Origin * scale, c.Radius * scale, 0, c.Height * scale, World, model, into);
else
foreach (var s in b.Spheres)
AppendPrism(s.Center * scale, s.Radius * scale, -s.Radius * scale, s.Radius * scale, World, model, into);
}
/// <summary>A convex polygon fanned into triangles that share its normal (by vertex order); degenerate ones are dropped.</summary>
public static void AppendPolygon(IReadOnlyList<Vector3> poly, uint source, List<CollisionTri> into)
{
if (poly.Count < 3) return;
Vector3 n = CellDat.Normal(poly);
if (n == Vector3.Zero || !float.IsFinite(n.X)) return;
Vector3 a = poly[0];
for (int i = 1; i < poly.Count - 1; i++)
{
Vector3 b = poly[i], c = poly[i + 1];
if (Vector3.Cross(b - a, c - a).LengthSquared() < 1e-10f) continue;
into.Add(new CollisionTri(a, b, c, n, source));
}
}
/// <summary>A closed 8-sided prism (sides, top and bottom), outward normals, standing in for a cylinder or sphere.</summary>
private static void AppendPrism(Vector3 center, float radius, float z0, float z1, Func<Vector3, Vector3> world, uint source, List<CollisionTri> into)
{
if (!(radius > 0.01f) || !(z1 > z0)) return;
const int N = 8;
var lo = new Vector3[N];
var hi = new Vector3[N];
for (int i = 0; i < N; i++)
{
float a = i * MathF.PI * 2 / N;
float x = center.X + radius * MathF.Cos(a), y = center.Y + radius * MathF.Sin(a);
lo[i] = world(new Vector3(x, y, center.Z + z0));
hi[i] = world(new Vector3(x, y, center.Z + z1));
}
Vector3 cl = world(new Vector3(center.X, center.Y, center.Z + z0)), ch = world(new Vector3(center.X, center.Y, center.Z + z1));
for (int i = 0; i < N; i++)
{
int j = (i + 1) % N;
AppendPolygon(new[] { lo[i], lo[j], hi[j], hi[i] }, source, into);
AppendPolygon(new[] { ch, hi[i], hi[j] }, source, into);
AppendPolygon(new[] { cl, lo[j], lo[i] }, source, into);
}
}
}

View file

@ -0,0 +1,310 @@
// ============================================================================
// RynthCore.Geometry - Collision/OutdoorCollision.cs
// What an outdoor walker collides with besides the terrain: per landblock,
// the static objects and building shells of its LandblockInfo, the walls,
// floors and objects of its building cells (EnvCells flagged SeenOutside),
// and the scenery the server places. Each landblock's triangles are built
// on first use, kept, and indexed on a 4 m grid; queries near a landblock
// edge also see the neighbouring landblocks' triangles, shifted into the
// queried landblock's frame.
//
// Logic from RynthSuite Tools/RynthNav.Baker/CollisionGeometry.cs (d4ae46a):
// AppendStatics, AppendBuildingCells, AppendScenery. RaiseIfLow is left out:
// it raises low objects into walls for the navmesh baker's 1 m climb, which
// a walker that steps like the client does not need.
// Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Scenery;
using RynthCore.Geometry.Terrain;
namespace RynthCore.Geometry.Collision;
/// <summary>Where a landblock's collision triangles came from (diagnostics).</summary>
public readonly record struct CollisionCounts(
int StaticObjects, int StaticTris,
int Buildings, int BuildingTris,
int BuildingCells, int BuildingCellTris,
int CellObjects, int CellObjectTris,
int Scenery, int SceneryTris)
{
public int Total => StaticTris + BuildingTris + BuildingCellTris + CellObjectTris + SceneryTris;
public override string ToString() =>
$"{Total} tris: statics {StaticObjects} ({StaticTris}), buildings {Buildings} ({BuildingTris}), " +
$"building cells {BuildingCells} ({BuildingCellTris}), cell objects {CellObjects} ({CellObjectTris}), scenery {Scenery} ({SceneryTris})";
}
/// <summary>
/// Outdoor collision geometry (everything solid but the terrain), landblock by landblock.
/// <para>Coordinates: every query names a landblock (0xXXYY or any 0xXXYYnnnn id) and takes and returns
/// positions in that landblock's frame (x, y in 0..192 from its SW corner, z absolute). Near an edge the
/// neighbouring landblocks' triangles are included, moved into that frame.</para>
/// <para>Thread-safe: each landblock is built once (other callers wait for that build) and never changed.</para>
/// </summary>
public sealed class OutdoorCollision
{
/// <summary>Grid bucket size, metres.</summary>
public const float Bucket = 4f;
/// <summary>How far a landblock's triangles may reach past its edge for a query to look at that neighbour.</summary>
public const float MaxOverhang = 24f;
/// <summary>ACE's FloorZ: a triangle with normal.Z at least this can be stood on.</summary>
public const float FloorZ = CellDat.FloorZ;
private const int Side = (int)(LandblockData.BlockLength / Bucket); // 48 buckets a side
private readonly DatDatabase _cell;
private readonly TerrainSampler _terrain;
private readonly IndoorWorld _indoor;
private readonly ModelTriangles _shapes;
private readonly ConcurrentDictionary<uint, Lazy<Block>> _blocks = new();
/// <summary>The scenery placer this uses (its tables are shared).</summary>
public SceneryPlacer Scenery { get; }
public OutdoorCollision(DatDatabase cell, DatDatabase portal, TerrainSampler terrain, ModelReader models, IndoorWorld indoor)
{
_cell = cell;
_terrain = terrain;
_indoor = indoor;
_shapes = new ModelTriangles(models, portal);
Scenery = new SceneryPlacer(cell, portal, terrain, models);
}
/// <summary>Setups whose cylinders/spheres had to be read from the end of their record (diagnostics).</summary>
public int TailReads => _shapes.TailReads;
// ---- per-landblock build ----------------------------------------------------------
private sealed class Block
{
public CollisionTri[] Tris = Array.Empty<CollisionTri>();
public float[] MinX = Array.Empty<float>(), MaxX = Array.Empty<float>(), MinY = Array.Empty<float>(), MaxY = Array.Empty<float>();
public int[][] Grid = Array.Empty<int[]>();
public float BMinX, BMinY, BMaxX, BMaxY; // XY bounds of all triangles (empty: Min > Max)
public CollisionCounts Counts;
public IReadOnlyList<SceneryObject> Scenery = Array.Empty<SceneryObject>();
}
private static uint Key(uint landblock) => LandblockData.KeyOf(landblock);
private Block Get(uint landblock) =>
_blocks.GetOrAdd(Key(landblock), k => new Lazy<Block>(() => Build(k), LazyThreadSafetyMode.ExecutionAndPublication)).Value;
/// <summary>Forgets a landblock's triangles (built again on next use).</summary>
public void Unload(uint landblock) => _blocks.TryRemove(Key(landblock), out _);
private Block Build(uint lb)
{
var tris = new List<CollisionTri>();
int statics = 0, staticTris = 0, buildings = 0, buildingTris = 0, cells = 0, cellTris = 0, cellObjs = 0, cellObjTris = 0;
var info = LandblockInfo.Load(_cell, lb);
if (info != null)
{
foreach (var s in info.Objects)
{
int n0 = tris.Count;
_shapes.Append(s.Id, s.Origin, s.Rotation, 1f, tris);
statics++; staticTris += tris.Count - n0;
}
foreach (var b in info.Buildings)
{
int n0 = tris.Count;
_shapes.Append(b.ModelId, b.Origin, b.Rotation, 1f, tris);
buildings++; buildingTris += tris.Count - n0;
}
}
// Building interiors: the EnvCells seen from outside (dungeon cells are not).
if (info == null || info.NumCells > 0)
{
foreach (var c in _indoor.LoadLandblock(lb))
{
if ((c.Flags & 0x01) == 0) continue;
cells++;
int n0 = tris.Count;
foreach (var f in c.Floors) ModelTriangles.AppendPolygon(f, c.Id, tris);
foreach (var w in c.Walls) ModelTriangles.AppendPolygon(w, c.Id, tris);
cellTris += tris.Count - n0;
foreach (var s in c.Stabs)
{
n0 = tris.Count;
_shapes.Append(s.Id, s.Origin, s.Rotation, 1f, tris);
cellObjs++; cellObjTris += tris.Count - n0;
}
}
}
var scenery = Scenery.Place(lb);
int sceneryTris0 = tris.Count;
foreach (var o in scenery) _shapes.Append(o.ModelId, o.Position, o.Rotation, o.Scale, tris);
var block = new Block
{
Tris = tris.ToArray(),
Scenery = scenery,
Counts = new CollisionCounts(statics, staticTris, buildings, buildingTris, cells, cellTris, cellObjs, cellObjTris,
scenery.Count, tris.Count - sceneryTris0),
};
Index(block);
return block;
}
private static int Cell(float v) => Math.Clamp((int)MathF.Floor(v / Bucket), 0, Side - 1);
private static void Index(Block b)
{
int n = b.Tris.Length;
b.MinX = new float[n]; b.MaxX = new float[n]; b.MinY = new float[n]; b.MaxY = new float[n];
b.BMinX = b.BMinY = float.MaxValue; b.BMaxX = b.BMaxY = float.MinValue;
var lists = new List<int>?[Side * Side];
for (int i = 0; i < n; i++)
{
var t = b.Tris[i];
b.MinX[i] = t.MinX; b.MaxX[i] = t.MaxX; b.MinY[i] = t.MinY; b.MaxY[i] = t.MaxY;
b.BMinX = MathF.Min(b.BMinX, t.MinX); b.BMaxX = MathF.Max(b.BMaxX, t.MaxX);
b.BMinY = MathF.Min(b.BMinY, t.MinY); b.BMaxY = MathF.Max(b.BMaxY, t.MaxY);
for (int gx = Cell(t.MinX); gx <= Cell(t.MaxX); gx++)
for (int gy = Cell(t.MinY); gy <= Cell(t.MaxY); gy++)
(lists[gx * Side + gy] ??= new List<int>()).Add(i);
}
b.Grid = lists.Select(l => l?.ToArray() ?? Array.Empty<int>()).ToArray();
}
/// <summary>
/// Calls <paramref name="visit"/> once for every triangle of <paramref name="b"/> whose XY bounds overlap
/// the box (in <paramref name="b"/>'s own frame). Each triangle is reported from one bucket only: the first
/// bucket of the overlap of its bounds and the box.
/// </summary>
private static void Visit(Block b, float x0, float y0, float x1, float y1, Action<int> visit)
{
if (b.Tris.Length == 0 || x1 < b.BMinX || x0 > b.BMaxX || y1 < b.BMinY || y0 > b.BMaxY) return;
int gx0 = Cell(x0), gx1 = Cell(x1), gy0 = Cell(y0), gy1 = Cell(y1);
for (int gx = gx0; gx <= gx1; gx++)
for (int gy = gy0; gy <= gy1; gy++)
foreach (int i in b.Grid[gx * Side + gy])
{
if (b.MaxX[i] < x0 || b.MinX[i] > x1 || b.MaxY[i] < y0 || b.MinY[i] > y1) continue;
if (Math.Max(Cell(b.MinX[i]), gx0) != gx || Math.Max(Cell(b.MinY[i]), gy0) != gy) continue;
visit(i);
}
}
/// <summary>
/// Runs <paramref name="each"/> for the landblock itself and every neighbour whose triangles may reach the
/// box (given in <paramref name="landblock"/>'s frame), with that block and the shift from its frame into
/// the landblock's (neighbour position + shift = position in the queried frame).
/// </summary>
private void ForBlocks(uint landblock, float x0, float y0, float x1, float y1, Action<Block, Vector3> each)
{
uint key = Key(landblock);
int lx = (int)(key >> 8), ly = (int)(key & 0xFF);
const float L = LandblockData.BlockLength;
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
{
int nx = lx + dx, ny = ly + dy;
if (nx < 0 || ny < 0 || nx > 0xFF || ny > 0xFF) continue;
float sx = dx * L, sy = dy * L;
if (dx != 0 || dy != 0)
{
// the box in the neighbour's frame must come within MaxOverhang of its square
float bx0 = x0 - sx, bx1 = x1 - sx, by0 = y0 - sy, by1 = y1 - sy;
if (bx1 < -MaxOverhang || bx0 > L + MaxOverhang || by1 < -MaxOverhang || by0 > L + MaxOverhang) continue;
}
each(Get((uint)(nx << 8 | ny)), new Vector3(sx, sy, 0));
}
}
// ---- queries ----------------------------------------------------------------------
/// <summary>The triangles of a landblock and its neighbours whose XY bounds come within <paramref name="radius"/> of (x, y).</summary>
public IReadOnlyList<CollisionTri> Near(uint landblock, float x, float y, float radius)
{
var result = new List<CollisionTri>();
float r2 = radius * radius;
ForBlocks(landblock, x - radius, y - radius, x + radius, y + radius, (b, shift) =>
{
float qx = x - shift.X, qy = y - shift.Y;
Visit(b, qx - radius, qy - radius, qx + radius, qy + radius, i =>
{
float ex = MathF.Max(0, MathF.Max(b.MinX[i] - qx, qx - b.MaxX[i]));
float ey = MathF.Max(0, MathF.Max(b.MinY[i] - qy, qy - b.MaxY[i]));
if (ex * ex + ey * ey > r2) return;
result.Add(shift == Vector3.Zero ? b.Tris[i] : b.Tris[i].Shifted(shift));
});
});
return result;
}
/// <summary>
/// The nearest triangle the segment <paramref name="a"/> to <paramref name="b"/> hits (either face), and
/// where: <paramref name="t"/> is the fraction along the segment (0..1). False when it hits nothing.
/// </summary>
public bool SegmentHit(uint landblock, Vector3 a, Vector3 b, out float t, out CollisionTri tri)
{
float bestT = float.MaxValue;
CollisionTri best = default;
float x0 = MathF.Min(a.X, b.X), x1 = MathF.Max(a.X, b.X), y0 = MathF.Min(a.Y, b.Y), y1 = MathF.Max(a.Y, b.Y);
float zLo = MathF.Min(a.Z, b.Z), zHi = MathF.Max(a.Z, b.Z);
ForBlocks(landblock, x0, y0, x1, y1, (blk, shift) =>
{
Vector3 pa = a - shift, pb = b - shift;
Visit(blk, x0 - shift.X, y0 - shift.Y, x1 - shift.X, y1 - shift.Y, i =>
{
var tr = blk.Tris[i];
if (tr.MaxZ < zLo || tr.MinZ > zHi) return;
if (tr.Hit(pa, pb, out float ht) && ht < bestT)
{
bestT = ht;
best = shift == Vector3.Zero ? tr : tr.Shifted(shift);
}
});
});
t = bestT == float.MaxValue ? 0 : bestT;
tri = best;
return bestT != float.MaxValue;
}
/// <summary>
/// The highest walkable (normal.Z &gt;= FloorZ) object or building triangle under (x, y) whose height
/// there is at most <paramref name="zTop"/> and above <paramref name="zTop"/> - <paramref name="maxDrop"/>;
/// null when there is none. The terrain is not included (take the max with the terrain yourself).
/// </summary>
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop)
{
float? best = null;
float lo = zTop - maxDrop;
ForBlocks(landblock, x, y, x, y, (b, shift) =>
{
float qx = x - shift.X, qy = y - shift.Y;
Visit(b, qx, qy, qx, qy, i =>
{
var tr = b.Tris[i];
if (!tr.Walkable || tr.MinZ > zTop || tr.MaxZ <= lo) return;
if (!tr.ContainsXY(qx, qy)) return;
float z = tr.PlaneZ(qx, qy);
if (z > zTop || z <= lo) return;
if (best == null || z > best.Value) best = z;
});
});
return best;
}
/// <summary>The number of collision triangles of the landblock itself (no neighbours).</summary>
public int Count(uint landblock) => Get(landblock).Tris.Length;
/// <summary>Where the landblock's triangles came from.</summary>
public CollisionCounts Counts(uint landblock) => Get(landblock).Counts;
/// <summary>The landblock's own triangles, in its frame (no neighbours).</summary>
public IReadOnlyList<CollisionTri> Triangles(uint landblock) => Get(landblock).Tris;
/// <summary>The scenery placed in the landblock (as used for its collision).</summary>
public IReadOnlyList<SceneryObject> SceneryOf(uint landblock) => Get(landblock).Scenery;
}

View file

@ -0,0 +1,515 @@
// ============================================================================
// RynthCore.Geometry - Dat/DatDatabase.cs (moved from RynthSuite Shared/RynthCore.TerrainData, 2f49195)
// Read-only access to Asheron's Call .dat archives (client_portal.dat,
// client_cell_1.dat, ...). Written for RynthCore (MIT) on 2026-10-05.
//
// Written from the dat container format as it is publicly documented, with
// Chorizite's DatReaderWriter (MIT, notice below) used as the format reference:
// - file header at byte 0x140: magic, block size, file size, data set,
// subset, free head / tail / count, then the byte offset of the root
// B-tree node (all little-endian uint32);
// - storage is fixed-size blocks; a block's first uint32 is the byte offset
// of the next block of the same chain (0 ends the chain), the remaining
// BlockSize - 4 bytes are payload;
// - the directory is a B-tree whose nodes are stored as block chains: 62
// uint32 child offsets, a uint32 entry count (at most 61), then the
// entries, 24 bytes each: flags/version, id, byte offset of the file's
// first block, size, timestamp, iteration. Entries are sorted by id,
// child i holds the ids between entry i-1 and entry i, and a node whose
// first child offset is 0 is a leaf.
//
// Nothing is indexed up front: lookups descend the tree from the root. Every
// interior node is kept once read (about 1 node in 62, a few hundred KB for
// client_cell_1.dat) and leaves go through a small LRU, so a lookup usually
// costs one leaf read and neighbouring ids (adjacent landblocks) none. The
// public API (null when a file or the database is missing) is the one
// RynthAi, RynthVision, RynthJuice and the RynthNav tools already use.
//
// Thread-safety: every stream read and cache access holds one lock, so one
// database can be shared between threads. NativeAOT/trimming safe (no
// reflection).
//
// Chorizite DatReaderWriter notice (format reference):
// Copyright 2024 ACClientLib
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions: The above copyright notice and this permission
// notice shall be included in all copies or substantial portions of the
// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// ============================================================================
// The API returns null for "not there" without annotations; its callers
// (RynthAi, RynthJuice, RynthVision) are written against that.
#nullable disable
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Geometry.Dat
{
/// <summary>
/// A read-only .dat archive. <see cref="Open"/> reads the header and checks
/// the root directory node; files are then found by id
/// (<see cref="FindFile"/>, <see cref="GetFileData"/>) by searching the
/// on-disk B-tree. Methods return null / empty when the database isn't open
/// or the file isn't there; nothing throws for a missing or damaged file.
/// </summary>
public class DatDatabase : IDisposable
{
// ---- container layout ----
private const long HeaderOffset = 0x140;
private const int HeaderBytes = 9 * 4; // magic .. root offset
private const int ChildSlots = 62;
private const int MaxEntriesPerNode = 61;
private const int EntryBytes = 24;
private const int CountOffset = ChildSlots * 4; // 248
private const int EntriesOffset = CountOffset + 4; // 252
private const int NodeBytes = EntriesOffset + MaxEntriesPerNode * EntryBytes; // 1716
// A real tree is 4 levels deep at most; this only stops a damaged child
// pointer from sending a search round in circles.
private const int DepthLimit = 16;
// Cache budget: all interior nodes (capped), a 128-leaf LRU.
private const int LeafLruSize = 128;
private const int InteriorCap = 4096;
private readonly object _gate = new object();
private FileStream _file;
private long _length;
private byte[] _nodeBuf; // one node's bytes, reused (under _gate)
private readonly Dictionary<uint, Node> _interior = new Dictionary<uint, Node>();
private readonly LruCache<uint, Node> _leaves = new LruCache<uint, Node>(LeafLruSize);
private int _count = -1;
/// <summary>Header word at 0x140 (the dat magic).</summary>
public uint FileType { get; private set; }
/// <summary>Block size in bytes (1024 in the retail dats).</summary>
public uint BlockSize { get; private set; }
/// <summary>File size recorded in the header.</summary>
public uint FileSize { get; private set; }
/// <summary>The header's data set (database type) word.</summary>
public uint DataSet { get; private set; }
/// <summary>Byte offset of the root directory node.</summary>
public uint BTreeRoot { get; private set; }
/// <summary>True between a successful <see cref="Open"/> and <see cref="Close"/>.</summary>
public bool IsLoaded { get; private set; }
/// <summary>The path last passed to <see cref="Open"/>.</summary>
public string FilePath { get; private set; }
/// <summary>Diagnostics from Open and failed reads (first 100 lines).</summary>
public List<string> DiagLog { get; } = new List<string>();
/// <summary>
/// Number of files in the dat. Counted on first use from the directory
/// nodes' entry counts (only the first bytes of each node are read) and
/// remembered until <see cref="Close"/>; 0 when not open.
/// </summary>
public int RecordCount
{
get
{
lock (_gate)
{
if (!IsLoaded) return 0;
if (_count < 0) _count = CountUnder(BTreeRoot, 0);
return _count;
}
}
}
private sealed class Node
{
public uint[] Children; // entry count + 1 offsets; null for a leaf
public DatBTreeEntry[] Entries; // ascending ObjectId
}
// ------------------------------------------------------------------ open / close
/// <summary>Opens <paramref name="path"/> read-only. False (and a DiagLog line) on any failure.</summary>
public bool Open(string path)
{
lock (_gate)
{
CloseLocked();
FilePath = path;
try
{
if (!File.Exists(path)) { Log($"Not found: {path}"); return false; }
// acclient.exe keeps its own handles on the dats and may open
// them after us (RynthAi opens at plugin init), so share
// everything, including delete: the client's open asks for
// delete-rename access and fails ("cannot access the data
// files") if an earlier handle refuses it.
_file = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
_length = _file.Length;
Span<byte> h = stackalloc byte[HeaderBytes];
if (!ReadAt(HeaderOffset, h)) { Log("Header is short"); CloseLocked(); return false; }
FileType = BinaryPrimitives.ReadUInt32LittleEndian(h);
BlockSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(4));
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(8));
DataSet = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(12));
BTreeRoot = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(32));
Log($"Header: type=0x{FileType:X8} blockSize={BlockSize} fileSize={FileSize} dataSet=0x{DataSet:X8} root=0x{BTreeRoot:X8} (file {_length} bytes)");
if (BlockSize <= 4 || BlockSize > 0x10000) { Log($"Bad block size {BlockSize}"); CloseLocked(); return false; }
if (BTreeRoot == 0 || BTreeRoot >= _length) { Log($"Bad root offset 0x{BTreeRoot:X8}"); CloseLocked(); return false; }
_nodeBuf = new byte[NodeBytes];
IsLoaded = true;
if (GetNode(BTreeRoot) == null)
{
Log($"Root node at 0x{BTreeRoot:X8} doesn't parse");
CloseLocked();
return false;
}
Log($"Opened {Path.GetFileName(path)}");
return true;
}
catch (Exception ex)
{
Log($"Open failed: {ex.Message}");
CloseLocked();
return false;
}
}
}
/// <summary>Closes the file and drops the cached directory nodes.</summary>
public void Close()
{
lock (_gate) CloseLocked();
}
public void Dispose() { Close(); }
private void CloseLocked()
{
IsLoaded = false;
_file?.Dispose();
_file = null;
_length = 0;
_nodeBuf = null;
_interior.Clear();
_leaves.Clear();
_count = -1;
}
// ------------------------------------------------------------------ lookups
/// <summary>The directory entry for <paramref name="fileId"/>, or null.</summary>
public DatBTreeEntry FindFile(uint fileId)
{
lock (_gate)
{
if (!IsLoaded) return null;
uint at = BTreeRoot;
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
{
Node n = GetNode(at);
if (n == null) return null;
int i = LowerBound(n.Entries, fileId);
if (i < n.Entries.Length && n.Entries[i].ObjectId == fileId) return n.Entries[i];
if (n.Children == null) return null;
at = n.Children[i];
}
return null;
}
}
/// <summary>The bytes of the file <paramref name="entry"/> describes, or null.</summary>
public byte[] ReadFileData(DatBTreeEntry entry)
{
if (entry == null) return null;
lock (_gate)
{
if (!IsLoaded) return null;
if (entry.FileSize > _length) { Log($"0x{entry.ObjectId:X8}: size {entry.FileSize} exceeds the file"); return null; }
var data = new byte[entry.FileSize];
if (ReadChain(entry.FileOffset, data) != data.Length)
{
Log($"0x{entry.ObjectId:X8}: block chain at 0x{entry.FileOffset:X8} is broken");
return null;
}
return data;
}
}
/// <summary><see cref="FindFile"/> then <see cref="ReadFileData"/>.</summary>
public byte[] GetFileData(uint fileId) => ReadFileData(FindFile(fileId));
/// <summary>
/// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock
/// <paramref name="landblockKey"/> (0xXXYY), ascending. Only the nodes
/// whose id range overlaps the landblock are read.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
var found = new List<uint>();
lock (_gate)
{
if (!IsLoaded) return found;
uint lo = (landblockKey << 16) | 0x0100;
uint hi = (landblockKey << 16) | 0xFFFD;
CollectRange(BTreeRoot, lo, hi, found, 0);
}
return found;
}
// In-order walk of the part of the subtree at `at` holding ids in [lo, hi].
private void CollectRange(uint at, uint lo, uint hi, List<uint> into, int depth)
{
if (at == 0 || depth >= DepthLimit) return;
Node n = GetNode(at);
if (n == null) return;
var e = n.Entries;
for (int i = 0; i <= e.Length; i++)
{
// Child i spans (e[i-1], e[i]); visit it if that overlaps [lo, hi].
if (n.Children != null)
{
bool aboveLo = i == e.Length || e[i].ObjectId > lo;
bool belowHi = i == 0 || e[i - 1].ObjectId < hi;
if (aboveLo && belowHi) CollectRange(n.Children[i], lo, hi, into, depth + 1);
}
if (i == e.Length) break;
uint id = e[i].ObjectId;
if (id > hi) break;
if (id >= lo) into.Add(id);
}
}
/// <summary>
/// Every entry, ascending by id, read from the tree as it goes (nothing
/// is kept afterwards). Reads every node of the dat: for diagnostics and
/// offline tools, not for lookups.
/// </summary>
public IEnumerable<DatBTreeEntry> EnumerateEntries()
{
Node root;
lock (_gate)
{
if (!IsLoaded) yield break;
root = GetNodeUncached(BTreeRoot);
}
if (root == null) yield break;
// Explicit stack (no recursion through iterators); the lock is taken
// per node read, never held across a yield.
var stack = new Stack<(Node node, int next)>();
stack.Push((root, 0));
DescendLeft(stack);
while (stack.Count > 0)
{
var (node, next) = stack.Pop();
if (next >= node.Entries.Length) continue;
yield return node.Entries[next];
stack.Push((node, next + 1));
if (node.Children != null)
{
Node child = ReadForWalk(node.Children[next + 1], stack.Count);
if (child != null) { stack.Push((child, 0)); DescendLeft(stack); }
}
}
}
// Pushes the leftmost path below the node on top of the stack.
private void DescendLeft(Stack<(Node node, int next)> stack)
{
while (true)
{
var top = stack.Peek().node;
if (top.Children == null) return;
Node child = ReadForWalk(top.Children[0], stack.Count);
if (child == null) return;
stack.Push((child, 0));
}
}
private Node ReadForWalk(uint at, int depth)
{
if (at == 0 || depth >= DepthLimit) return null;
lock (_gate)
{
if (!IsLoaded) return null;
return GetNodeUncached(at);
}
}
/// <summary>The lowest file ids in the dat (up to <paramref name="maxCount"/>), for diagnostics.</summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
if (maxCount <= 0) return ids;
foreach (var e in EnumerateEntries())
{
ids.Add(e.ObjectId);
if (ids.Count >= maxCount) break;
}
return ids;
}
// ------------------------------------------------------------------ nodes
// First entry index whose id is >= id (Length when none).
private static int LowerBound(DatBTreeEntry[] e, uint id)
{
int a = 0, b = e.Length;
while (a < b)
{
int m = (a + b) >> 1;
if (e[m].ObjectId < id) a = m + 1; else b = m;
}
return a;
}
// Cached node. Caller holds _gate.
private Node GetNode(uint at)
{
if (_interior.TryGetValue(at, out Node n)) return n;
if (_leaves.TryGet(at, out n)) return n;
n = ParseNode(at);
if (n == null) return null;
if (n.Children != null)
{
if (_interior.Count < InteriorCap) _interior[at] = n;
}
else _leaves.Set(at, n);
return n;
}
// For full walks: use a cached node if there is one, but don't fill the
// caches with the whole tree. Caller holds _gate.
private Node GetNodeUncached(uint at)
{
if (_interior.TryGetValue(at, out Node n)) return n;
if (_leaves.TryGet(at, out n)) return n;
return ParseNode(at);
}
// Reads and decodes the node at byte offset `at`. Caller holds _gate.
private Node ParseNode(uint at)
{
byte[] buf = _nodeBuf;
int got = ReadChain(at, buf);
if (got < EntriesOffset) return null;
ReadOnlySpan<byte> s = buf;
int count = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(CountOffset));
if (count < 0 || count > MaxEntriesPerNode || got < EntriesOffset + count * EntryBytes) return null;
var entries = new DatBTreeEntry[count];
for (int i = 0; i < count; i++)
{
var r = s.Slice(EntriesOffset + i * EntryBytes, EntryBytes);
entries[i] = new DatBTreeEntry
{
BitFlags = BinaryPrimitives.ReadUInt32LittleEndian(r),
ObjectId = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(4)),
FileOffset = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(8)),
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(12)),
};
}
uint[] children = null;
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != 0)
{
children = new uint[count + 1];
for (int i = 0; i <= count; i++)
children[i] = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(i * 4));
}
return new Node { Children = children, Entries = entries };
}
// Node entry counts under `at`, reading only each node's first bytes
// (child table + count). Caller holds _gate.
private int CountUnder(uint at, int depth)
{
if (at == 0 || depth >= DepthLimit) return 0;
Span<byte> head = stackalloc byte[EntriesOffset];
if (ReadChain(at, head) != EntriesOffset) return 0;
int count = BinaryPrimitives.ReadInt32LittleEndian(head.Slice(CountOffset));
if (count < 0 || count > MaxEntriesPerNode) return 0;
int total = count;
if (BinaryPrimitives.ReadUInt32LittleEndian(head) != 0)
{
// Copy the child offsets out: the recursion reuses the stack.
Span<uint> kids = stackalloc uint[count + 1];
for (int i = 0; i <= count; i++) kids[i] = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(i * 4));
for (int i = 0; i <= count; i++) total += CountUnder(kids[i], depth + 1);
}
return total;
}
// ------------------------------------------------------------------ blocks
// Copies the block chain starting at byte offset `first` into `dest`
// and returns how many bytes it filled: dest.Length, or less when the
// chain ends (a 0 link) first; -1 when a link points outside the file.
// Caller holds _gate.
private int ReadChain(uint first, Span<byte> dest)
{
int payload = (int)BlockSize - 4;
long block = first;
int done = 0;
Span<byte> link = stackalloc byte[4];
while (done < dest.Length)
{
if (block == 0) return done;
if (block + 4 > _length) return -1;
int take = Math.Min(payload, dest.Length - done);
if (!ReadAt(block, link) || !ReadAt(block + 4, dest.Slice(done, take))) return -1;
done += take;
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
}
return done;
}
// Caller holds _gate (or is Open, before anything else can see the file).
private bool ReadAt(long offset, Span<byte> into)
{
if (offset < 0 || offset + into.Length > _length) return false;
_file.Position = offset;
int got = 0;
while (got < into.Length)
{
int n = _file.Read(into.Slice(got));
if (n <= 0) return false;
got += n;
}
return true;
}
private void Log(string msg)
{
string line = "[DatDB] " + msg;
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(line);
}
}
/// <summary>One directory entry: a file's id, flags, first block and size.</summary>
public class DatBTreeEntry
{
public uint BitFlags;
public uint ObjectId;
public uint FileOffset; // byte offset of the file's first block
public uint FileSize;
}
}

View file

@ -0,0 +1,62 @@
using System.Collections.Generic;
namespace RynthCore.Geometry.Dat;
/// <summary>
/// Small fixed-capacity least-recently-used map. Not thread-safe: callers hold
/// their own lock. A hit moves the entry to the front without allocating; only
/// an insert allocates (one list node), and the oldest entry is dropped when
/// the map is full.
/// </summary>
internal sealed class LruCache<TKey, TValue> where TKey : notnull
{
private readonly int _capacity;
private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> _map;
private readonly LinkedList<KeyValuePair<TKey, TValue>> _order = new();
public LruCache(int capacity)
{
_capacity = capacity < 1 ? 1 : capacity;
_map = new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(_capacity);
}
public int Count => _map.Count;
public bool TryGet(TKey key, out TValue value)
{
if (_map.TryGetValue(key, out var node))
{
if (node != _order.First)
{
_order.Remove(node);
_order.AddFirst(node);
}
value = node.Value.Value;
return true;
}
value = default!;
return false;
}
public void Set(TKey key, TValue value)
{
if (_map.TryGetValue(key, out var existing))
{
_order.Remove(existing);
_map.Remove(key);
}
else if (_map.Count >= _capacity)
{
var oldest = _order.Last!;
_order.RemoveLast();
_map.Remove(oldest.Value.Key);
}
_map[key] = _order.AddFirst(new KeyValuePair<TKey, TValue>(key, value));
}
public void Clear()
{
_map.Clear();
_order.Clear();
}
}

View file

@ -0,0 +1,110 @@
// ============================================================================
// RynthCore.Geometry - Models/LandblockInfo.cs
// The outdoor objects of a landblock, from its LandblockInfo record in the
// cell dat (0xXXYYFFFE): static objects (Stabs) and buildings, each a model
// id with a landblock-local frame, plus each building's portals (the indoor
// cells its doorways open into).
//
// Format as in ACE (LandblockInfo.Unpack, BuildInfo.Unpack, CBldPortal.Unpack):
// uint Id, uint NumCells, uint count + Stab[] (uint id, frame),
// ushort numBuildings, ushort packMask,
// BuildInfo[]: uint ModelId, frame, uint NumLeaves, uint count + CBldPortal[]
// (ushort flags, otherCell, otherPortal, numStabs, ushort[numStabs], align 4),
// (packMask & 1) restriction table (not read).
// A frame is origin x, y, z then rotation w, x, y, z.
//
// Written for RynthCore (MIT) on 2026-10-28.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Models;
/// <summary>A building placed on a landblock, and the cells its doorways open into.</summary>
public sealed class BuildingInfo
{
/// <summary>Its model: a GfxObj (0x01..) or a Setup (0x02..).</summary>
public uint ModelId;
/// <summary>Landblock-local.</summary>
public Vector3 Origin;
public Quaternion Rotation;
public uint NumLeaves;
/// <summary>Low words of the indoor cells behind the building's doorways.</summary>
public List<ushort> PortalCells = new();
}
/// <summary>A landblock's LandblockInfo (0xXXYYFFFE): its outdoor static objects and buildings.</summary>
public sealed class LandblockInfo
{
public uint Id;
public uint NumCells;
/// <summary>Static objects, landblock-local frames.</summary>
public List<Stab> Objects = new();
public List<BuildingInfo> Buildings = new();
/// <summary>The whole record (objects and buildings) was read.</summary>
public bool Complete;
/// <summary>
/// Reads landblock <paramref name="landblock"/>'s LandblockInfo (0xXXYY, or any cell id 0xXXYYnnnn of it);
/// null when the record is missing. A damaged record returns what parsed, with <see cref="Complete"/> false.
/// </summary>
public static LandblockInfo? Load(DatDatabase cellDat, uint landblock)
{
if (landblock > 0xFFFF) landblock >>= 16;
byte[]? data = cellDat.GetFileData((landblock << 16) | 0xFFFE);
return data == null ? null : Parse(data);
}
public static LandblockInfo Parse(byte[] data)
{
var info = new LandblockInfo();
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
try
{
info.Id = r.ReadUInt32();
info.NumCells = r.ReadUInt32();
uint numObjects = r.ReadUInt32();
for (uint i = 0; i < numObjects && i < 10000; i++)
{
var s = new Stab { Id = r.ReadUInt32() };
(s.Origin, s.Rotation) = ReadFrame(r);
info.Objects.Add(s);
}
ushort numBuildings = r.ReadUInt16();
r.ReadUInt16(); // pack mask
for (int b = 0; b < numBuildings; b++)
{
var bi = new BuildingInfo { ModelId = r.ReadUInt32() };
(bi.Origin, bi.Rotation) = ReadFrame(r);
bi.NumLeaves = r.ReadUInt32();
uint numPortals = r.ReadUInt32();
if (numPortals > 1000) throw new InvalidDataException("bad building portal count");
for (uint p = 0; p < numPortals; p++)
{
r.ReadUInt16(); // flags
bi.PortalCells.Add(r.ReadUInt16()); // other cell
r.ReadUInt16(); // other portal
ushort numStabs = r.ReadUInt16();
ms.Seek(numStabs * 2L, SeekOrigin.Current);
long a = (ms.Position + 3) & ~3L;
if (a > ms.Length) throw new EndOfStreamException();
ms.Position = a;
}
info.Buildings.Add(bi);
}
info.Complete = true;
}
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException) { }
return info;
}
private static (Vector3, Quaternion) ReadFrame(BinaryReader r)
{
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
return (o, new Quaternion(x, y, z, w));
}
}

View file

@ -0,0 +1,174 @@
// ============================================================================
// RynthCore.Geometry - Models/ModelReader.cs
// The solid shape of a model (a Setup 0x02.. or a GfxObj 0x01..) in its own
// frame: the physics polygons of its parts, its collision cylinders and
// spheres, and the Setup's own radius and height. Formats as in ACE
// (SetupModel.Unpack, GfxObj.Unpack); a model with no physics has no
// polygons. Shapes are cached per id; the reader is thread-safe.
//
// Moved from RynthSuite Tools/RynthNav.TownNet/Models.cs (3a8075a).
// Written for RynthCore (MIT).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Models;
/// <summary>A model's solid shape in model space. Treat as read-only once returned by <see cref="ModelReader.Get"/>.</summary>
public sealed class ModelShape
{
/// <summary>Physics polygons of every part, in model space (part frames and scales applied).</summary>
public List<Vector3[]> Polygons = new();
/// <summary>Collision cylinders: base centre (model space), radius, height.</summary>
public List<(Vector3 Origin, float Radius, float Height)> Cylinders = new();
/// <summary>Collision spheres: centre (model space), radius.</summary>
public List<(Vector3 Center, float Radius)> Spheres = new();
/// <summary>The Setup's own (selection) radius and height; 0 for a GfxObj, or when the hooks stopped the read.</summary>
public float Radius, Height;
/// <summary>The model's record was found and read.</summary>
public bool Parsed;
public bool IsEmpty => Polygons.Count == 0 && Cylinders.Count == 0 && Spheres.Count == 0;
/// <summary>The polygons placed in the world: scaled, rotated, then moved to <paramref name="origin"/>.</summary>
public IEnumerable<Vector3[]> Place(Vector3 origin, Quaternion rotation, float scale = 1f)
{
foreach (var poly in Polygons)
{
var p = new Vector3[poly.Length];
for (int i = 0; i < p.Length; i++) p[i] = Vector3.Transform(poly[i] * scale, rotation) + origin;
yield return p;
}
}
}
/// <summary>Reads <see cref="ModelShape"/>s from the portal dat, caching each id.</summary>
public sealed class ModelReader
{
private readonly DatDatabase _portal;
private readonly Dictionary<uint, ModelShape> _cache = new();
private readonly object _gate = new();
public ModelReader(DatDatabase portalDat) { _portal = portalDat; }
/// <summary>The player's model (a human Setup): its collision spheres give the walker's radius.</summary>
public const uint HumanSetup = 0x02000001;
/// <summary>The shape of a GfxObj (0x01..) or Setup (0x02..); an empty, unparsed shape for anything else.</summary>
public ModelShape Get(uint id)
{
lock (_gate)
{
if (_cache.TryGetValue(id, out var s)) return s;
}
var shape = new ModelShape();
try
{
if ((id >> 24) == 0x01) { shape.Parsed = ReadGfxObj(id, shape.Polygons, Matrix4x4.Identity); }
else if ((id >> 24) == 0x02) { shape.Parsed = ReadSetup(id, shape); }
}
catch (Exception) { shape.Parsed = false; }
lock (_gate)
{
if (_cache.TryGetValue(id, out var s)) return s; // another thread won the race
_cache[id] = shape;
return shape;
}
}
private bool ReadGfxObj(uint id, List<Vector3[]> into, Matrix4x4 m)
{
byte[]? data = _portal.GetFileData(id);
if (data == null) return false;
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
uint numSurfaces = ReadCompressed(r);
ms.Seek(numSurfaces * 4L, SeekOrigin.Current);
var verts = CellDat.ReadVertexArray(r, ms);
if (verts == null) return false;
if ((flags & 1) == 0) return true; // no physics: walk through it
uint numPhys = ReadCompressed(r);
foreach (var (_, ids) in CellDat.ReadPolygons(r, ms, numPhys))
{
var p = CellDat.Resolve(ids, verts);
if (p.Length >= 3) into.Add(p.Select(v => Vector3.Transform(v, m)).ToArray());
}
return true;
}
private bool ReadSetup(uint id, ModelShape s)
{
byte[]? data = _portal.GetFileData(id);
if (data == null) return false;
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
uint numParts = r.ReadUInt32();
if (numParts > 1000) return false;
var parts = new uint[numParts];
for (int i = 0; i < numParts; i++) parts[i] = r.ReadUInt32();
if ((flags & 1) != 0) ms.Seek(numParts * 4L, SeekOrigin.Current); // parents
var scale = Enumerable.Repeat(Vector3.One, (int)numParts).ToArray();
if ((flags & 2) != 0)
for (int i = 0; i < numParts; i++) scale[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
SkipLocations(r, ms); // holding locations
SkipLocations(r, ms); // connection points
int placements = r.ReadInt32();
Matrix4x4[]? frames = null;
bool hooksSeen = false;
for (int p = 0; p < placements && !hooksSeen; p++)
{
int key = r.ReadInt32();
var f = new Matrix4x4[numParts];
for (int i = 0; i < numParts; i++) f[i] = ReadFrame(r);
if (frames == null || key == 0) frames = f;
if (r.ReadUInt32() != 0) hooksSeen = true; // variable-size hooks: stop here
}
for (int i = 0; i < numParts; i++)
{
Matrix4x4 m = Matrix4x4.CreateScale(scale[i]) * (frames != null ? frames[i] : Matrix4x4.Identity);
if ((parts[i] >> 24) == 0x01) ReadGfxObj(parts[i], s.Polygons, m);
}
if (hooksSeen) return true;
uint numCyl = r.ReadUInt32();
for (uint i = 0; i < numCyl && i < 64; i++)
s.Cylinders.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle(), r.ReadSingle()));
uint numSph = r.ReadUInt32();
for (uint i = 0; i < numSph && i < 64; i++)
s.Spheres.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle()));
s.Height = r.ReadSingle();
s.Radius = r.ReadSingle();
return true;
}
private static Matrix4x4 ReadFrame(BinaryReader r)
{
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
var q = new Quaternion(x, y, z, w);
if (q.LengthSquared() < 1e-6f) q = Quaternion.Identity;
return Matrix4x4.CreateFromQuaternion(Quaternion.Normalize(q)) * Matrix4x4.CreateTranslation(o);
}
private static void SkipLocations(BinaryReader r, MemoryStream ms)
{
int n = r.ReadInt32();
if (n < 0 || n > 1000) throw new InvalidDataException("bad location table");
ms.Seek(n * 36L, SeekOrigin.Current); // key, part id, frame
}
private static uint ReadCompressed(BinaryReader r)
{
byte b0 = r.ReadByte();
if ((b0 & 0x80) == 0) return b0;
byte b1 = r.ReadByte();
if ((b0 & 0x40) == 0) return (uint)(((b0 & 0x7F) << 8) | b1);
ushort s = r.ReadUInt16();
return (uint)((((b0 & 0x3F) << 8 | b1) << 16) | s);
}
}

View file

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthCore.Geometry: the AC world's shape, read from the dats. Dat access, terrain
heights/normals, indoor cells (EnvCells, portals, floors), model physics polygons, and a
collision query for walking. Shared by RynthCore.Headless now; meant to replace the
copies in RynthSuite (Shared/RynthCore.TerrainData, RynthAi Raycasting, RynthNav tools).
Pure managed code, no host, no Windows APIs.
-->
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthCore.Geometry</RootNamespace>
<AssemblyName>RynthCore.Geometry</AssemblyName>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="GeometryTests" />
<InternalsVisibleTo Include="RynthCore.Headless" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,211 @@
// ============================================================================
// RynthCore.Geometry - Scenery/SceneryPlacer.cs
// The scenery (trees, rocks, bushes) of a landblock, placed as ACE's
// Landblock.get_land_scenes places it on the server: per terrain vertex the
// pseudo-random scene pick, each object's frequency and displacement, then
// the rules that drop one: a weenie object, outside the landblock, on a
// road (ACE OnRoad), in a 24 m land cell that holds a building, on a slope
// outside the object's MinSlope..MaxSlope, or poking out of the landblock
// (PhysicsObj.obj_within_block). Then the heading (slope-aligned or random),
// and the object's scale (ObjectDesc.ScaleObj).
//
// Logic from RynthSuite Tools/RynthNav.Baker/Scenery.cs (d4ae46a), on the
// region tables of Plugins/RynthCore.Plugin.RynthAi/Raycasting/ScatterSystem.cs
// (4b29610). Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Terrain;
namespace RynthCore.Geometry.Scenery;
/// <summary>
/// A piece of scenery placed in a landblock. <see cref="Position"/> is landblock-local (z on the terrain);
/// <see cref="Rotation"/> is the full placement rotation (from <see cref="Heading"/> when the object is
/// turned, else the Scene's base rotation); <see cref="Heading"/> is in AC degrees (0 = north, clockwise),
/// NaN when the object keeps its base rotation.
/// </summary>
public readonly record struct SceneryObject(uint ModelId, Vector3 Position, Quaternion Rotation, float Heading, float Scale);
/// <summary>Places a landblock's scenery. Thread-safe; nothing is cached per landblock (callers cache).</summary>
public sealed class SceneryPlacer
{
private readonly DatDatabase _cell;
private readonly DatDatabase _portal;
private readonly TerrainSampler _terrain;
private readonly ModelReader _models;
private readonly Lazy<SceneryTables> _tables;
private readonly ConcurrentDictionary<uint, ShapeInfo> _shapes = new();
public SceneryPlacer(DatDatabase cell, DatDatabase portal, TerrainSampler terrain, ModelReader models)
{
_cell = cell;
_portal = portal;
_terrain = terrain;
_models = models;
_tables = new Lazy<SceneryTables>(() => new SceneryTables(portal), LazyThreadSafetyMode.ExecutionAndPublication);
}
/// <summary>The region's scene tables (read on first use).</summary>
public SceneryTables Tables => _tables.Value;
/// <summary>
/// The scenery of landblock <paramref name="landblock"/> (0xXXYY or any 0xXXYYnnnn id); empty when the
/// landblock or the region tables are missing.
/// </summary>
public List<SceneryObject> Place(uint landblock)
{
uint lb = LandblockData.KeyOf(landblock);
var result = new List<SceneryObject>();
var tables = Tables;
var land = _terrain.LoadLandblock(lb);
if (!tables.Ready || land == null) return result;
var buildingCells = new HashSet<int>();
var info = LandblockInfo.Load(_cell, lb);
if (info != null)
foreach (var b in info.Buildings)
buildingCells.Add(Math.Clamp((int)(b.Origin.X / 24f), 0, 7) * 8 + Math.Clamp((int)(b.Origin.Y / 24f), 0, 7));
ushort[] terrain = land.TerrainWords;
uint blockX = ((lb >> 8) & 0xFF) * 8, blockY = (lb & 0xFF) * 8;
unchecked
{
for (uint i = 0; i < 81; i++)
{
int terrainType = (terrain[i] >> 2) & 0x1F;
int sceneType = terrain[i] >> 11;
if (terrainType >= tables.TerrainTypes.Count) continue;
var tt = tables.TerrainTypes[terrainType];
if (sceneType >= tt.Count) continue;
int sceneInfo = (int)tt[sceneType];
if (sceneInfo < 0 || sceneInfo >= tables.SceneTypes.Count) continue;
var scenes = tables.SceneTypes[sceneInfo];
if (scenes.Count == 0) continue;
uint cellX = i / 9, cellY = i % 9;
uint gx = cellX + blockX, gy = cellY + blockY;
uint cellMat = gy * (712977289u * gx + 1813693831u) - 1109124029u * gx + 2139937281u;
double offset = cellMat * 2.3283064e-10;
int sceneIdx = (int)(scenes.Count * offset);
if (sceneIdx >= scenes.Count || sceneIdx < 0) sceneIdx = 0;
var objs = tables.Scene(scenes[sceneIdx]);
uint cellXMat = 0u - 1109124029u * gx;
uint cellYMat = 1813693831u * gy;
uint cellMat2 = 1360117743u * gx * gy + 1888038839u;
for (uint j = 0; j < objs.Count; j++)
{
var obj = objs[(int)j];
double noise = (uint)(cellXMat + cellYMat - cellMat2 * (23399u + j)) * 2.3283064e-10;
if (!(noise < obj.Freq) || obj.WeenieObj != 0) continue;
var pos = Displace(obj, gx, gy, j);
float lx = cellX * 24f + pos.X, ly = cellY * 24f + pos.Y;
if (lx < 0 || ly < 0 || lx >= 192f || ly >= 192f || TerrainSampler.OnRoad(land, lx, ly)) continue;
int cx = Math.Min((int)(lx / 24f), 7), cy = Math.Min((int)(ly / 24f), 7);
if (buildingCells.Contains(cx * 8 + cy)) continue;
Vector3 n = TerrainSampler.GetNormal(land, lx, ly);
if (!(n.Z >= obj.MinSlope && n.Z <= obj.MaxSlope)) continue;
float z = TerrainSampler.GetTerrainZ(land, lx, ly);
float heading = float.NaN;
if (obj.Align != 0) heading = Heading(-n.X, -n.Y);
else if (obj.MaxRotation > 0f)
heading = (float)((uint)(1813693831u * gy - (j + 63127u) * (1360117743u * gy * gx + 1888038839u) - 1109124029u * gx)
* 2.3283064e-10 * obj.MaxRotation);
// AFrame.set_heading: heading 0 = north (+Y), clockwise: a rotation about Z by -heading.
Quaternion rot = float.IsNaN(heading)
? obj.BaseRotation
: Quaternion.CreateFromAxisAngle(Vector3.UnitZ, -heading * MathF.PI / 180f);
var origin = new Vector3(lx, ly, z);
if (!WithinBlock(origin, rot, Shape(obj.ObjId))) continue;
result.Add(new SceneryObject(obj.ObjId, origin, rot, heading, ScaleObj(obj, gx, gy, j)));
}
}
}
return result;
}
// ---- ACE ObjectDesc maths (uint arithmetic wraps, as in the client) -------------
private static Vector3 Displace(SceneObjectDesc obj, uint ix, uint iy, uint iq)
{
unchecked
{
float x = obj.DisplaceX <= 0 ? obj.BaseOrigin.X
: (float)((uint)(1813693831u * iy - (iq + 45773u) * (1360117743u * iy * ix + 1888038839u) - 1109124029u * ix) * 2.3283064e-10 * obj.DisplaceX + obj.BaseOrigin.X);
float y = obj.DisplaceY <= 0 ? obj.BaseOrigin.Y
: (float)((uint)(1813693831u * iy - (iq + 72719u) * (1360117743u * iy * ix + 1888038839u) - 1109124029u * ix) * 2.3283064e-10 * obj.DisplaceY + obj.BaseOrigin.Y);
float z = obj.BaseOrigin.Z;
double quadrant = (uint)(1813693831u * iy - ix * (1870387557u * iy + 1109124029u) - 402451965u) * 2.3283064e-10;
if (quadrant >= 0.75) return new Vector3(y, -x, z);
if (quadrant >= 0.5) return new Vector3(-x, -y, z);
if (quadrant >= 0.25) return new Vector3(-y, x, z);
return new Vector3(x, y, z);
}
}
private static float ScaleObj(SceneObjectDesc obj, uint x, uint y, uint k)
{
if (obj.MinScale == obj.MaxScale) return obj.MaxScale;
unchecked
{
double t = (uint)(1813693831u * y - (k + 32593u) * (1360117743u * y * x + 1888038839u) - 1109124029u * x) * 2.3283064e-10;
return (float)(Math.Pow(obj.MaxScale / obj.MinScale, t) * obj.MinScale);
}
}
/// <summary>Vector3.get_heading: degrees, 0 = +Y (north), clockwise.</summary>
private static float Heading(float x, float y)
{
float len = MathF.Sqrt(x * x + y * y);
if (len < 1e-6f) return 0;
return (450f - MathF.Atan2(y / len, x / len) * 180f / MathF.PI) % 360f;
}
// ---- obj_within_block ---------------------------------------------------------
/// <summary>What obj_within_block needs of a model: sorting sphere, physics BSP or not, cylinders, spheres.</summary>
private readonly record struct ShapeInfo(Vector3 Center, float Radius, bool Bsp, (Vector3 Low, float R)[] Cylinders, bool Spheres);
private ShapeInfo Shape(uint model) => _shapes.GetOrAdd(model, ReadShape);
private ShapeInfo ReadShape(uint model)
{
var none = Array.Empty<(Vector3, float)>();
var shape = _models.Get(model);
if ((model >> 24) == 0x01)
{
if (shape.Polygons.Count == 0) return new ShapeInfo(Vector3.Zero, 0, false, none, false);
Vector3 mn = new(float.MaxValue), mx = new(float.MinValue);
foreach (var p in shape.Polygons) foreach (var v in p) { mn = Vector3.Min(mn, v); mx = Vector3.Max(mx, v); }
return new ShapeInfo((mn + mx) / 2, (mx - mn).Length() / 2, true, none, false);
}
var b = SetupBounds.Read(_portal, model);
if (b == null) return new ShapeInfo(Vector3.Zero, 0, shape.Polygons.Count > 0, none, false);
return new ShapeInfo(b.SortCenter, b.SortRadius, shape.Polygons.Count > 0,
b.Cylinders.Select(c => (c.Origin, c.Radius)).ToArray(), b.Spheres.Count > 0);
}
/// <summary>PhysicsObj.obj_within_block (ACE), before scaling, as the server checks it.</summary>
private static bool WithinBlock(Vector3 origin, Quaternion rot, ShapeInfo s)
{
Vector3 G(Vector3 p) => Vector3.Transform(p, rot) + origin;
bool Inside(Vector3 c, float r) => c.X >= r && c.Y >= r && c.X < 192f - r && c.Y < 192f - r;
if (s.Bsp) return Inside(G(s.Center), s.Radius);
if (s.Cylinders.Length > 0)
{
foreach (var (low, r) in s.Cylinders)
if (!Inside(G(low), r)) return false;
return true;
}
if (s.Spheres) return Inside(G(s.Center), s.Radius);
return origin.X >= 0 && origin.Y >= 0 && origin.X < 192f && origin.Y < 192f;
}
}

View file

@ -0,0 +1,232 @@
// ============================================================================
// RynthCore.Geometry - Scenery/SceneryTables.cs
// The tables scenery placement reads from the portal dat: the region's
// scene types (each a list of Scene files 0x12..) and terrain types (each a
// list of scene-type indices), from RegionDesc 0x13000000, and the object
// descriptions (ObjectDesc) of each Scene file.
//
// RegionDesc layout as in ACE (RegionDesc.Unpack): Id, RegionNumber, Version,
// RegionName (PString), LandDefs (8 values + 256-float height table),
// GameTime, PartsMask, (0x10) SkyDesc, (0x01) SoundDesc, (0x02) SceneDesc,
// TerrainDesc, ... A PString is a ushort length + bytes, aligned to 4.
// If the walk through it fails a sanity check, the scene and terrain tables
// are found by scanning (as RynthSuite's ScatterSystem does).
//
// Logic from RynthSuite Plugins/RynthCore.Plugin.RynthAi/Raycasting/
// ScatterSystem.cs (4b29610: ParseRegionDesc, ParseSceneDesc, ParseTerrainDesc,
// ScanForTables) and Tools/RynthNav.Baker/Scenery.cs (d4ae46a: Scene).
// Written for RynthCore (MIT).
// ============================================================================
using System.Collections.Concurrent;
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Scenery;
/// <summary>One object of a Scene file (ACE ObjectDesc): what to place, where in the cell, how often, how big.</summary>
public sealed record SceneObjectDesc(
uint ObjId, Vector3 BaseOrigin, Quaternion BaseRotation, float Freq, float DisplaceX, float DisplaceY,
float MinScale, float MaxScale, float MaxRotation, float MinSlope, float MaxSlope, uint Align, uint Orient, uint WeenieObj);
/// <summary>The region's terrain -> scene-type -> Scene tables, and the Scene files' objects (cached, thread-safe).</summary>
public sealed class SceneryTables
{
public const uint RegionDescId = 0x13000000;
private readonly DatDatabase _portal;
private readonly ConcurrentDictionary<uint, IReadOnlyList<SceneObjectDesc>> _scenes = new();
/// <summary>Per terrain type (0..31): indices into <see cref="SceneTypes"/>.</summary>
public IReadOnlyList<IReadOnlyList<uint>> TerrainTypes { get; private set; } = Array.Empty<IReadOnlyList<uint>>();
/// <summary>Per scene type: its Scene file ids (0x12..).</summary>
public IReadOnlyList<IReadOnlyList<uint>> SceneTypes { get; private set; } = Array.Empty<IReadOnlyList<uint>>();
/// <summary>Both tables were read.</summary>
public bool Ready => TerrainTypes.Count > 0 && SceneTypes.Count > 0;
/// <summary>The tables came from the scan fallback, not the structured walk (diagnostics).</summary>
public bool Scanned { get; private set; }
public SceneryTables(DatDatabase portal)
{
_portal = portal;
byte[]? data = portal.GetFileData(RegionDescId);
if (data == null) return;
if (!Walk(data)) Scanned = Scan(data);
}
/// <summary>The objects of Scene file <paramref name="sceneId"/> (empty when missing).</summary>
public IReadOnlyList<SceneObjectDesc> Scene(uint sceneId) => _scenes.GetOrAdd(sceneId, ReadScene);
private IReadOnlyList<SceneObjectDesc> ReadScene(uint sceneId)
{
var list = new List<SceneObjectDesc>();
byte[]? data = _portal.GetFileData(sceneId);
if (data == null || data.Length < 8) return list;
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint n = r.ReadUInt32();
for (uint i = 0; i < n && ms.Position + 76 <= ms.Length; i++)
{
uint obj = r.ReadUInt32();
var o = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
float w = r.ReadSingle(), x = r.ReadSingle(), y = r.ReadSingle(), z = r.ReadSingle();
list.Add(new SceneObjectDesc(obj, o, new Quaternion(x, y, z, w),
r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadSingle(),
r.ReadSingle(), r.ReadSingle(), r.ReadSingle(), r.ReadUInt32(), r.ReadUInt32(), r.ReadUInt32()));
}
return list;
}
// ---- structured walk -----------------------------------------------------
private bool Walk(byte[] data)
{
try
{
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadUInt32(); r.ReadUInt32(); // id, region number, version
PString(r, ms); // region name
ms.Seek(8 * 4 + 256 * 4, SeekOrigin.Current); // LandDefs
// GameTime
r.ReadDouble(); r.ReadUInt32(); r.ReadSingle(); r.ReadUInt32();
PString(r, ms);
uint n = Count(r, 100);
for (uint i = 0; i < n; i++) { r.ReadSingle(); r.ReadUInt32(); PString(r, ms); }
n = Count(r, 100);
for (uint i = 0; i < n; i++) PString(r, ms);
n = Count(r, 100);
for (uint i = 0; i < n; i++) { r.ReadUInt32(); PString(r, ms); }
uint parts = r.ReadUInt32();
if ((parts & 0x10) != 0) // SkyDesc
{
r.ReadDouble(); r.ReadDouble();
uint groups = Count(r, 1000);
for (uint g = 0; g < groups; g++)
{
r.ReadSingle();
PString(r, ms);
ms.Seek(Count(r, 10000) * 36L, SeekOrigin.Current); // SkyObjects
uint times = Count(r, 10000);
for (uint t = 0; t < times; t++)
{
ms.Seek(44, SeekOrigin.Current);
ms.Seek(Count(r, 10000) * 24L, SeekOrigin.Current); // SkyObjectReplace
}
}
}
if ((parts & 0x01) != 0) // SoundDesc
{
uint stbs = Count(r, 10000);
for (uint s = 0; s < stbs; s++)
{
r.ReadUInt32();
ms.Seek(Count(r, 10000) * 20L, SeekOrigin.Current);
}
}
if ((parts & 0x02) == 0) return false;
var scenes = ReadSceneTypes(r);
if (scenes == null) return false;
var terrain = ReadTerrainTypes(r, ms);
if (terrain == null) return false;
SceneTypes = scenes;
TerrainTypes = terrain;
return true;
}
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException)
{
return false;
}
}
private static List<IReadOnlyList<uint>>? ReadSceneTypes(BinaryReader r)
{
uint n = Count(r, 1000);
if (n == 0) return null;
var list = new List<IReadOnlyList<uint>>();
for (uint i = 0; i < n; i++)
{
r.ReadUInt32(); // STB index
uint k = Count(r, 1000);
var ids = new uint[k];
for (uint s = 0; s < k; s++)
{
ids[s] = r.ReadUInt32();
if ((ids[s] >> 24) != 0x12) return null;
}
list.Add(ids);
}
return list;
}
private static List<IReadOnlyList<uint>>? ReadTerrainTypes(BinaryReader r, MemoryStream ms)
{
uint n = Count(r, 100);
if (n < 5) return null;
var list = new List<IReadOnlyList<uint>>();
for (uint i = 0; i < n; i++)
{
ushort len = r.ReadUInt16();
if (len > 200) return null;
byte[] name = r.ReadBytes(len);
if (name.Any(b => b < 32 || b > 126)) return null;
Align(ms);
r.ReadUInt32(); // terrain colour
uint k = Count(r, 200);
var idx = new uint[k];
for (uint s = 0; s < k; s++) idx[s] = r.ReadUInt32();
list.Add(idx);
}
return list;
}
// ---- scan fallback ----------------------------------------------------------
private bool Scan(byte[] data)
{
for (int pos = 100; pos + 8 < data.Length; pos += 4)
{
uint count = BitConverter.ToUInt32(data, pos);
if (count < 20 || count > 200) continue;
try
{
var ms = new MemoryStream(data) { Position = pos };
using var r = new BinaryReader(ms);
var scenes = ReadSceneTypes(r);
if (scenes == null || scenes.Sum(s => s.Count) < 10) continue;
var terrain = ReadTerrainTypes(r, ms);
if (terrain == null) continue;
SceneTypes = scenes;
TerrainTypes = terrain;
return true;
}
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException) { }
}
return false;
}
// ---- helpers ------------------------------------------------------------------
private static uint Count(BinaryReader r, uint max)
{
uint n = r.ReadUInt32();
if (n > max) throw new InvalidDataException("bad list count");
return n;
}
private static void PString(BinaryReader r, MemoryStream ms)
{
ushort len = r.ReadUInt16();
if (ms.Position + len > ms.Length) throw new EndOfStreamException();
ms.Seek(len, SeekOrigin.Current);
Align(ms);
}
private static void Align(MemoryStream ms)
{
long a = (ms.Position + 3) & ~3L;
if (a > ms.Length) throw new EndOfStreamException();
ms.Position = a;
}
}

View file

@ -0,0 +1,152 @@
// ============================================================================
// RynthCore.Geometry - Scenery/SetupBounds.cs
// The tail of a Setup (0x02..) record: its collision cylinders and spheres,
// height and radius, and its sorting sphere (the sphere obj_within_block
// checks). ModelReader stops reading a Setup whose placement frames carry
// animation hooks (variable size); this reader finds the tail from the end
// of the record instead, so those Setups keep their cylinders.
//
// Setup layout as in ACE (SetupModel.Unpack):
// Id, Flags, NumParts, Parts[], (Flags&1) Parents[], (Flags&2) Scales[],
// HoldingLocations, ConnectionPoints (count + 36-byte entries),
// PlacementFrames (count + key, numParts frames, numHooks, hooks[]),
// CylSpheres (count + 20 bytes), Spheres (count + 16 bytes),
// Height, Radius, StepUpHeight, StepDownHeight,
// SortingSphere (16), SelectionSphere (16),
// Lights (count + key 4 + LightInfo 44), 5 default ids (20).
//
// Written for RynthCore (MIT) on 2026-10-28; the tail scan follows RynthSuite
// Plugins/RynthCore.Plugin.RynthAi/Raycasting/LandblockStructs.cs SetupInfo
// (4b29610).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Scenery;
/// <summary>A Setup's collision cylinders and spheres, height, radius and sorting sphere, in model space.</summary>
internal sealed class SetupBounds
{
public readonly List<(Vector3 Origin, float Radius, float Height)> Cylinders = new();
public readonly List<(Vector3 Center, float Radius)> Spheres = new();
public float Height, Radius, StepUp, StepDown;
public Vector3 SortCenter;
public float SortRadius;
/// <summary>Found from the end of the record (the placement frames had animation hooks).</summary>
public bool FromTail;
private const int LightBytes = 4 + 44;
/// <summary>The bounds of Setup <paramref name="id"/>, or null when the record is missing or does not parse.</summary>
public static SetupBounds? Read(DatDatabase portal, uint id)
{
if ((id >> 24) != 0x02) return null;
byte[]? data = portal.GetFileData(id);
if (data == null || data.Length < 16) return null;
try { return Forward(data) ?? FromEnd(data); }
catch (Exception e) when (e is EndOfStreamException or InvalidDataException or IOException or ArgumentException)
{
return FromEnd(data);
}
}
/// <summary>Reads a Setup record front to back (null when it has animation hooks), or from its end (tests compare the two).</summary>
internal static SetupBounds? Parse(byte[] data, bool fromEnd) => fromEnd ? FromEnd(data) : Forward(data);
// Reads front to back; null when the placement frames have hooks (variable size, not skipped).
private static SetupBounds? Forward(byte[] data)
{
var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
uint flags = r.ReadUInt32();
uint numParts = r.ReadUInt32();
if (numParts > 1000) throw new InvalidDataException("bad part count");
ms.Seek(numParts * 4L, SeekOrigin.Current);
if ((flags & 1) != 0) ms.Seek(numParts * 4L, SeekOrigin.Current);
if ((flags & 2) != 0) ms.Seek(numParts * 12L, SeekOrigin.Current);
for (int t = 0; t < 2; t++)
{
int n = r.ReadInt32();
if (n < 0 || n > 1000) throw new InvalidDataException("bad location table");
ms.Seek(n * 36L, SeekOrigin.Current);
}
int placements = r.ReadInt32();
if (placements < 0 || placements > 1000) throw new InvalidDataException("bad placement count");
for (int p = 0; p < placements; p++)
{
r.ReadInt32();
ms.Seek(numParts * 28L, SeekOrigin.Current);
if (r.ReadUInt32() != 0) return null;
}
var b = new SetupBounds();
uint numCyl = r.ReadUInt32();
if (numCyl > 256) throw new InvalidDataException("bad cylinder count");
for (uint i = 0; i < numCyl; i++)
b.Cylinders.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle(), r.ReadSingle()));
uint numSph = r.ReadUInt32();
if (numSph > 256) throw new InvalidDataException("bad sphere count");
for (uint i = 0; i < numSph; i++)
b.Spheres.Add((new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle()), r.ReadSingle()));
b.Height = r.ReadSingle(); b.Radius = r.ReadSingle(); b.StepUp = r.ReadSingle(); b.StepDown = r.ReadSingle();
b.SortCenter = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
b.SortRadius = r.ReadSingle();
return b;
}
// The record ends: sorting sphere, selection sphere, light count + lights, 5 ids. Find the light count
// that fits, then walk back over Height..StepDown, the sphere list and the cylinder list.
private static SetupBounds? FromEnd(byte[] data)
{
for (int lights = 0; lights <= 16; lights++)
{
int countAt = data.Length - 20 - lights * LightBytes - 4;
if (countAt < 16 + 32 + 16 + 8) break;
if (BitConverter.ToUInt32(data, countAt) != (uint)lights) continue;
int sortAt = countAt - 32, heightAt = sortAt - 16;
float sortR = BitConverter.ToSingle(data, sortAt + 12);
if (!float.IsFinite(sortR) || sortR < 0 || sortR > 10000) continue;
for (int k = 0; k <= 64; k++)
{
int sphCountAt = heightAt - 16 * k - 4;
if (sphCountAt < 16) break;
if (BitConverter.ToUInt32(data, sphCountAt) != (uint)k) continue;
for (int m = 0; m <= 64; m++)
{
int cylCountAt = sphCountAt - 20 * m - 4;
if (cylCountAt < 16) break;
if (BitConverter.ToUInt32(data, cylCountAt) != (uint)m) continue;
var b = new SetupBounds { FromTail = true };
for (int i = 0; i < m; i++)
{
int o = cylCountAt + 4 + 20 * i;
b.Cylinders.Add((V(data, o), F(data, o + 12), F(data, o + 16)));
}
for (int i = 0; i < k; i++)
{
int o = sphCountAt + 4 + 16 * i;
b.Spheres.Add((V(data, o), F(data, o + 12)));
}
b.Height = F(data, heightAt); b.Radius = F(data, heightAt + 4);
b.StepUp = F(data, heightAt + 8); b.StepDown = F(data, heightAt + 12);
b.SortCenter = V(data, sortAt); b.SortRadius = sortR;
if (Plausible(b)) return b;
}
}
}
return null;
}
private static bool Plausible(SetupBounds b)
{
static bool Ok(float f) => float.IsFinite(f) && MathF.Abs(f) < 10000;
if (!Ok(b.Height) || !Ok(b.Radius) || b.Height < 0 || b.Radius < 0) return false;
foreach (var c in b.Cylinders) if (!Ok(c.Origin.Length()) || !Ok(c.Radius) || !Ok(c.Height) || c.Radius < 0 || c.Height < 0) return false;
foreach (var s in b.Spheres) if (!Ok(s.Center.Length()) || !Ok(s.Radius) || s.Radius < 0) return false;
return Ok(b.SortCenter.Length());
}
private static float F(byte[] d, int o) => BitConverter.ToSingle(d, o);
private static Vector3 V(byte[] d, int o) => new(F(d, o), F(d, o + 4), F(d, o + 8));
}

View file

@ -0,0 +1,153 @@
// ============================================================================
// RynthCore.Geometry - Terrain/LandblockData.cs
// One outdoor landblock's terrain as the cell dat stores it: the 9x9 vertex
// grid of terrain words (road bits, terrain type, scene type) and height
// indices, plus the heights decoded through the region's land-height table.
// Pure data: the triangle math (split-aware Z, normals, raycast, roads) lives
// in TerrainSampler so there is exactly one implementation of it.
//
// Moved from RynthSuite Shared/RynthCore.TerrainData/LandblockData.cs (72b9e26).
// Changes on the move: namespace, nullable annotations, System.Numerics; the
// old GetTerrainZLocal / RaycastTerrainLocal, which always split cells SW->NE
// (wrong on about half the cells), were dropped in favour of the split-aware
// TerrainSampler.GetTerrainZ / RaycastTerrain.
// ============================================================================
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Terrain;
/// <summary>
/// Parsed CellLandblock (cell dat file 0xXXYYFFFF): the terrain heightmap and terrain words of
/// one 192 x 192 m landblock.
///
/// File layout:
/// uint Id (0xXXYYFFFF)
/// uint HasObjects (nonzero if the matching 0xXXYYFFFE LandblockInfo exists)
/// ushort Terrain[81] 9x9 grid: roadBits (bits 0-1) | terrainType &lt;&lt; 2 (bits 2-6) | sceneType &lt;&lt; 11
/// byte Height[81] 9x9 grid, indices into RegionDesc's LandHeightTable
///
/// Vertex indexing: idx = ix * 9 + iy, ix = 0..8 west to east, iy = 0..8 south to north.
/// Vertex (ix, iy) sits at landblock-local (ix * 24, iy * 24). Heights are absolute world Z.
/// </summary>
public sealed class LandblockData
{
public const int VertexDim = 9;
public const int BlockSide = 8;
public const float CellLength = 24.0f;
public const float BlockLength = 192.0f;
/// <summary>0xXXYY landblock key (no cell word).</summary>
public uint LandblockKey { get; }
/// <summary>The landblock has a 0xXXYYFFFE LandblockInfo (buildings / static objects).</summary>
public bool HasObjects { get; }
/// <summary>81 terrain words, idx = ix * 9 + iy.</summary>
public ushort[] TerrainWords { get; }
/// <summary>81 raw height indices (into the land-height table), idx = ix * 9 + iy.</summary>
public byte[] HeightIndices { get; }
/// <summary>Decoded world Z of every vertex, HeightsZ[ix, iy].</summary>
public float[,] HeightsZ { get; }
/// <summary>World X of vertex (0, 0), the SW corner of the landblock (landblock X * 192).</summary>
public float WorldOriginX => ((LandblockKey >> 8) & 0xFF) * BlockLength;
/// <summary>World Y of vertex (0, 0), the SW corner of the landblock (landblock Y * 192).</summary>
public float WorldOriginY => (LandblockKey & 0xFF) * BlockLength;
private LandblockData(uint key, bool hasObjects, ushort[] terrain, byte[] heights, float[,] heightsZ)
{
LandblockKey = key;
HasObjects = hasObjects;
TerrainWords = terrain;
HeightIndices = heights;
HeightsZ = heightsZ;
}
/// <summary>
/// The 0xXXYY key of any landblock or cell id: 0xXXYYnnnn gives 0xXXYY, a value that already
/// fits in 16 bits is taken as the key itself. (So cell ids of landblock 0x0000, open ocean
/// at the world corner, can't be passed this way; pass the key 0 instead.)
/// </summary>
public static uint KeyOf(uint landblockOrCellId) => landblockOrCellId > 0xFFFF ? landblockOrCellId >> 16 : landblockOrCellId;
/// <summary>
/// Loads and parses the 0xXXYYFFFF CellLandblock. <paramref name="landblock"/> is the 0xXXYY key
/// or any 0xXXYYnnnn id (see <see cref="KeyOf"/>). Returns null if the file is missing or short.
/// </summary>
public static LandblockData? Load(DatDatabase cellDat, uint landblock, float[] landHeightTable)
{
ArgumentNullException.ThrowIfNull(cellDat);
ArgumentNullException.ThrowIfNull(landHeightTable);
uint key = KeyOf(landblock);
byte[]? data = cellDat.GetFileData((key << 16) | 0xFFFF);
return data == null ? null : Parse(key, data, landHeightTable);
}
/// <summary>
/// Parses a CellLandblock record (the bytes of 0xXXYYFFFF). Returns null if it's too short.
/// </summary>
public static LandblockData? Parse(uint landblockKey, ReadOnlySpan<byte> data, float[] landHeightTable)
{
// 4 (Id) + 4 (HasObjects) + 81*2 (terrain) + 81 (heights) = 251
const int Needed = 4 + 4 + 81 * 2 + 81;
if (data.Length < Needed) return null;
bool hasObjects = BitConverter.ToUInt32(data.Slice(4, 4)) != 0;
var terrain = new ushort[81];
for (int i = 0; i < 81; i++)
terrain[i] = BitConverter.ToUInt16(data.Slice(8 + i * 2, 2));
var heights = data.Slice(8 + 81 * 2, 81).ToArray();
var heightsZ = new float[VertexDim, VertexDim];
for (int ix = 0; ix < VertexDim; ix++)
for (int iy = 0; iy < VertexDim; iy++)
{
byte h = heights[ix * VertexDim + iy];
heightsZ[ix, iy] = h < landHeightTable.Length ? landHeightTable[h] : 0f;
}
return new LandblockData(KeyOf(landblockKey), hasObjects, terrain, heights, heightsZ);
}
/// <summary>Vertex Z at grid coords (0..8, 0..8); 0 outside the grid.</summary>
public float GetVertexZ(int ix, int iy)
{
if ((uint)ix > BlockSide || (uint)iy > BlockSide) return 0f;
return HeightsZ[ix, iy];
}
/// <summary>Terrain word at grid coords (0..8, 0..8); 0 outside the grid.</summary>
public ushort GetTerrainWord(int ix, int iy)
{
if ((uint)ix > BlockSide || (uint)iy > BlockSide) return 0;
return TerrainWords[ix * VertexDim + iy];
}
/// <summary>
/// Z of the nearest grid vertex for a landblock-local position; coordinates outside the block
/// are clamped to the edge. (A coarse lookup; TerrainSampler.GetTerrainZ is the exact one.)
/// </summary>
public float GetNearestVertexHeightLocal(float lx, float ly)
{
int ix = Math.Clamp((int)MathF.Round(lx / CellLength), 0, BlockSide);
int iy = Math.Clamp((int)MathF.Round(ly / CellLength), 0, BlockSide);
return HeightsZ[ix, iy];
}
/// <summary>Min and max vertex Z across the landblock.</summary>
public void GetHeightRange(out float min, out float max)
{
min = float.PositiveInfinity;
max = float.NegativeInfinity;
foreach (float z in HeightsZ)
{
if (z < min) min = z;
if (z > max) max = z;
}
}
}

View file

@ -0,0 +1,569 @@
// ============================================================================
// RynthCore.Geometry - Terrain/TerrainSampler.cs
// Outdoor ground queries on AC's landscape mesh: terrain Z, triangle normal,
// walkability, road test, terrain type and a ray-vs-terrain cast, all on the
// triangle the game actually uses for each 24 m cell (the per-cell diagonal
// split, ACE LandblockStruct.ConstructPolygons / FSplitNESW). Reads the land-
// height table from RegionDesc 0x13000000 in the portal dat and keeps parsed
// landblocks (cell dat 0xXXYYFFFF) in a small thread-safe LRU.
//
// Moved from RynthSuite Shared/RynthCore.TerrainData/TerrainSampler.cs (8777fac),
// with TerrainNormal and OnRoad from Tools/RynthNav.Baker/Scenery.cs (d4ae46a).
// Changes on the move: built on caller-supplied (shareable) DatDatabase
// instances instead of opening its own, System.Numerics.Vector3, the split-
// aware raycast (the old LandblockData.RaycastTerrainLocal always split SW->NE)
// now crosses into neighbouring landblocks.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Dat;
namespace RynthCore.Geometry.Terrain;
/// <summary>
/// Terrain queries for AC's outdoor landscape.
///
/// Coordinates: a landblock is named by its 0xXXYY key, or by any 0xXXYYnnnn landblock/cell id
/// (the high word is used, see <see cref="LandblockData.KeyOf"/>). Positions are landblock-local:
/// X east and Y north in 0..192 from the landblock's SW corner, Z absolute (the same Z as
/// server positions). Each landblock is 8 x 8 cells of 24 m; each cell is two triangles, cut
/// along the diagonal <see cref="SwToNeCut"/> picks.
///
/// Thread-safety: all members can be called from any thread. The landblock cache is behind a
/// lock; the DatDatabase instances are thread-safe themselves.
/// </summary>
public sealed class TerrainSampler : IDisposable
{
/// <summary>
/// AC's walkable threshold (ACE PhysicsGlobals.FloorZ): a surface whose unit normal has Z
/// below this is too steep to stand on (is_valid_walkable). About 48.4 degrees.
/// </summary>
public const float FloorZ = 0.66417414618662751f;
/// <summary>RegionDesc record in the portal dat that holds the land-height table.</summary>
public const uint RegionDescId = 0x13000000;
private const float Cell = LandblockData.CellLength;
private const float Block = LandblockData.BlockLength;
private readonly DatDatabase _portal;
private readonly DatDatabase _cell;
private readonly bool _ownsDats;
private readonly float[] _landHeightTable;
// Parsed landblocks (null = not in the dat), least recently used out first. A load runs
// outside the lock; two threads missing the same key both parse it and the later Set wins,
// which is harmless.
private readonly object _cacheGate = new();
private readonly LruCache<uint, LandblockData?> _cache;
/// <summary>
/// A sampler over already-open dats, which stay the caller's (Dispose doesn't close them).
/// Throws InvalidDataException if RegionDesc's land-height table can't be read.
/// </summary>
public TerrainSampler(DatDatabase portal, DatDatabase cell, int cacheCapacity = 64)
: this(portal, cell, cacheCapacity, ownsDats: false) { }
private TerrainSampler(DatDatabase portal, DatDatabase cell, int cacheCapacity, bool ownsDats)
{
ArgumentNullException.ThrowIfNull(portal);
ArgumentNullException.ThrowIfNull(cell);
_portal = portal;
_cell = cell;
_ownsDats = ownsDats;
_landHeightTable = ReadLandHeightTable(portal)
?? throw new InvalidDataException($"RegionDesc 0x{RegionDescId:X8} land-height table not readable from {portal.FilePath}");
// The default holds a 7x7-landblock window (an overlay of radius 3 landblocks) plus headroom.
_cache = new LruCache<uint, LandblockData?>(cacheCapacity);
}
/// <summary>
/// Opens client_portal.dat (or portal.dat) and client_cell_1.dat (or cell.dat) in
/// <paramref name="acFolder"/> read-only; the sampler owns them and closes them on Dispose.
/// Throws FileNotFoundException / InvalidDataException with the reason on failure.
/// </summary>
public static TerrainSampler Open(string acFolder, int cacheCapacity = 64)
{
string portalPath = FindDat(acFolder, "client_portal.dat", "portal.dat")
?? throw new FileNotFoundException($"no client_portal.dat / portal.dat in {acFolder}");
string cellPath = FindDat(acFolder, "client_cell_1.dat", "cell.dat")
?? throw new FileNotFoundException($"no client_cell_1.dat / cell.dat in {acFolder}");
var portal = new DatDatabase();
var cell = new DatDatabase();
try
{
if (!portal.Open(portalPath)) throw new InvalidDataException($"can't open {portalPath}: {Last(portal)}");
if (!cell.Open(cellPath)) throw new InvalidDataException($"can't open {cellPath}: {Last(cell)}");
return new TerrainSampler(portal, cell, cacheCapacity, ownsDats: true);
}
catch
{
portal.Dispose();
cell.Dispose();
throw;
}
static string Last(DatDatabase d) => d.DiagLog.Count > 0 ? d.DiagLog[^1] : "unknown error";
}
/// <summary>The 256-entry land-height table (height index to world Z).</summary>
public IReadOnlyList<float> LandHeightTable => _landHeightTable;
public DatDatabase PortalDat => _portal;
public DatDatabase CellDat => _cell;
/// <summary>Parsed landblock (heights + terrain words), cached. Null if the dat doesn't have it.</summary>
public LandblockData? LoadLandblock(uint landblock)
{
uint key = LandblockData.KeyOf(landblock);
lock (_cacheGate)
{
if (_cache.TryGet(key, out var cached)) return cached;
}
LandblockData? data = LandblockData.Load(_cell, key, _landHeightTable);
lock (_cacheGate) _cache.Set(key, data);
return data;
}
// ------------------------------------------------------------------ height
/// <summary>Terrain Z at landblock-local (lx, ly), clamped to the block. NaN if the landblock isn't in the dat.</summary>
public float GetTerrainZ(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? float.NaN : GetTerrainZ(lb, localX, localY);
}
/// <summary>
/// Terrain Z at landblock-local (lx, ly) in [0, 192], on the triangle AC uses for that cell
/// (<see cref="SwToNeCut"/>). Coordinates are clamped to the block.
/// </summary>
public static float GetTerrainZ(LandblockData lb, float localX, float localY)
=> GetTerrainZ(lb, localX, localY, invertSplit: false);
/// <summary>GetTerrainZ with the split polarity optionally flipped (the tests use it to check the polarity).</summary>
internal static float GetTerrainZ(LandblockData lb, float localX, float localY, bool invertSplit)
{
Locate(localX, localY, out int cx, out int cy, out float u, out float v);
float h00 = lb.GetVertexZ(cx, cy); // SW
float h10 = lb.GetVertexZ(cx + 1, cy); // SE
float h01 = lb.GetVertexZ(cx, cy + 1); // NW
float h11 = lb.GetVertexZ(cx + 1, cy + 1); // NE
if (SwToNeCut(lb.LandblockKey, cx, cy) != invertSplit)
{
// SE half (SW,SE,NE) when v <= u, NW half (SW,NE,NW) otherwise.
return v <= u
? h00 + u * (h10 - h00) + v * (h11 - h10)
: h00 + v * (h01 - h00) + u * (h11 - h01);
}
// SW half (SW,SE,NW) when u + v <= 1, NE half (SE,NE,NW) otherwise.
return u + v <= 1f
? h00 + u * (h10 - h00) + v * (h01 - h00)
: h11 + (1f - u) * (h01 - h11) + (1f - v) * (h10 - h11);
}
// ------------------------------------------------------------------ normal / slope
/// <summary>Unit upward (Z &gt; 0) normal of the terrain triangle under (lx, ly). Zero vector if the landblock isn't in the dat.</summary>
public Vector3 GetNormal(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? Vector3.Zero : GetNormal(lb, localX, localY);
}
/// <summary>
/// Unit upward normal of the terrain triangle under landblock-local (lx, ly), on AC's per-cell
/// split (Scenery.TerrainNormal in the RynthNav baker). Coordinates are clamped to the block.
/// </summary>
public static Vector3 GetNormal(LandblockData lb, float localX, float localY)
{
Locate(localX, localY, out int cx, out int cy, out float u, out float v);
bool swToNe = SwToNeCut(lb.LandblockKey, cx, cy);
int tri = swToNe ? (v <= u ? 0 : 1) : (u + v <= 1f ? 0 : 1);
CellTriangle(lb, cx, cy, swToNe, tri, out var a, out var b, out var c);
return UpNormal(a, b, c);
}
/// <summary>True if a surface with this unit normal is flat enough to stand on (normal.Z &gt;= <paramref name="floorZ"/>).</summary>
public static bool IsWalkable(Vector3 normal, float floorZ = FloorZ) => normal.Z >= floorZ;
/// <summary>
/// Walkability of the two triangles of cell (cx, cy), 0..7. Which halves tri1/tri2 are depends
/// on the split: swToNeCut true gives tri1 = SE half (SW,SE,NE), tri2 = NW half (SW,NE,NW);
/// false gives tri1 = SW half (SW,SE,NW), tri2 = NE half (SE,NE,NW).
/// </summary>
public static void GetTrianglePassability(LandblockData lb, int cx, int cy, bool swToNeCut,
out bool tri1Passable, out bool tri2Passable, float floorZ = FloorZ)
{
CellTriangle(lb, cx, cy, swToNeCut, 0, out var a, out var b, out var c);
tri1Passable = UpNormal(a, b, c).Z >= floorZ;
CellTriangle(lb, cx, cy, swToNeCut, 1, out a, out b, out c);
tri2Passable = UpNormal(a, b, c).Z >= floorZ;
}
/// <summary>GetTrianglePassability on the cell's own split.</summary>
public static void GetTrianglePassability(LandblockData lb, int cx, int cy,
out bool tri1Passable, out bool tri2Passable, float floorZ = FloorZ)
=> GetTrianglePassability(lb, cx, cy, SwToNeCut(lb.LandblockKey, cx, cy),
out tri1Passable, out tri2Passable, floorZ);
// ------------------------------------------------------------------ split
/// <summary>
/// AC's per-cell diagonal split (ACE LandblockStruct.ConstructPolygons / FSplitNESW). True: the
/// cell is cut SW to NE (triangles SW-SE-NE and SW-NE-NW); false: cut SE to NW (triangles
/// SW-SE-NW and SE-NE-NW). Roughly half the cells each way.
///
/// The PRNG inputs are the cell's vertex-grid coordinates (landblock index * 8 + cell index),
/// matching ACE's blockid_to_lcoord (LandblockShift = 3), not raw landblock indices.
/// <paramref name="landblock"/> is the 0xXXYY key or any 0xXXYYnnnn id.
/// </summary>
public static bool SwToNeCut(uint landblock, int cellX, int cellY)
{
uint key = LandblockData.KeyOf(landblock);
int lbX = (int)((key >> 8) & 0xFF);
int lbY = (int)(key & 0xFF);
int vertexX = (lbX << 3) + cellX;
int vertexY = (lbY << 3) + cellY;
unchecked
{
uint magicA = (uint)vertexX * 214614067u + 1813693831u;
uint magicB = (uint)vertexX * 1109124029u;
uint splitDir = (uint)vertexY * magicA - magicB - 1369149221u;
return (splitDir & 0x80000000u) != 0;
}
}
// ------------------------------------------------------------------ roads / terrain type
/// <summary>True if (lx, ly) is on a road (ACE Landblock.OnRoad). False if the landblock isn't in the dat.</summary>
public bool OnRoad(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb != null && OnRoad(lb, localX, localY);
}
/// <summary>
/// ACE Landblock.OnRoad: from the road bits of the four corners of the 24 m cell under
/// (lx, ly), with a 5 m road width. Used by the server to keep scenery off roads.
/// </summary>
public static bool OnRoad(LandblockData lb, float localX, float localY)
{
const float rMin = 5f, rMax = Cell - rMin;
int x = (int)(localX / Cell), y = (int)(localY / Cell);
uint r0 = RoadBits(lb, x, y), r1 = RoadBits(lb, x, y + 1), r2 = RoadBits(lb, x + 1, y), r3 = RoadBits(lb, x + 1, y + 1);
if (r0 == 0 && r1 == 0 && r2 == 0 && r3 == 0) return false;
float dx = localX - x * Cell, dy = localY - y * Cell;
if (r0 > 0)
{
if (r1 > 0)
{
if (r2 > 0) return r3 > 0 || dx < rMin || dy < rMin;
return r3 > 0 ? (dx < rMin || dy > rMax) : dx < rMin;
}
if (r2 > 0) return r3 > 0 ? (dx > rMax || dy < rMin) : dy < rMin;
return r3 > 0 ? MathF.Abs(dx - dy) < rMin : dx + dy < rMin;
}
if (r1 > 0)
{
if (r2 > 0) return r3 > 0 ? (dx > rMax || dy > rMax) : MathF.Abs(dx + dy - Cell) < rMin;
return r3 > 0 ? dy > rMax : Cell + dx - dy < rMin;
}
if (r2 > 0) return r3 > 0 ? dx > rMax : Cell - dx + dy < rMin;
return r3 > 0 && Cell * 2f - dx - dy < rMin;
}
/// <summary>Road bits (terrain word bits 0-1) of vertex (ix, iy); 0 outside 0..8.</summary>
public static uint RoadBits(LandblockData lb, int ix, int iy) => (uint)(lb.GetTerrainWord(ix, iy) & 3);
/// <summary>
/// Terrain type (0-31: grass, water types, ...) of the grid vertex nearest (lx, ly).
/// -1 if the landblock isn't in the dat.
/// </summary>
public int TerrainType(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
if (lb == null) return -1;
int ix = Math.Clamp((int)MathF.Round(localX / Cell), 0, LandblockData.BlockSide);
int iy = Math.Clamp((int)MathF.Round(localY / Cell), 0, LandblockData.BlockSide);
return TerrainType(lb, ix, iy);
}
/// <summary>Terrain type (terrain word bits 2-6) of vertex (ix, iy), 0..8; -1 outside the grid.</summary>
public static int TerrainType(LandblockData lb, int ix, int iy)
{
if ((uint)ix > LandblockData.BlockSide || (uint)iy > LandblockData.BlockSide) return -1;
return (lb.GetTerrainWord(ix, iy) >> 2) & 0x1F;
}
// ------------------------------------------------------------------ water
/// <summary>True for the water terrain types: WaterRunning (16) .. WaterDeepSea (20).</summary>
public static bool IsWaterTerrain(int terrainType) => terrainType >= 16 && terrainType <= 20;
/// <summary>
/// Water type of land cell (cx, cy), 0..7, from its four corner vertices (ACE
/// LandblockStruct.CalcCellWater): all four water terrain = EntirelyWater, some = PartiallyWater.
/// </summary>
public static WaterType GetWaterType(LandblockData lb, int cx, int cy)
{
int water = 0;
if (IsWaterTerrain(TerrainType(lb, cx, cy))) water++;
if (IsWaterTerrain(TerrainType(lb, cx + 1, cy))) water++;
if (IsWaterTerrain(TerrainType(lb, cx, cy + 1))) water++;
if (IsWaterTerrain(TerrainType(lb, cx + 1, cy + 1))) water++;
return water == 0 ? WaterType.NotWater : water == 4 ? WaterType.EntirelyWater : WaterType.PartiallyWater;
}
/// <summary>
/// How far an object standing in the land cell under (lx, ly) sinks below the terrain mesh
/// (ACE ObjCell.get_water_depth): 0 on dry cells, 0.45 m in a partially-water cell, 0.9 m in
/// an entirely-water cell. 0 if the landblock isn't in the dat.
/// </summary>
public float GetWaterDepth(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? 0f : GetWaterDepth(lb, localX, localY);
}
/// <inheritdoc cref="GetWaterDepth(uint, float, float)"/>
public static float GetWaterDepth(LandblockData lb, float localX, float localY)
{
Locate(localX, localY, out int cx, out int cy, out _, out _);
return GetWaterType(lb, cx, cy) switch
{
WaterType.EntirelyWater => 0.9f,
WaterType.PartiallyWater => 0.45f,
_ => 0f,
};
}
/// <summary>
/// Z at which an object stands on open ground at (lx, ly): the terrain mesh Z less the cell's
/// water depth. (Buildings, porches and other objects can hold it higher; they aren't tested.)
/// NaN if the landblock isn't in the dat.
/// </summary>
public float GetStandingZ(uint landblock, float localX, float localY)
{
var lb = LoadLandblock(landblock);
return lb == null ? float.NaN : GetTerrainZ(lb, localX, localY) - GetWaterDepth(lb, localX, localY);
}
// ------------------------------------------------------------------ raycast
/// <summary>
/// Nearest hit of a ray with the terrain mesh. <paramref name="localOrigin"/> is relative to
/// <paramref name="landblock"/>'s SW corner (X/Y local, normally 0..192 but may lie outside;
/// Z absolute). <paramref name="dir"/> needn't be unit length; <paramref name="dist"/> is in
/// metres along it. The ray walks the 24 m cell grid (2D DDA) and tests the two triangles of
/// each cell on the cell's real split (Moller-Trumbore, both faces). It is not limited to the
/// starting landblock: cells past the edge are looked up in the neighbouring landblocks, and
/// a landblock missing from the dat (or off the world) is passed over as having no ground.
/// <paramref name="normal"/> is the unit upward normal of the triangle hit.
/// Terrain only: buildings, objects and dungeon cells are not tested.
/// </summary>
public bool RaycastTerrain(uint landblock, Vector3 localOrigin, Vector3 dir, float maxDist,
out float dist, out Vector3 normal)
{
dist = 0f;
normal = Vector3.Zero;
float len = dir.Length();
if (!(len > 1e-12f) || !(maxDist > 0f) || !float.IsFinite(localOrigin.X + localOrigin.Y + localOrigin.Z)) return false;
dir /= len;
uint key = LandblockData.KeyOf(landblock);
int lbX = (int)((key >> 8) & 0xFF), lbY = (int)(key & 0xFF);
float px = localOrigin.X, py = localOrigin.Y;
int cx = (int)MathF.Floor(px / Cell);
int cy = (int)MathF.Floor(py / Cell);
int stepX = dir.X > 0 ? 1 : (dir.X < 0 ? -1 : 0);
int stepY = dir.Y > 0 ? 1 : (dir.Y < 0 ? -1 : 0);
float tMaxX = float.PositiveInfinity, tDeltaX = float.PositiveInfinity;
float tMaxY = float.PositiveInfinity, tDeltaY = float.PositiveInfinity;
if (stepX != 0)
{
tMaxX = ((stepX > 0 ? cx + 1 : cx) * Cell - px) / dir.X;
tDeltaX = Cell / MathF.Abs(dir.X);
}
if (stepY != 0)
{
tMaxY = ((stepY > 0 ? cy + 1 : cy) * Cell - py) / dir.Y;
tDeltaY = Cell / MathF.Abs(dir.Y);
}
// Cells a ray of this length can cross, plus slack for float error at the boundaries.
float span = maxDist * (MathF.Abs(dir.X) + MathF.Abs(dir.Y)) / Cell;
int iterLimit = (int)MathF.Min(span, 1_000_000f) + 4;
float bestT = maxDist;
bool found = false;
LandblockData? lb = null;
int lbCurX = int.MinValue, lbCurY = int.MinValue;
while (iterLimit-- > 0)
{
int dlx = FloorDiv(cx, LandblockData.BlockSide), dly = FloorDiv(cy, LandblockData.BlockSide);
int nx = lbX + dlx, ny = lbY + dly;
if (nx != lbCurX || ny != lbCurY)
{
lbCurX = nx;
lbCurY = ny;
lb = (uint)nx <= 0xFF && (uint)ny <= 0xFF ? LoadLandblock((uint)((nx << 8) | ny)) : null;
}
if (lb != null)
{
int lcx = cx - dlx * LandblockData.BlockSide, lcy = cy - dly * LandblockData.BlockSide;
bool swToNe = SwToNeCut(lb.LandblockKey, lcx, lcy);
// Cell-local frame (SW vertex at the origin) keeps the float math small.
float baseZ = lb.GetVertexZ(lcx, lcy);
var o = new Vector3(px - cx * Cell, py - cy * Cell, localOrigin.Z - baseZ);
for (int tri = 0; tri < 2; tri++)
{
CellTriangle(lb, lcx, lcy, swToNe, tri, out var a, out var b, out var c);
a.Z -= baseZ; b.Z -= baseZ; c.Z -= baseZ;
if (RayTriangle(o, dir, a, b, c, out float t) && t <= bestT)
{
bestT = t;
normal = UpNormal(a, b, c);
found = true;
}
}
}
float tNext = MathF.Min(tMaxX, tMaxY);
// A hit in this cell lies before the ray leaves it, so it's the nearest one.
if (found && bestT <= tNext + 1e-4f) break;
if (tNext > maxDist) break;
if (stepX == 0 && stepY == 0) break; // vertical ray: one cell
if (tMaxX < tMaxY) { tMaxX += tDeltaX; cx += stepX; }
else { tMaxY += tDeltaY; cy += stepY; }
}
if (!found) { normal = Vector3.Zero; return false; }
dist = bestT;
return true;
}
// ------------------------------------------------------------------ height table
/// <summary>
/// The 256-entry land-height table from RegionDesc 0x13000000: header (id, region number,
/// version), the region name (PString), the eight LandDefs scalars, then 256 floats.
/// Null if the record is missing or short.
/// </summary>
public static float[]? ReadLandHeightTable(DatDatabase portal)
{
byte[]? data = portal.GetFileData(RegionDescId);
// 12 (header) + >=2 (PString) + 32 (LandDefs prefix) + 256*4 (table)
if (data == null || data.Length < 12 + 2 + 32 + 256 * 4) return null;
int pos = 12; // id, regionNumber, version
int nameLen = BitConverter.ToUInt16(data, pos); // RegionName: ushort length + bytes,
pos = (pos + 2 + nameLen + 3) & ~3; // padded to 4 bytes
pos += 32; // LandDefs: NumBlockLength, NumBlockWidth, SquareLength, LBlockLength,
// VertexPerCell, MaxObjHeight, SkyHeight, RoadWidth
if (pos + 256 * 4 > data.Length) return null;
var table = new float[256];
for (int i = 0; i < 256; i++) table[i] = BitConverter.ToSingle(data, pos + i * 4);
return table;
}
// ------------------------------------------------------------------ helpers
private static void Locate(float lx, float ly, out int cx, out int cy, out float u, out float v)
{
lx = float.IsNaN(lx) ? 0f : Math.Clamp(lx, 0f, Block);
ly = float.IsNaN(ly) ? 0f : Math.Clamp(ly, 0f, Block);
cx = Math.Min((int)(lx / Cell), LandblockData.BlockSide - 1);
cy = Math.Min((int)(ly / Cell), LandblockData.BlockSide - 1);
u = (lx - cx * Cell) / Cell;
v = (ly - cy * Cell) / Cell;
}
/// <summary>
/// Triangle <paramref name="tri"/> (0 or 1) of cell (cx, cy), in the cell's local XY (0 or 24)
/// with absolute Z, wound counter-clockwise seen from above. swToNe: 0 = SE half (SW,SE,NE),
/// 1 = NW half (SW,NE,NW); otherwise 0 = SW half (SW,SE,NW), 1 = NE half (SE,NE,NW).
/// </summary>
private static void CellTriangle(LandblockData lb, int cx, int cy, bool swToNe, int tri,
out Vector3 a, out Vector3 b, out Vector3 c)
{
var sw = new Vector3(0f, 0f, lb.GetVertexZ(cx, cy));
var se = new Vector3(Cell, 0f, lb.GetVertexZ(cx + 1, cy));
var nw = new Vector3(0f, Cell, lb.GetVertexZ(cx, cy + 1));
var ne = new Vector3(Cell, Cell, lb.GetVertexZ(cx + 1, cy + 1));
if (swToNe)
{
if (tri == 0) { a = sw; b = se; c = ne; } else { a = sw; b = ne; c = nw; }
}
else
{
if (tri == 0) { a = sw; b = se; c = nw; } else { a = se; b = ne; c = nw; }
}
}
private static Vector3 UpNormal(Vector3 a, Vector3 b, Vector3 c)
{
var n = Vector3.Normalize(Vector3.Cross(b - a, c - a));
return n.Z < 0 ? -n : n;
}
// Moller-Trumbore, both faces; t along a unit direction.
private static bool RayTriangle(Vector3 origin, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t)
{
t = 0f;
const float Epsilon = 1e-7f;
Vector3 edge1 = v1 - v0;
Vector3 edge2 = v2 - v0;
Vector3 h = Vector3.Cross(dir, edge2);
float a = Vector3.Dot(edge1, h);
if (a > -Epsilon && a < Epsilon) return false;
float f = 1f / a;
Vector3 s = origin - v0;
float u = f * Vector3.Dot(s, h);
if (u < 0f || u > 1f) return false;
Vector3 q = Vector3.Cross(s, edge1);
float v = f * Vector3.Dot(dir, q);
if (v < 0f || u + v > 1f) return false;
t = f * Vector3.Dot(edge2, q);
return t >= 0f;
}
private static int FloorDiv(int a, int b) => a >= 0 ? a / b : -((-a + b - 1) / b);
private static string? FindDat(string folder, params string[] names)
{
foreach (var n in names)
{
string p = Path.Combine(folder, n);
if (File.Exists(p)) return p;
}
return null;
}
/// <summary>Drops the cache; closes the dats only if <see cref="Open"/> opened them.</summary>
public void Dispose()
{
lock (_cacheGate) _cache.Clear();
if (_ownsDats)
{
_portal.Dispose();
_cell.Dispose();
}
}
}
/// <summary>Water in a 24 m land cell (ACE LandDefs.WaterType).</summary>
public enum WaterType
{
NotWater = 0,
PartiallyWater = 1,
EntirelyWater = 2,
}

View file

@ -0,0 +1,146 @@
// ============================================================================
// RynthCore.Geometry - Walking/LocalPlanner.cs
// A short-range path around obstacles (a building corner, a fence, a doorway), for
// when a straight walk is blocked. Not a navigator: long routes come from RynthNav.
//
// A* over a grid (Grid metres) anchored at the start, where an edge exists only if
// the Walker itself can make that step (so walls, slopes, drops, doors, deep water and
// cell changes are all respected, indoors and out) and ends where it was aimed. Search
// is bounded (MaxNodes). The raw grid path is then shortened by string-pulling: from
// each kept point, the farthest later point the walker reaches in a straight line.
//
// Positions are in the start's landblock frame; a step into a neighbouring landblock
// is shifted back into that frame for the grid key, and every returned point carries
// its real cell and landblock-local position.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
namespace RynthCore.Geometry.Walking;
public readonly record struct PathPoint(uint Cell, Vector3 Position);
public sealed class LocalPlanner
{
public float Grid { get; init; } = 1.0f;
public int MaxNodes { get; init; } = 6000;
private readonly Walker _walker;
public LocalPlanner(Walker walker) => _walker = walker;
private sealed class Node
{
public required (int X, int Y) Key;
public required PathPoint At;
public Vector2 Frame; // position in the start landblock's frame
public float G;
public Node? Parent;
}
private static readonly (int X, int Y)[] Dirs = { (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1) };
/// <summary>
/// A walkable path from <paramref name="start"/> to within <paramref name="stop"/> of
/// <paramref name="goal"/> (goal's x/y in the start landblock's frame), or null.
/// The first point is the start; the last is where the path ends. With
/// <paramref name="bestEffort"/>, an unreachable goal gives the path to the reachable point
/// nearest it instead of null.
/// </summary>
public List<PathPoint>? Find(PathPoint start, Vector2 goal, float stop, bool bestEffort = false)
{
uint lb0 = start.Cell >> 16;
var origin = new Vector2(start.Position.X, start.Position.Y);
var startNode = new Node { Key = (0, 0), At = start, Frame = origin, G = 0 };
var best = new Dictionary<(int, int), Node> { [(0, 0)] = startNode };
var open = new PriorityQueue<Node, float>();
open.Enqueue(startNode, Vector2.Distance(origin, goal));
float reach = Math.Max(stop, Grid * 0.75f);
int expanded = 0;
Node? found = null, closest = startNode;
float closestD = Vector2.Distance(origin, goal);
while (open.TryDequeue(out Node? n, out _))
{
if (best[n.Key] != n) continue; // stale entry
float dn = Vector2.Distance(n.Frame, goal);
if (dn <= reach) { found = n; break; }
if (dn < closestD) { closestD = dn; closest = n; }
if (++expanded > MaxNodes) break;
foreach (var (dx, dy) in Dirs)
{
var key = (n.Key.X + dx, n.Key.Y + dy);
var target = origin + new Vector2(key.Item1, key.Item2) * Grid;
Vector2 step = target - n.Frame;
StepResult r = _walker.Step(n.At.Cell, n.At.Position, step.X, step.Y);
if (r.Blocked) continue;
Vector2 landed = InFrame(lb0, r.Cell, r.Position);
if (Vector2.Distance(landed, target) > 0.1f) continue; // slid somewhere else
float g = n.G + step.Length() + MathF.Abs(r.Position.Z - n.At.Position.Z) * 0.5f;
if (best.TryGetValue(key, out Node? old) && old.G <= g) continue;
var m = new Node { Key = key, At = new PathPoint(r.Cell, r.Position), Frame = landed, G = g, Parent = n };
best[key] = m;
open.Enqueue(m, g + Vector2.Distance(landed, goal));
}
}
if (found == null)
{
// Best effort: the reachable point nearest the goal, if it is clearly nearer than the start.
if (!bestEffort || closest == startNode || closestD > Vector2.Distance(origin, goal) - 0.5f) return null;
found = closest;
}
var raw = new List<PathPoint>();
for (Node? p = found; p != null; p = p.Parent) raw.Add(p.At);
raw.Reverse();
// The last bit, from the final grid point toward the goal itself, if it can be walked.
PathPoint last = raw[^1];
Vector2 lastFrame = InFrame(lb0, last.Cell, last.Position);
Vector2 toGoal = goal - lastFrame;
float left = toGoal.Length() - stop;
if (left > 0.05f)
{
Vector2 d = toGoal / toGoal.Length() * left;
StepResult r = _walker.Step(last.Cell, last.Position, d.X, d.Y);
if (!r.Blocked) raw.Add(new PathPoint(r.Cell, r.Position));
}
return Smooth(raw, lb0);
}
/// <summary>Keeps only the turning points: each kept point walks straight to the next.</summary>
private List<PathPoint> Smooth(List<PathPoint> raw, uint lb0)
{
var path = new List<PathPoint> { raw[0] };
int i = 0;
while (i < raw.Count - 1)
{
int j = raw.Count - 1;
for (; j > i + 1; j--)
if (StraightReaches(raw[i], raw[j], lb0)) break;
path.Add(raw[j]);
i = j;
}
return path;
}
private bool StraightReaches(PathPoint a, PathPoint b, uint lb0)
{
Vector2 fa = InFrame(lb0, a.Cell, a.Position), fb = InFrame(lb0, b.Cell, b.Position);
Vector2 d = fb - fa;
StepResult r = _walker.Step(a.Cell, a.Position, d.X, d.Y);
if (r.Blocked || r.Slid) return false;
return Vector2.Distance(InFrame(lb0, r.Cell, r.Position), fb) < 0.1f && MathF.Abs(r.Position.Z - b.Position.Z) < 0.3f
&& (EnvCell.IsIndoor(b.Cell) == EnvCell.IsIndoor(r.Cell));
}
/// <summary>A landblock-local position expressed in landblock lb0's frame (0xXXYY).</summary>
public static Vector2 InFrame(uint lb0, uint cell, Vector3 p)
{
uint lb = cell >> 16;
float ox = ((int)(lb >> 8) - (int)(lb0 >> 8)) * 192f, oy = ((int)(lb & 0xFF) - (int)(lb0 & 0xFF)) * 192f;
return new Vector2(p.X + ox, p.Y + oy);
}
}

View file

@ -0,0 +1,98 @@
// ============================================================================
// RynthCore.Geometry - Walking/Obstacles.cs
// IObstacles sources for the walker: the static outdoor world (OutdoorCollision:
// buildings, statics, building cells, scenery), objects placed at run time (closed
// doors and the like, given as placed models), and a composite of both.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Collision;
namespace RynthCore.Geometry.Walking;
/// <summary>The dats' outdoor world as walker obstacles.</summary>
public sealed class StaticObstacles : IObstacles
{
private readonly OutdoorCollision _world;
public StaticObstacles(OutdoorCollision world) => _world = world;
public IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius)
{
foreach (CollisionTri t in _world.Near(landblock, x, y, radius))
yield return (t.A, t.B, t.C, t.Normal);
}
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop)
=> _world.SurfaceBelow(landblock, x, y, zTop, maxDrop);
}
/// <summary>Several obstacle sources as one.</summary>
public sealed class CompositeObstacles : IObstacles
{
private readonly IObstacles[] _parts;
public CompositeObstacles(params IObstacles[] parts) => _parts = parts;
public IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius)
=> _parts.SelectMany(p => p.Near(landblock, x, y, radius));
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop)
{
float? best = null;
foreach (IObstacles p in _parts)
if (p.SurfaceBelow(landblock, x, y, zTop, maxDrop) is { } z && (best == null || z > best)) best = z;
return best;
}
}
/// <summary>
/// Triangles that come and go (closed doors, ...), keyed by the object they belong to, in
/// landblock-local coordinates of the landblock given when set. Thread-safe.
/// </summary>
public sealed class DynamicObstacles : IObstacles
{
private readonly object _gate = new();
private readonly Dictionary<uint, (uint Landblock, (Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)[] Tris)> _byObject = new();
public int Count { get { lock (_gate) return _byObject.Count; } }
public void Set(uint objectId, uint landblock, IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> tris)
{
var arr = tris.ToArray();
lock (_gate) _byObject[objectId] = ((landblock >> 16) == 0 ? landblock : landblock >> 16, arr);
}
public void Remove(uint objectId)
{
lock (_gate) _byObject.Remove(objectId);
}
public IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius)
{
uint lb = (landblock >> 16) == 0 ? landblock : landblock >> 16;
List<(Vector3, Vector3, Vector3, Vector3)> hits = new();
lock (_gate)
{
foreach (var (olb, tris) in _byObject.Values)
{
// Shift a neighbouring landblock's triangles into this frame.
float ox = ((int)(olb >> 8) - (int)(lb >> 8)) * 192f, oy = ((int)(olb & 0xFF) - (int)(lb & 0xFF)) * 192f;
if (MathF.Abs(ox) > 192 || MathF.Abs(oy) > 192) continue;
var off = new Vector3(ox, oy, 0);
foreach (var t in tris)
{
Vector3 a = t.A + off, b = t.B + off, c = t.C + off;
float minX = MathF.Min(a.X, MathF.Min(b.X, c.X)), maxX = MathF.Max(a.X, MathF.Max(b.X, c.X));
float minY = MathF.Min(a.Y, MathF.Min(b.Y, c.Y)), maxY = MathF.Max(a.Y, MathF.Max(b.Y, c.Y));
if (x < minX - radius || x > maxX + radius || y < minY - radius || y > maxY + radius) continue;
hits.Add((a, b, c, t.Normal));
}
}
}
return hits;
}
/// <summary>Dynamic objects are not stood on (doors are walls).</summary>
public float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop) => null;
}

View file

@ -0,0 +1,289 @@
// ============================================================================
// RynthCore.Geometry - Walking/Walker.cs
// Where a walking step lands: a kinematic walker over the dats. Not ACE's physics
// (no sphere sweep / BSP transitions); what a bot needs to move in ways the server and
// other players find sensible:
//
// - the body is the human Setup's two collision spheres (r 0.48 at 0.475 and 1.35 m);
// walls block a step that moves a sphere into them (moving away is always allowed);
// the lower test sits high enough (bottom at StepUp) that stairs and kerbs don't block;
// - a move is cut into sub-steps of at most SubStep metres, so StepUp (0.45 m) and the
// walkable slope (FloorZ) agree: a 0.4 m step on the steepest walkable ground rises
// ~0.45 m;
// - indoors: the cell follows the doorways crossed (IndoorWorld.TrackCell); leaving a
// cell's floor plan without a doorway is a wall; the feet height is where the body's
// sphere rests on the floor (StandZ), which is what ACE reports;
// - outdoors: the feet are on the terrain (less water depth) or on a walkable object
// surface (porches, platforms) within StepUp; terrain steeper than walkable can't be
// climbed; deep water (all four corners water) is not entered; crossing a building's
// outdoor doorway inward enters that EnvCell;
// - drops of more than MaxDrop are refused (a bot shouldn't walk off cliffs).
// When a step is blocked the walker tries sliding: the same step turned by 25, 50 and
// 75 degrees either way (shortened by the cosine).
//
// Coordinates: positions are landblock-local (x, y in 0..192 of the cell's landblock,
// z absolute). An outdoor step may leave the landblock; the result is re-expressed in
// the new landblock with the new cell id.
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Terrain;
namespace RynthCore.Geometry.Walking;
/// <summary>Static and dynamic obstacles outdoors (buildings, statics, scenery, doors), landblock-local.</summary>
public interface IObstacles
{
/// <summary>Triangles within <paramref name="radius"/> of (x, y) on the ground plane, in <paramref name="landblock"/>'s frame.</summary>
IEnumerable<(Vector3 A, Vector3 B, Vector3 C, Vector3 Normal)> Near(uint landblock, float x, float y, float radius);
/// <summary>The highest walkable object surface under (x, y) between zTop - maxDrop and zTop, not terrain.</summary>
float? SurfaceBelow(uint landblock, float x, float y, float zTop, float maxDrop);
}
public readonly record struct StepResult(uint Cell, Vector3 Position, bool Blocked, string? Why = null, bool Slid = false);
public sealed class Walker
{
public const float FloorZ = 0.66417414618662751f;
public float Radius { get; init; } = 0.48f;
/// <summary>Sphere centres above the feet used for wall tests.</summary>
public float LowSphere { get; init; } = 0.93f;
public float HighSphere { get; init; } = 1.35f;
public float StepUp { get; init; } = 0.45f;
public float MaxDrop { get; init; } = 2.5f;
public float SubStep { get; init; } = 0.4f;
private readonly TerrainSampler _terrain;
private readonly IndoorWorld _indoor;
private readonly IObstacles? _obstacles;
public Walker(TerrainSampler terrain, IndoorWorld indoor, IObstacles? obstacles = null)
{
_terrain = terrain;
_indoor = indoor;
_obstacles = obstacles;
}
/// <summary>Moves from <paramref name="pos"/> in <paramref name="cell"/> by (dx, dy) on the ground plane.</summary>
public StepResult Step(uint cell, Vector3 pos, float dx, float dy)
{
float len = MathF.Sqrt(dx * dx + dy * dy);
if (len < 1e-5f) return new StepResult(cell, pos, false);
int n = Math.Max(1, (int)MathF.Ceiling(len / SubStep));
float sx = dx / n, sy = dy / n;
bool slid = false;
for (int i = 0; i < n; i++)
{
StepResult r = SubStepWithSlide(cell, pos, sx, sy);
if (r.Blocked) return r with { Slid = slid || r.Slid };
slid |= r.Slid;
cell = r.Cell;
pos = r.Position;
}
return new StepResult(cell, pos, false, null, slid);
}
private static readonly float[] SlideAngles = { 25, -25, 50, -50, 75, -75 };
private StepResult SubStepWithSlide(uint cell, Vector3 pos, float dx, float dy)
{
StepResult r = TryMove(cell, pos, dx, dy);
if (!r.Blocked) return r;
foreach (float deg in SlideAngles)
{
float a = deg * MathF.PI / 180f, c = MathF.Cos(a), s = MathF.Sin(a);
float rx = (dx * c - dy * s) * c, ry = (dx * s + dy * c) * c;
StepResult t = TryMove(cell, pos, rx, ry);
if (!t.Blocked) return t with { Slid = true };
}
return r;
}
/// <summary>One straight sub-step, no sliding.</summary>
public StepResult TryMove(uint cell, Vector3 pos, float dx, float dy)
{
var to = new Vector3(pos.X + dx, pos.Y + dy, pos.Z);
return EnvCell.IsIndoor(cell) ? MoveIndoor(cell, pos, to) : MoveOutdoor(cell, pos, to);
}
// ── indoors ─────────────────────────────────────────────────────────────
private StepResult MoveIndoor(uint cell, Vector3 from, Vector3 to)
{
EnvCell? cur = _indoor.GetCell(cell);
if (cur == null) return Blocked(cell, from, "unknown cell");
uint next = _indoor.TrackCell(cell, from, to);
if (next == 0)
{
// Out through a doorway to the outdoors.
uint lb = cell >> 16;
float gz = OutdoorGround(lb, to.X, to.Y, from.Z, out string? why);
if (why != null) return Blocked(cell, from, why);
var outside = new Vector3(to.X, to.Y, gz);
if (BlockedByObstacles(lb, from, outside)) return Blocked(cell, from, "obstacle");
return Relocated(lb, outside);
}
if (next == cell && !cur.CoversXY(to.X, to.Y)) return Blocked(cell, from, "wall");
float? z = _indoor.StandZ(next, to.X, to.Y, Radius, from.Z);
if (z is not { } fz) return Blocked(cell, from, "no floor");
if (fz - from.Z > StepUp) return Blocked(cell, from, "step too high");
if (from.Z - fz > MaxDrop) return Blocked(cell, from, "drop");
var p = new Vector3(to.X, to.Y, fz);
if (BlockedIndoors(next, from, p)) return Blocked(cell, from, "wall");
return new StepResult(next, p, false);
}
private bool BlockedIndoors(uint cell, Vector3 from, Vector3 to)
{
foreach (uint c in CellAndNeighbours(cell))
{
foreach (Vector3[] wall in _indoor.Walls(c))
if (IntoPolygon(wall, from, to)) return true;
foreach (Vector3[] obj in _indoor.ObjectPolygons(c))
if (CellDat.Normal(obj).Z < FloorZ && IntoPolygon(obj, from, to)) return true;
}
return false;
}
private IEnumerable<uint> CellAndNeighbours(uint cell)
{
yield return cell;
foreach (uint n in _indoor.Neighbours(cell)) yield return n;
}
// ── outdoors ────────────────────────────────────────────────────────────
private StepResult MoveOutdoor(uint cell, Vector3 from, Vector3 to)
{
uint lb = cell >> 16;
// Into a building through one of its outdoor doorways?
foreach (EnvCell c in _indoor.LoadLandblock(lb))
{
if ((c.Flags & 1) == 0) continue; // only cells seen from outside have outdoor doorways
foreach (CellPortal p in c.Portals)
{
if (!p.LeadsOutdoors || p.Polygon.Length < 3) continue;
var lift = new Vector3(0, 0, IndoorWorld.PortalLift);
if (!Geo.SegmentCrossesToward(p.Polygon, from + lift, to + lift, !p.PortalSide)) continue;
// Just past the threshold the floor plan may not start yet: keep the height until it does.
float fz = _indoor.StandZ(c.Id, to.X, to.Y, Radius, from.Z) ?? from.Z;
if (fz - from.Z > StepUp) return Blocked(cell, from, "step too high");
var inside = new Vector3(to.X, to.Y, fz);
if (BlockedIndoors(c.Id, from, inside)) return Blocked(cell, from, "wall");
return new StepResult(c.Id, inside, false);
}
}
float gz = OutdoorGround(lb, to.X, to.Y, from.Z, out string? why);
if (why != null) return Blocked(cell, from, why);
var at = new Vector3(to.X, to.Y, gz);
if (BlockedByObstacles(lb, from, at)) return Blocked(cell, from, "obstacle");
return Relocated(lb, at);
}
/// <summary>Feet height outdoors at (x, y) in landblock lb's frame (x/y may be outside 0..192). why != null = not allowed.</summary>
private float OutdoorGround(uint lb, float x, float y, float fromZ, out string? why)
{
why = null;
(uint tlb, float lx, float ly) = Normalize(lb, x, y);
LandblockData? land = _terrain.LoadLandblock(tlb);
if (land == null) { why = "no terrain"; return fromZ; }
int cx = Math.Clamp((int)(lx / 24), 0, 7), cy = Math.Clamp((int)(ly / 24), 0, 7);
if (TerrainSampler.GetWaterType(land, cx, cy) == WaterType.EntirelyWater) { why = "deep water"; return fromZ; }
float terrainZ = TerrainSampler.GetTerrainZ(land, lx, ly) - TerrainSampler.GetWaterDepth(land, lx, ly);
float z = terrainZ;
if (_obstacles?.SurfaceBelow(tlb, lx, ly, fromZ + StepUp, MaxDrop + StepUp) is { } s && s > z) z = s;
if (z - fromZ > StepUp)
{
// Climbing: allowed on walkable terrain (sub-steps keep the rise per step small), not on objects.
bool onTerrain = z == terrainZ;
if (!onTerrain || !TerrainSampler.IsWalkable(TerrainSampler.GetNormal(land, lx, ly))) { why = onTerrain ? "too steep" : "step too high"; return fromZ; }
}
if (fromZ - z > MaxDrop) { why = "drop"; return fromZ; }
return z;
}
private bool BlockedByObstacles(uint lb, Vector3 from, Vector3 to)
{
if (_obstacles == null) return false;
foreach (var t in _obstacles.Near(lb, to.X, to.Y, Radius + 0.5f))
{
if (t.Normal.Z >= FloorZ) continue;
if (IntoPolygon(new[] { t.A, t.B, t.C }, from, to)) return true;
}
return false;
}
/// <summary>
/// Could the body stand at <paramref name="p"/> (landblock-local, in <paramref name="cell"/>)?
/// Indoors: the cell has a floor there. Outdoors: there is ground (not deep water, not too
/// far below or above p.Z) and no wall within the body's radius.
/// </summary>
public bool CanStand(uint cell, Vector3 p)
{
if (EnvCell.IsIndoor(cell))
return _indoor.StandZ(cell, p.X, p.Y, Radius, p.Z) is { } z && MathF.Abs(z - p.Z) < 2f;
uint lb = cell >> 16;
float gz = OutdoorGround(lb, p.X, p.Y, p.Z + 1f, out string? why);
if (why != null || MathF.Abs(gz - p.Z) > 2f) return false;
if (_obstacles == null) return true;
var at = new Vector3(p.X, p.Y, gz);
foreach (var t in _obstacles.Near(lb, p.X, p.Y, Radius + 0.5f))
{
if (t.Normal.Z >= FloorZ) continue;
var tri = new[] { t.A, t.B, t.C };
if (Geo.DistToPolygon(tri, at + new Vector3(0, 0, LowSphere)) < Radius * 0.8f
|| Geo.DistToPolygon(tri, at + new Vector3(0, 0, HighSphere)) < Radius * 0.8f) return false;
}
return true;
}
// ── shared ──────────────────────────────────────────────────────────────
/// <summary>Does moving the body from -> to push one of its spheres into the polygon?</summary>
private bool IntoPolygon(IReadOnlyList<Vector3> poly, Vector3 from, Vector3 to)
{
foreach (float h in new[] { LowSphere, HighSphere })
{
var b = new Vector3(to.X, to.Y, to.Z + h);
float after = Geo.DistToPolygon(poly, b);
if (after >= Radius) continue;
float before = Geo.DistToPolygon(poly, new Vector3(from.X, from.Y, from.Z + h));
if (after < before - 1e-4f) return true;
}
return false;
}
private static StepResult Blocked(uint cell, Vector3 at, string why) => new(cell, at, true, why);
/// <summary>An outdoor position given in landblock lb's frame (0xXXYY), re-expressed in the landblock that contains it.</summary>
private static StepResult Relocated(uint lb, Vector3 p)
{
(uint l, float x, float y) = Normalize(lb, p.X, p.Y);
return new StepResult(OutdoorCell(l, x, y), new Vector3(x, y, p.Z), false);
}
private static (uint lb, float x, float y) Normalize(uint lb, float x, float y)
{
int bx = (int)(lb >> 8) & 0xFF, by = (int)lb & 0xFF;
while (x < 0 && bx > 0) { x += 192; bx--; }
while (x >= 192 && bx < 254) { x -= 192; bx++; }
while (y < 0 && by > 0) { y += 192; by--; }
while (y >= 192 && by < 254) { y -= 192; by++; }
return ((uint)((bx << 8) | by), Math.Clamp(x, 0, 191.999f), Math.Clamp(y, 0, 191.999f));
}
/// <summary>The outdoor land cell (1..64) containing (x, y) of landblock lb (x/y may be outside 0..192).</summary>
public static uint OutdoorCell(uint lb, float x, float y)
{
(uint l, float lx, float ly) = Normalize(lb, x, y);
return (l << 16) | (uint)((int)(lx / 24) * 8 + (int)(ly / 24) + 1);
}
}

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();
}
}

View file

@ -0,0 +1,101 @@
// ============================================================================
// RynthCore.Headless - Dat/DatFile.cs
// Reads one file by id from an AC dat (header at 0x140, B-tree search by id, block
// chains whose first dword is the next block). Adapted from the engine's minimal
// reader in ImGui/MonsterHud/PortalSpellTable.cs (itself a port of RynthSuite's
// TerrainData/DatDatabase.cs). Read-only, shares the file with running clients.
// P2 replaces this with the shared dat library.
// ============================================================================
namespace RynthCore.Headless.Dat;
public static class DatFile
{
private const int HeaderOffset = 0x140;
private const int Branches = 62, MaxEntries = 61, EntrySize = 24;
private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716
private const int MaxDepth = 16;
/// <summary>
/// The folder with the dats: <paramref name="preferred"/> (the launcher's acclient.exe folder) when it
/// has them, else the usual install folder, else the current directory.
/// </summary>
public static string? FindAcFolder(string? preferred = null)
{
foreach (string dir in new[] { preferred ?? "", @"C:\Turbine\Asheron's Call", Environment.CurrentDirectory })
if (dir.Length > 0 && File.Exists(Path.Combine(dir, "client_portal.dat"))) return dir;
return null;
}
public static byte[]? Read(string path, uint fileId, out string why)
{
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
Span<byte> hdr = stackalloc byte[36];
fs.Seek(HeaderOffset, SeekOrigin.Begin);
if (!ReadFully(fs, hdr)) { why = "short header"; return null; }
uint blockSize = BitConverter.ToUInt32(hdr.Slice(4, 4));
uint root = BitConverter.ToUInt32(hdr.Slice(32, 4));
if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length) { why = "bad header"; return null; }
uint offset = root;
for (int depth = 0; depth < MaxDepth && offset != 0; depth++)
{
byte[]? node = ReadChain(fs, blockSize, offset, NodeSize);
if (node == null) { why = "unreadable B-tree node"; return null; }
uint count = BitConverter.ToUInt32(node, 4 * Branches);
if (count > MaxEntries) { why = "corrupt B-tree node"; return null; }
int i = 0;
while (i < count && BitConverter.ToUInt32(node, 4 * Branches + 4 + i * EntrySize + 4) < fileId) i++;
if (i < count && BitConverter.ToUInt32(node, 4 * Branches + 4 + i * EntrySize + 4) == fileId)
{
int e = 4 * Branches + 4 + i * EntrySize;
uint fileOffset = BitConverter.ToUInt32(node, e + 8);
uint fileSize = BitConverter.ToUInt32(node, e + 12);
if (fileSize == 0 || fileSize > 64 * 1024 * 1024) { why = "implausible file size"; return null; }
byte[]? data = ReadChain(fs, blockSize, fileOffset, (int)fileSize);
why = data == null ? "unreadable file blocks" : "";
return data;
}
bool leaf = BitConverter.ToUInt32(node, 0) == 0;
if (leaf || i >= Branches) break;
offset = BitConverter.ToUInt32(node, i * 4);
}
why = $"file 0x{fileId:X8} not in the dat";
return null;
}
private static byte[]? ReadChain(FileStream fs, uint blockSize, uint offset, int size)
{
if ((long)offset + 4 > fs.Length) return null;
var buffer = new byte[size];
Span<byte> next = stackalloc byte[4];
fs.Seek(offset, SeekOrigin.Begin);
if (!ReadFully(fs, next)) return null;
uint nextAddr = BitConverter.ToUInt32(next);
int done = 0, guard = 0;
while (done < size)
{
int take = Math.Min((int)blockSize - 4, size - done);
if (!ReadFully(fs, buffer.AsSpan(done, take))) return null;
done += take;
if (done >= size) break;
if (nextAddr == 0 || nextAddr >= fs.Length || ++guard > 1_000_000) return null;
fs.Seek(nextAddr, SeekOrigin.Begin);
if (!ReadFully(fs, next)) return null;
nextAddr = BitConverter.ToUInt32(next);
}
return buffer;
}
private static bool ReadFully(FileStream fs, Span<byte> dest)
{
while (dest.Length > 0)
{
int n = fs.Read(dest);
if (n <= 0) return false;
dest = dest.Slice(n);
}
return true;
}
}

View file

@ -0,0 +1,165 @@
// ============================================================================
// RynthCore.Headless - Dat/SkillTable.cs
// The two portal-dat tables the character sheet is computed from:
// 0x0E000004 SkillTable: file id, then a packed hash table (u16 count, u16 buckets)
// of u32 skill id + SkillBase: description and name (u16-length strings, each
// padded to a 4-byte boundary), icon, trained cost, specialized cost, category,
// chargen use, min level (1 = usable untrained, 2 = must be trained), the formula
// (w, x, y, z = divisor, attr1, attr2; x == 0 = no attribute part), then upper
// bound, lower bound and learn mod (doubles).
// 0x0E000003 SecondaryAttributeTable: file id, then the max health, max stamina and
// max mana formulas (same 6 dwords each).
// The retired skills (axe, bow, ... unarmed) are not in the dat; their formulas are
// the documented retail ones.
// ============================================================================
namespace RynthCore.Headless.Dat;
/// <summary>A dat skill/vital formula: (attr1 [+ attr2]) / divisor, rounded half away from zero.</summary>
public readonly record struct SkillFormula(uint W, uint X, uint Y, uint Divisor, uint Attr1, uint Attr2)
{
public bool HasAttributes => X != 0;
/// <summary>The attribute contribution for the given attribute values (Strength 1 .. Self 6).</summary>
public uint Apply(Func<uint, uint> attribute)
{
if (X == 0 || Attr1 == 0) return 0;
uint total = attribute(Attr1);
if (Attr2 != 0) total += attribute(Attr2);
if (Divisor > 1)
total = (uint)Math.Round((float)total / Divisor, MidpointRounding.AwayFromZero);
return total;
}
public override string ToString() => X == 0 ? "none" : Attr2 != 0 ? $"(a{Attr1} + a{Attr2}) / {Divisor}" : $"a{Attr1} / {Divisor}";
}
public sealed record SkillBaseInfo(uint Id, string Name, uint Category, uint MinLevel, SkillFormula Formula)
{
/// <summary>Untrained skills with MinLevel 1 still get the attribute part.</summary>
public bool UsableUntrained => MinLevel == 1;
}
public sealed class SkillTable
{
public const uint SkillFileId = 0x0E000004;
public const uint VitalFileId = 0x0E000003;
private readonly Dictionary<uint, SkillBaseInfo> _skills = new();
public IReadOnlyDictionary<uint, SkillBaseInfo> Skills => _skills;
/// <summary>Max health, max stamina, max mana formulas.</summary>
public SkillFormula MaxHealth { get; private set; }
public SkillFormula MaxStamina { get; private set; }
public SkillFormula MaxMana { get; private set; }
public SkillBaseInfo? Get(uint skill) => _skills.TryGetValue(skill, out SkillBaseInfo? s) ? s : null;
/// <summary>The formula for a vital: 1 Health, 2 Stamina, 3 Mana.</summary>
public SkillFormula VitalFormula(uint vital) => vital switch { 1 => MaxHealth, 2 => MaxStamina, _ => MaxMana };
public static SkillTable? Load(string acFolder, out string why)
{
string portal = Path.Combine(acFolder, "client_portal.dat");
byte[]? skills = DatFile.Read(portal, SkillFileId, out why);
if (skills == null) return null;
byte[]? vitals = DatFile.Read(portal, VitalFileId, out why);
if (vitals == null) return null;
var t = new SkillTable();
if (!t.ParseSkills(skills)) { why = "skill table did not parse"; return null; }
if (!t.ParseVitals(vitals)) { why = "secondary attribute table did not parse"; return null; }
t.AddRetired();
why = "";
return t;
}
private sealed class Reader
{
private readonly byte[] _b;
public int P;
public bool Ok = true;
public Reader(byte[] b) => _b = b;
public uint U32() { if (P + 4 > _b.Length) { Ok = false; return 0; } uint v = BitConverter.ToUInt32(_b, P); P += 4; return v; }
public ushort U16() { if (P + 2 > _b.Length) { Ok = false; return 0; } ushort v = BitConverter.ToUInt16(_b, P); P += 2; return v; }
public double F64() { if (P + 8 > _b.Length) { Ok = false; return 0; } double v = BitConverter.ToDouble(_b, P); P += 8; return v; }
public string Str()
{
int n = U16();
if (!Ok || P + n > _b.Length) { Ok = false; return ""; }
string s = System.Text.Encoding.Latin1.GetString(_b, P, n);
P += n;
P = (P + 3) & ~3;
return s;
}
public SkillFormula Formula() => new(U32(), U32(), U32(), U32(), U32(), U32());
}
private bool ParseSkills(byte[] raw)
{
var r = new Reader(raw);
r.U32(); // file id
int count = r.U16();
r.U16(); // buckets
for (int i = 0; i < count && r.Ok; i++)
{
uint id = r.U32();
r.Str(); // description
string name = r.Str();
r.U32(); r.U32(); r.U32(); // icon, trained cost, specialized cost
uint category = r.U32();
r.U32(); // chargen use
uint minLevel = r.U32();
SkillFormula f = r.Formula();
r.F64(); r.F64(); r.F64(); // upper bound, lower bound, learn mod
if (r.Ok) _skills[id] = new SkillBaseInfo(id, name, category, minLevel, f);
}
return r.Ok && _skills.Count > 0;
}
private bool ParseVitals(byte[] raw)
{
var r = new Reader(raw);
r.U32();
MaxHealth = r.Formula();
MaxStamina = r.Formula();
MaxMana = r.Formula();
return r.Ok;
}
private void AddRetired()
{
// Strength 1, Endurance 2, Quickness 3, Coordination 4, Focus 5, Self 6.
void Add(uint id, string name, uint a1, uint a2, uint div)
{
if (!_skills.ContainsKey(id))
_skills[id] = new SkillBaseInfo(id, name, 1, 2, new SkillFormula(0, 1, 0, div, a1, a2));
}
Add(1, "Axe", 1, 4, 3);
Add(2, "Bow", 4, 0, 2);
Add(3, "Crossbow", 4, 0, 2);
Add(4, "Dagger", 3, 4, 3);
Add(5, "Mace", 1, 4, 3);
Add(9, "Spear", 1, 4, 3);
Add(10, "Staff", 1, 4, 3);
Add(11, "Sword", 1, 4, 3);
Add(12, "Thrown Weapons", 4, 0, 2);
Add(13, "Unarmed Combat", 1, 4, 3);
}
// One table per process: the portal dat doesn't change while we run.
private static readonly Lazy<SkillTable?> _shared = new(() =>
{
try
{
string? ac = DatFile.FindAcFolder();
return ac != null ? Load(ac, out _) : null;
}
catch
{
return null;
}
});
/// <summary>The table from the usual AC folder (null when the dats aren't there).</summary>
public static SkillTable? Shared => _shared.Value;
}

View file

@ -0,0 +1,84 @@
// ============================================================================
// RynthCore.Headless - Dat/SpellTable.cs
// The spell table (portal dat file 0x0E00000E): every spell's name, school,
// category, flags, mana, power and duration. Layout as documented in the engine's
// ImGui/MonsterHud/PortalSpellTable.cs (whose parse this follows): file id, then a
// hash table of u32 id + SpellBase (obfuscated name/description strings, school,
// icon, category, bitfield, base mana, range const/mod, power, economy mod, formula
// version, component loss, meta type, meta id, [duration + degrade for enchantments |
// lifetime for portal summons], 8 components, effects, recovery, display order,
// target type, mana mod).
// ============================================================================
namespace RynthCore.Headless.Dat;
public sealed record SpellInfo(uint Id, string Name, uint School, uint Icon, uint Category, uint Flags, uint BaseMana,
float RangeConstant, float RangeMod, uint Power, uint MetaType, double Duration)
{
public bool Beneficial => (Flags & 0x4) != 0;
public bool SelfTargeted => (Flags & 0x8) != 0;
public bool IsEnchantment => MetaType is 1 or 12;
}
public sealed class SpellTable
{
public const uint FileId = 0x0E00000E;
private const uint MetaEnchantment = 1, MetaPortalSummon = 7, MetaFellowEnchantment = 12;
private readonly Dictionary<uint, SpellInfo> _byId = new();
public IReadOnlyDictionary<uint, SpellInfo> ById => _byId;
public static SpellTable? Load(string acFolder, out string why)
{
byte[]? raw = DatFile.Read(Path.Combine(acFolder, "client_portal.dat"), FileId, out why);
if (raw == null) return null;
var t = new SpellTable();
t.Parse(raw);
return t;
}
public SpellInfo? Get(uint id) => _byId.TryGetValue(id, out SpellInfo? s) ? s : null;
private void Parse(byte[] raw)
{
int p = 0;
bool ok = true;
uint U32() { if (p + 4 > raw.Length) { ok = false; return 0; } uint v = BitConverter.ToUInt32(raw, p); p += 4; return v; }
float F32() { if (p + 4 > raw.Length) { ok = false; return 0; } float v = BitConverter.ToSingle(raw, p); p += 4; return v; }
double F64() { if (p + 8 > raw.Length) { ok = false; return 0; } double v = BitConverter.ToDouble(raw, p); p += 8; return v; }
ushort U16() { if (p + 2 > raw.Length) { ok = false; return 0; } ushort v = BitConverter.ToUInt16(raw, p); p += 2; return v; }
void Skip(int n) { if (p + n > raw.Length) ok = false; else p += n; }
string Str()
{
int n = U16();
if (!ok || p + n > raw.Length) { ok = false; return ""; }
var c = new char[n];
for (int i = 0; i < n; i++) { byte x = raw[p + i]; c[i] = (char)(byte)((x >> 4) | (x << 4)); }
p += n;
p = (p + 3) & ~3;
return new string(c);
}
U32();
int total = U16();
U16();
for (int i = 0; i < total && ok; i++)
{
uint id = U32();
string name = Str();
Str();
uint school = U32(), icon = U32(), category = U32(), flags = U32(), mana = U32();
float rc = F32(), rm = F32();
uint power = U32();
Skip(12);
uint meta = U32();
U32();
double duration = 0;
if (meta == MetaEnchantment || meta == MetaFellowEnchantment) { duration = F64(); Skip(8); }
else if (meta == MetaPortalSummon) Skip(8);
Skip(8 * 4 + 12 + 8 + 4 + 12);
if (!ok) break;
_byId[id] = new SpellInfo(id, name, school, icon, category, flags, mana, rc, rm, power, meta, duration);
}
}
}

View file

@ -0,0 +1,70 @@
// ============================================================================
// RynthCore.Headless - Host/Actions/ChatLineRouter.cs
// Where a chat-bar line goes once no plugin has eaten it (the engine's
// ChatCommandDispatcher, minus AC's chat bar):
// bare text, and '@' server commands -> Talk (0x0015) as typed
// /say /s, /emote, /me, /tell /t Name, msg -> Talk, Emote (0x01DF), SoulEmote (0x01E1),
// Tell (0x005D)
// any other "/command args" -> Talk "@command args": ACE runs Talk text
// that starts with '@' as a server command
// (GameActionTalk), and a server command typed
// with '/' reaches it that way from a retail
// client too
// chat channels (/a /f /g /trade ...), /r /retell, the engine's /rc
// -> not available headless (refused)
// ============================================================================
namespace RynthCore.Headless.Host.Actions;
public enum ChatRouteKind { None, Say, Emote, SoulEmote, Tell, Unsupported }
public readonly record struct ChatRoute(ChatRouteKind Kind, string Text, string Target = "", string Why = "");
public static class ChatLineRouter
{
// AC's own channel and reply commands: they need AC's chat rooms or its tell memory.
private static readonly HashSet<string> Unsupported = new(StringComparer.OrdinalIgnoreCase)
{
"a", "f", "g", "p", "v", "c", "m", "general", "trade", "lfg", "roleplay", "society", "olthoi",
"allegiance", "fellowship", "patron", "vassals", "covassals", "monarch",
"r", "reply", "rt", "retell", "rc",
};
public static ChatRoute Route(string? line)
{
string t = (line ?? "").Trim();
if (t.Length == 0) return new ChatRoute(ChatRouteKind.None, "");
if (t[0] != '/') return new ChatRoute(ChatRouteKind.Say, t);
int space = t.IndexOf(' ');
string cmd = (space < 0 ? t.Substring(1) : t.Substring(1, space - 1)).ToLowerInvariant();
string rest = space < 0 ? "" : t.Substring(space + 1).Trim();
switch (cmd)
{
case "":
return new ChatRoute(ChatRouteKind.None, "");
case "say":
case "s":
return rest.Length > 0 ? new ChatRoute(ChatRouteKind.Say, rest) : new ChatRoute(ChatRouteKind.None, "");
case "emote":
case "em":
case "e":
return rest.Length > 0 ? new ChatRoute(ChatRouteKind.Emote, rest) : new ChatRoute(ChatRouteKind.None, "");
case "me":
return rest.Length > 0 ? new ChatRoute(ChatRouteKind.SoulEmote, rest) : new ChatRoute(ChatRouteKind.None, "");
case "tell":
case "t":
{
int comma = rest.IndexOf(',');
string name = comma > 0 ? rest.Substring(0, comma).Trim() : "";
string msg = comma > 0 ? rest.Substring(comma + 1).Trim() : "";
return name.Length > 0 && msg.Length > 0
? new ChatRoute(ChatRouteKind.Tell, msg, name)
: new ChatRoute(ChatRouteKind.Unsupported, t, Why: "usage: /tell Name, message");
}
}
if (Unsupported.Contains(cmd))
return new ChatRoute(ChatRouteKind.Unsupported, t, Why: $"/{cmd} isn't available headless");
return new ChatRoute(ChatRouteKind.Say, "@" + t.Substring(1));
}
}

View file

@ -0,0 +1,341 @@
// ============================================================================
// RynthCore.Headless - Host/HostApi.Actions.cs
// The ACTIONS area's API slots: combat, casts, busy / use-done / weenie-error
// tracking, uses and inventory sends, selection, chat, movement and jumps,
// confirmations. Thin unmanaged wrappers over HostContext.Actions.cs; every one
// swallows its exceptions (a plugin call must never see one) and answers as the
// engine does: 1 sent / queued, 0 refused.
// ============================================================================
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginSdk;
namespace RynthCore.Headless.Host;
internal static unsafe partial class HostApi
{
static partial void FillActions(RynthCoreApiNative* api)
{
// combat + casts
api->ChangeCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ActChangeCombatMode;
api->CancelAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActCancelAttack;
api->QueryHealthFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ActQueryHealth;
api->MeleeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&ActMeleeAttack;
api->MissileAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, float, int>)&ActMissileAttack;
api->CastSpellFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&ActCastSpell;
api->NativeAttackFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, float, int>)&ActNativeAttack;
api->IsPlayerReadyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActIsPlayerReady;
api->GetCurrentCombatModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActGetCurrentCombatMode;
// busy, use-done, errors
api->GetCastBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActGetCastBusyState;
api->GetBusyStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActGetBusyState;
api->ForceResetBusyCountFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&ActForceResetBusyCount;
api->GetUseDoneSeqFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActGetUseDoneSeq;
api->GetLastUseDoneFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, int>)&ActGetLastUseDone;
api->GetLastWeenieErrorFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, uint*, uint*, uint*, int>)&ActGetLastWeenieError;
// uses + inventory
api->UseObjectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ActUseObject;
api->UseObjectOnFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&ActUseObjectOn;
api->UseEquippedItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&ActUseEquippedItem;
api->MoveItemExternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&ActMoveItemExternal;
api->MoveItemInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)&ActMoveItemInternal;
api->PutItemInContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&ActPutItemInContainer;
api->SalvageDirectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&ActSalvageDirect;
api->SplitStackInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int, int>)&ActSplitStackInternal;
api->MergeStackInternalFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&ActMergeStackInternal;
api->GetMergeStackResultFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)&ActGetMergeStackResult;
api->GiveObjectToFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int>)&ActGiveObjectTo;
api->WieldItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&ActWieldItem;
api->CloseContainerFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ActCloseContainer;
// selection
api->SelectItemFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ActSelectItem;
api->SetSelectedObjectIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ActSetSelectedObjectId;
api->GetSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&ActGetSelectedItemId;
api->GetPreviousSelectedItemIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&ActGetPreviousSelectedItemId;
api->GetGroundContainerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&ActGetGroundContainerId;
// chat
api->WriteToChatFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int, int>)&ActWriteToChat;
api->InvokeChatParserFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, int>)&ActInvokeChatParser;
api->SetIncomingChatSuppressionFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, void>)&ActSetIncomingChatSuppression;
// movement
api->DoMovementFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, float, int, int>)&ActDoMovement;
api->StopMovementFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&ActStopMovement;
api->SetMotionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int>)&ActSetMotion;
api->SetAutoRunFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ActSetAutoRun;
api->StopCompletelyFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActStopCompletely;
api->TurnToHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&ActTurnToHeading;
api->SetAutonomyLevelFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ActSetAutonomyLevel;
// jumps
api->JumpNonAutonomousFn = (IntPtr)(delegate* unmanaged[Cdecl]<float, int>)&ActJumpNonAutonomous;
api->TapJumpFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActTapJump;
api->CommenceJumpFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&ActCommenceJump;
api->DoJumpFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int>)&ActDoJump;
api->LaunchJumpWithMotionFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int, int, int, int, int>)&ActLaunchJumpWithMotion;
// confirmations
api->ArmConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, int, int>)&ActArmConfirmation;
api->GetLastConfirmationFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int*, int*, int*, int>)&ActGetLastConfirmation;
}
/// <summary>Runs <paramref name="f"/> against the current context; <paramref name="fallback"/> without one or when it throws.</summary>
private static T RunAct<T>(Func<HostContext, T> f, T fallback)
{
try
{
HostContext? c = Ctx;
return c == null ? fallback : f(c);
}
catch (Exception ex)
{
try { Ctx?.Log($"[host] action threw {ex.GetType().Name}: {ex.Message}"); } catch { }
return fallback;
}
}
private static int RunAct(Func<HostContext, bool> f) => RunAct(c => f(c) ? 1 : 0, 0);
// ── combat + casts ──────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActChangeCombatMode(int mode) => RunAct(c => c.ActChangeCombatMode(mode));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActCancelAttack() => RunAct(c => c.ActCancelAttack());
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActQueryHealth(uint target) => RunAct(c => c.ActQueryHealth(target));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActMeleeAttack(uint target, int height, float power) => RunAct(c => c.ActMelee(target, height, power));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActMissileAttack(uint target, int height, float accuracy) => RunAct(c => c.ActMissile(target, height, accuracy));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActCastSpell(uint target, int spellId) => RunAct(c => c.ActCast(target, spellId));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActNativeAttack(int height, float power) => RunAct(c => c.ActNativeAttack(height, power));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActIsPlayerReady() => RunAct(c => c.PlayerReady);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetCurrentCombatMode() => RunAct(c => c.CurrentCombatMode, 1);
// ── busy, use-done, errors ──────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetCastBusyState() => RunAct(c => c.CastBusyState, 0);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetBusyState() => RunAct(c => Math.Max(0, c.BusyCount), 0);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void ActForceResetBusyCount() => RunAct(c => { c.ForceResetBusy(); return true; });
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetUseDoneSeq() => RunAct(c => c.UseDoneSeq, 0);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetLastUseDone(int* seq, uint* error)
{
try
{
HostContext? c = Ctx;
if (c == null) return 0;
(int s, uint e) = c.LastUseDone;
if (seq != null) *seq = s;
if (error != null) *error = e;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId)
{
try
{
HostContext? c = Ctx;
if (c == null) return 0;
(int s, uint e, uint t, uint o) = c.LastWeenieError;
if (seq != null) *seq = s;
if (error != null) *error = e;
if (eventType != null) *eventType = t;
if (objectId != null) *objectId = o;
return 1;
}
catch { return 0; }
}
// ── uses + inventory ────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActUseObject(uint obj) => RunAct(c => c.ActUse(obj));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActUseObjectOn(uint source, uint target) => RunAct(c => c.ActUseOn(source, target));
/// <summary>An equipped item used on a target (a wand on a creature, ...): the same UseWithTarget the client sends.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActUseEquippedItem(uint source, uint target) => RunAct(c => c.ActUseOn(source, target));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActMoveItemExternal(uint obj, uint container, int amount) => RunAct(c => c.ActMoveItemExternal(obj, container, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActMoveItemInternal(uint obj, uint container, int slot, int amount) => RunAct(c => c.ActMoveItemInternal(obj, container, slot, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActPutItemInContainer(uint item, uint container, int placement) => RunAct(c => c.ActPutItemInContainer(item, container, placement), 0);
/// <summary>SalvageDirect: the ids are copied out first (a lambda can't hold the pointer); count sent, 0 refused.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSalvageDirect(uint tool, uint* ids, int count)
{
if (ids == null || count <= 0 || count > RynthCoreHost.MaxSalvageDirectItems) return 0;
var list = new uint[count];
for (int i = 0; i < count; i++) list[i] = ids[i];
return RunAct(c => c.ActSalvageDirect(tool, list), 0);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSplitStackInternal(uint obj, uint container, int slot, int amount) => RunAct(c => c.ActSplitStack(obj, container, slot, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActMergeStackInternal(uint source, uint target) => RunAct(c => c.ActMergeStack(source, target));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetMergeStackResult(uint source, uint target, int* amount, int* ageMs)
{
try
{
HostContext? c = Ctx;
if (c == null) return HostContext.MergeNone;
int status = c.MergeResult(source, target, out int a, out int age);
if (amount != null) *amount = a;
if (ageMs != null) *ageMs = age;
return status;
}
catch { return HostContext.MergeNone; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGiveObjectTo(uint obj, uint target, int amount) => RunAct(c => c.ActGive(obj, target, amount));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActWieldItem(uint obj, uint equipMask) => RunAct(c => c.ActWield(obj, equipMask));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActCloseContainer(uint container) => RunAct(c => c.ActCloseContainer(container));
// ── selection ───────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSelectItem(uint obj) => RunAct(c => c.ActSelectItem(obj));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSetSelectedObjectId(uint obj) => RunAct(c => c.ActSetSelected(obj));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint ActGetSelectedItemId() => RunAct(c => c.SelectedId, 0u);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint ActGetPreviousSelectedItemId() => RunAct(c => c.PreviousSelectedId, 0u);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint ActGetGroundContainerId() => RunAct(c => c.GroundContainer, 0u);
// ── chat ────────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActWriteToChat(IntPtr textUtf16, int chatType)
{
string? text = textUtf16 != IntPtr.Zero ? Marshal.PtrToStringUni(textUtf16) : null;
return RunAct(c => c.ActWriteToChat(text, chatType));
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActInvokeChatParser(IntPtr textUtf16)
{
string? text = textUtf16 != IntPtr.Zero ? Marshal.PtrToStringUni(textUtf16) : null;
return RunAct(c => c.ActInvokeChatParser(text));
}
/// <summary>No chat window to keep lines out of: a no-op.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void ActSetIncomingChatSuppression(int enabled) { }
// ── movement ────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActDoMovement(uint motion, float speed, int holdKey) => RunAct(c => c.ActSetMotion(motion, true, holdKey != 0));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActStopMovement(uint motion, int holdKey) => RunAct(c => c.ActSetMotion(motion, false, holdKey != 0));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSetMotion(uint motion, int enabled) => RunAct(c => c.ActSetMotion(motion, enabled != 0));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSetAutoRun(int enabled) => RunAct(c => c.ActSetAutoRun(enabled != 0));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActStopCompletely() => RunAct(c => c.ActStopCompletely());
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActTurnToHeading(float headingDegrees) => RunAct(c => c.ActTurnToHeading(headingDegrees));
/// <summary>The client's autonomy level has no counterpart here: accepted.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActSetAutonomyLevel(uint level) => 1;
// ── jumps ───────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActJumpNonAutonomous(float extent) => RunAct(c => c.ActJump(extent));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActTapJump() => RunAct(c => c.ActJump(0f));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActCommenceJump() => RunAct(c => c.ActCommenceJump());
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActDoJump(int autonomous) => RunAct(c => c.ActJump(c.JumpCharge));
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActLaunchJumpWithMotion(int shift, int w, int x, int z, int cKey)
=> RunAct(c => c.ActLaunchJump(shift != 0, w != 0, x != 0, z != 0, cKey != 0));
// ── confirmations ───────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActArmConfirmation(uint type, int minPercent, int timeoutMs) => RunAct(c => c.ActArmConfirmation(type, minPercent, timeoutMs), 0);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ActGetLastConfirmation(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs)
{
try
{
HostContext? c = Ctx;
if (c == null) return 0;
int seq = c.LastConfirmation(out uint t, out uint ctx, out int pct, out int oc, out int age);
if (type != null) *type = t;
if (contextId != null) *contextId = ctx;
if (percent != null) *percent = pct;
if (outcome != null) *outcome = oc;
if (ageMs != null) *ageMs = age;
return seq;
}
catch { return 0; }
}
}

View file

@ -0,0 +1,577 @@
// ============================================================================
// RynthCore.Headless - Host/HostApi.Objects.cs
// The objects / properties slots of the API table: names, positions, types, flags,
// every property kind (Host/Objects/ObjectProps.cs has the lookup order and the
// CreateObject header fallbacks), ownership and containers, the live id list,
// identify (request, appraisal data, spell book, target vitals), heading / physics
// state / door motion, server age and ghost removal, the v84 property record,
// container order and what the player wields.
//
// Engine conventions (its off-thread answers): 1/0, out-pointers written only on
// success, 0 / -1 for "no context" or "unknown", nothing thrown back at a plugin.
// ============================================================================
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Headless.Host.Objects;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
using RynthCore.PluginSdk;
namespace RynthCore.Headless.Host;
internal static unsafe partial class HostApi
{
// ANSI slots (HostContext.Ansi) owned by this area.
private const int AnsiObjectName = 100, AnsiStringProperty = 101;
static partial void FillObjects(RynthCoreApiNative* api)
{
api->GetObjectNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, IntPtr>)&ObjGetName;
api->GetObjectPositionFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, float*, float*, float*, int>)&ObjGetPosition;
api->GetItemTypeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int>)&ObjGetItemType;
api->ObjectIsAttackableFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjIsAttackable;
api->GetObjectBitfieldFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&ObjGetBitfield;
api->GetObjectWcidFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint>)&ObjGetWcid;
api->GetObjectIntPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int>)&ObjGetInt;
api->GetObjectBoolPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int>)&ObjGetBool;
api->GetObjectDoublePropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, double*, int>)&ObjGetDouble;
api->GetObjectQuadPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, long*, int>)&ObjGetQuad;
api->GetObjectStringPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, IntPtr>)&ObjGetString;
api->GetObjectDataIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&ObjGetDataId;
api->GetObjectInstanceIdPropertyFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&ObjGetInstanceId;
api->GetObjectWielderInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, int>)&ObjGetWielderInfo;
api->GetObjectOwnershipInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, int>)&ObjGetOwnershipInfo;
api->GetContainerContentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&ObjGetContainerContents;
api->GetNumContainedItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjNumContainedItems;
api->GetNumContainedContainersFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjNumContainedContainers;
api->GetLiveObjectIdsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&ObjGetLiveIds;
api->RequestIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjRequestId;
api->HasAppraisalDataFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjHasAppraisalData;
api->GetLastIdTimeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, long>)&ObjGetLastIdTime;
api->GetObjectSpellIdsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int, int>)&ObjGetSpellIds;
api->GetTargetVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, uint*, uint*, uint*, uint*, int>)&ObjGetTargetVitals;
api->GetObjectHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, float*, int>)&ObjGetHeading;
api->GetObjectStateFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, int>)&ObjGetState;
api->GetObjectMotionOnFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int*, int>)&ObjGetMotionOn;
api->GetObjectServerAgeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjGetServerAge;
api->RemoveClientObjectFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int>)&ObjRemoveClientObject;
api->GetObjectPropertiesFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, byte*, int, int>)&ObjGetProperties;
api->GetObjectPalettesFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, uint*, int, int>)&ObjGetPalettes;
api->GetContainerOrderFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, int, uint*, int, int>)&ObjGetContainerOrder;
api->GetWieldedItemsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, int, int>)&ObjGetWieldedItems;
}
/// <summary>The object, when there is a context and the world model has it.</summary>
private static WorldObject? ObjFind(uint id, out HostContext? c)
{
c = Ctx;
return c == null || id == 0 ? null : c.World.Get(id);
}
/// <summary>The object, only once the server created it (not a stub an inventory event made).</summary>
private static WorldObject? ObjCreated(uint id, out HostContext? c)
{
WorldObject? o = ObjFind(id, out c);
return o != null && ObjectProps.Created(o) ? o : null;
}
// ── identity ────────────────────────────────────────────────────────────
/// <summary>The object's name (host-owned ANSI, valid until the next call on this thread); 0 when unknown.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr ObjGetName(uint id)
{
try
{
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetString(o, 1, out string name)) return IntPtr.Zero;
return HostContext.Ansi(AnsiObjectName, name);
}
catch { return IntPtr.Zero; }
}
/// <summary>The landcell and cell-local x, y, z; 0 for an object with no place in the world (in a pack, wielded).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetPosition(uint id, uint* cell, float* x, float* y, float* z)
{
try
{
if (cell == null || x == null || y == null || z == null) return 0;
if (ObjFind(id, out _)?.Position is not { } p) return 0;
*cell = p.Cell; *x = p.X; *y = p.Y; *z = p.Z;
return 1;
}
catch { return 0; }
}
/// <summary>ItemType flags: the header's, else an identify's (int 1); an object with neither answers 0.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetItemType(uint id, uint* flags)
{
try
{
if (flags == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null) return 0;
uint t = o.Desc.ItemType;
if (t == 0 && o.TryGetInt(1, out int it)) t = (uint)it;
if (t == 0 && !ObjectProps.Created(o)) return 0;
*flags = t;
return 1;
}
catch { return 0; }
}
/// <summary>See <see cref="ObjectProps.IsAttackable"/>: the Attackable bit, never the player, other players only PK vs PK.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjIsAttackable(uint id)
{
try
{
WorldObject? o = ObjCreated(id, out HostContext? c);
return o != null && ObjectProps.IsAttackable(o, c!.World.PlayerObject) ? 1 : 0;
}
catch { return 0; }
}
/// <summary>ObjectDescriptionFlags from the header; 0 when unknown.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint ObjGetBitfield(uint id)
{
try { return ObjCreated(id, out _)?.Desc.DescriptionFlags ?? 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint ObjGetWcid(uint id)
{
try { return ObjCreated(id, out _)?.Desc.WeenieClassId ?? 0; }
catch { return 0; }
}
// ── properties ──────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetInt(uint id, uint stype, int* value)
{
try
{
if (value == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetInt(o, stype, out int v)) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetBool(uint id, uint stype, int* value)
{
try
{
if (value == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetBool(o, stype, out bool v)) return 0;
*value = v ? 1 : 0;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetDouble(uint id, uint stype, double* value)
{
try
{
if (value == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetFloat(o, stype, out double v)) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetQuad(uint id, uint stype, long* value)
{
try
{
if (value == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetInt64(o, stype, out long v)) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
/// <summary>Host-owned ANSI (valid until the next call on this thread); 0 when unknown or empty.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr ObjGetString(uint id, uint stype)
{
try
{
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetString(o, stype, out string v)) return IntPtr.Zero;
return HostContext.Ansi(AnsiStringProperty, v);
}
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetDataId(uint id, uint stype, uint* value)
{
try
{
if (value == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetDataId(o, stype, out uint v)) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetInstanceId(uint id, uint stype, uint* value)
{
try
{
if (value == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null || !ObjectProps.TryGetInstanceId(o, stype, out uint v)) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
// ── ownership and containers ────────────────────────────────────────────
/// <summary>Wielder and EquipMask location (both 0 when not wielded); 0 for an unknown object.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetWielderInfo(uint id, uint* wielder, uint* location)
{
try
{
if (wielder == null || location == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null) return 0;
*wielder = o.WielderId;
*location = o.WieldedLocation;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetOwnershipInfo(uint id, uint* container, uint* wielder, uint* location)
{
try
{
if (container == null || wielder == null || location == null) return 0;
WorldObject? o = ObjFind(id, out _);
if (o == null) return 0;
*container = o.ContainerId;
*wielder = o.WielderId;
*location = o.WieldedLocation;
return 1;
}
catch { return 0; }
}
/// <summary>
/// The ids whose container OR wielder is <paramref name="containerId"/> (a pack's items, a creature's
/// gear), ascending; writes at most maxCount (the lowest ids) and returns how many it wrote.
/// </summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetContainerContents(uint containerId, uint* ids, int maxCount)
{
try
{
if (ids == null || maxCount <= 0 || containerId == 0) return 0;
HostContext? c = Ctx;
if (c == null) return 0;
var list = new List<uint>();
foreach (WorldObject o in c.World.Objects.Values)
if (o.Id != containerId && (o.ContainerId == containerId || o.WielderId == containerId)) list.Add(o.Id);
list.Sort();
int n = Math.Min(list.Count, maxCount);
for (int i = 0; i < n; i++) ids[i] = list[i];
return n;
}
catch { return 0; }
}
/// <summary>Ordinary items directly inside (the player: the main pack's item list); -1 for an unknown object.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjNumContainedItems(uint id)
{
try { return ObjContainedCount(id, containers: false); }
catch { return -1; }
}
/// <summary>Packs and foci directly inside (the player: the pack column); -1 for an unknown object.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjNumContainedContainers(uint id)
{
try { return ObjContainedCount(id, containers: true); }
catch { return -1; }
}
private static int ObjContainedCount(uint id, bool containers)
{
WorldObject? o = ObjFind(id, out HostContext? c);
if (o == null) return -1;
PlayerState p = c!.World.Player;
if (id == p.Id && p.DescriptionReceived)
return containers ? p.SidePackOrder.Count : p.MainPackOrder.Count;
// Packs and foci take a pack slot (foci are no containers: RequiresPackSlot 0x800000 marks them).
int n = 0;
foreach (WorldObject x in c.World.Objects.Values)
if (x.Id != id && x.ContainerId == id && (x.IsContainer || (x.Desc.DescriptionFlags & 0x800000) != 0) == containers) n++;
return n;
}
/// <summary>v69: every object the server created (ascending); returns the total, copying up to capacity.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetLiveIds(uint* buffer, int capacity)
{
try
{
HostContext? c = Ctx;
if (c == null) return 0;
var list = new List<uint>(c.World.Objects.Count);
foreach (WorldObject o in c.World.Objects.Values)
if (ObjectProps.Created(o)) list.Add(o.Id);
list.Sort();
if (buffer != null && capacity > 0)
{
int n = Math.Min(capacity, list.Count);
for (int i = 0; i < n; i++) buffer[i] = list[i];
}
return list.Count;
}
catch { return 0; }
}
// ── identify ────────────────────────────────────────────────────────────
/// <summary>Sends an identify (game action 0xC8) while in the world; 1 sent.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjRequestId(uint id)
{
try
{
HostContext? c = Ctx;
if (c == null || id == 0 || c.Session.State != Session.SessionState.InWorld) return 0;
c.Session.Identify(id);
return 1;
}
catch { return 0; }
}
/// <summary>1 once an identify reply (successful or not) came for the object this session.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjHasAppraisalData(uint id)
{
try { return Ctx?.HasAppraisalData(id) == true ? 1 : 0; }
catch { return 0; }
}
/// <summary>Unix seconds of the last identify reply; 0 never.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static long ObjGetLastIdTime(uint id)
{
try { return Ctx?.LastIdTime(id) ?? 0; }
catch { return 0; }
}
/// <summary>The last identify's spell book: the total count (copying up to maxCount), -1 when there is none.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetSpellIds(uint id, uint* spellIds, int maxCount)
{
try
{
if (spellIds == null || maxCount <= 0) return -1;
uint[]? spells = Ctx?.IdentifySpells(id);
if (spells == null || spells.Length == 0) return -1;
int n = Math.Min(spells.Length, maxCount);
for (int i = 0; i < n; i++) spellIds[i] = spells[i];
return spells.Length;
}
catch { return -1; }
}
/// <summary>A creature's vitals from its identify's creature profile (health kept current by UpdateHealth); 0 when none.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetTargetVitals(uint id, uint* health, uint* maxHealth, uint* stamina, uint* maxStamina, uint* mana, uint* maxMana)
{
try
{
if (health == null || maxHealth == null || stamina == null || maxStamina == null || mana == null || maxMana == null) return 0;
HostContext? c = Ctx;
if (c == null || id == 0 || !c.TryGetTargetVitals(id, out HostContext.TargetVitals v)) return 0;
*health = v.Health; *maxHealth = v.MaxHealth;
*stamina = v.Stamina; *maxStamina = v.MaxStamina;
*mana = v.Mana; *maxMana = v.MaxMana;
return 1;
}
catch { return 0; }
}
// ── physics ─────────────────────────────────────────────────────────────
/// <summary>Compass heading 0..360 (0 north, clockwise) from the object's rotation; 0 with no position.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetHeading(uint id, float* heading)
{
try
{
if (heading == null) return 0;
if (ObjFind(id, out _)?.Position is not { } p) return 0;
*heading = ObjectProps.Heading(p.Qw, p.Qz);
return 1;
}
catch { return 0; }
}
/// <summary>PhysicsState (CreateObject, then SetState: Ethereal 0x4 = an open door).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetState(uint id, uint* state)
{
try
{
if (state == null) return 0;
WorldObject? o = ObjCreated(id, out _);
if (o == null) return 0;
*state = o.PhysicsState;
return 1;
}
catch { return 0; }
}
/// <summary>A door's / lever's last On / Off motion from UpdateMotion; 0 when none was seen.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetMotionOn(uint id, int* isOn)
{
try
{
if (isOn == null) return 0;
HostContext? c = Ctx;
if (c == null || !c.TryGetMotionOn(id, out bool on)) return 0;
*isOn = on ? 1 : 0;
return 1;
}
catch { return 0; }
}
/// <summary>v83: ms since the server's last message about the object (capped); -1 none seen.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetServerAge(uint id)
{
try
{
HostContext? c = Ctx;
if (c == null || id == 0) return -1;
long age = c.ServerAgeMs(id);
return age < 0 ? -1 : (int)Math.Min(age, int.MaxValue);
}
catch { return -1; }
}
/// <summary>v83: drops a ghost creature (1 removed, 0 refused; -1 without a context).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjRemoveClientObject(uint id)
{
try
{
HostContext? c = Ctx;
return c == null ? -1 : c.RemoveClientObject(id);
}
catch { return 0; }
}
/// <summary>v84: the property record's size (copied when it fits); 0 unknown object; -1 bad arguments.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetProperties(uint id, byte* buffer, int size)
{
try
{
if (id == 0 || size < 0 || (buffer == null && size > 0)) return -1;
WorldObject? o = ObjFind(id, out HostContext? c);
if (o == null) return 0;
byte[]? rec = ObjectProps.Record(o, id == c!.World.Player.Id, c.HasAppraisalData(id), c.LastIdTime(id), c.IdentifySpells(id));
if (rec == null) return 0;
if (rec.Length <= size) rec.AsSpan().CopyTo(new Span<byte>(buffer, size));
return rec.Length;
}
catch { return -1; }
}
/// <summary>No ObjDesc palettes are kept (CreateObject's model data is skipped): always -1, "no data".</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetPalettes(uint id, uint* subIds, uint* offsets, int maxCount) => -1;
/// <summary>
/// v80: the player's main pack in server slot order (slotKind 0: ordinary items; 1: side packs
/// and foci). -1 for any other container (no full list kept) or bad arguments.
/// </summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetContainerOrder(uint containerId, int slotKind, uint* ids, int maxIds)
{
try
{
if (containerId == 0 || slotKind is < 0 or > 1 || maxIds < 0 || (ids == null && maxIds > 0)) return -1;
HostContext? c = Ctx;
if (c == null) return -1;
PlayerState p = c.World.Player;
if (containerId != p.Id || !p.DescriptionReceived) return -1;
IReadOnlyList<uint> order = slotKind == 1 ? p.SidePackOrder : p.MainPackOrder;
int n = Math.Min(order.Count, maxIds);
for (int i = 0; i < n; i++) ids[i] = order[i];
return order.Count;
}
catch { return -1; }
}
/// <summary>
/// v87: what the player wields and where (EquipMask): PlayerDescription's equipped list kept by
/// WieldObject / PutObjInContainer / PutObjectIn3D, plus anything the world model shows wielded by
/// the player in no container; ascending by id. -1 with no player yet or bad arguments.
/// </summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ObjGetWieldedItems(uint* ids, uint* locations, int max)
{
try
{
if (ids == null || locations == null || max <= 0) return -1;
HostContext? c = Ctx;
if (c == null) return -1;
PlayerState p = c.World.Player;
if (p.Id == 0 || !p.DescriptionReceived) return -1;
var all = new SortedDictionary<uint, uint>();
foreach (var kv in p.EquippedItems) all[kv.Key] = kv.Value;
foreach (WorldObject o in c.World.Objects.Values)
if (o.WielderId == p.Id && o.ContainerId == 0 && o.WieldedLocation != 0 && o.Id != p.Id)
all.TryAdd(o.Id, o.WieldedLocation);
int n = 0;
foreach (var kv in all)
{
if (n >= max) break;
ids[n] = kv.Key;
locations[n] = kv.Value;
n++;
}
return n;
}
catch { return -1; }
}
}

View file

@ -0,0 +1,348 @@
// ============================================================================
// RynthCore.Headless - Host/HostApi.Player.cs
// The PLAYER slots: vitals, attributes, skills, spellbook, enchantments, the server
// clock, and the player's pose / heading / map coordinates.
//
// Values follow the engine's off-thread answers (what plugins see there):
// GetPlayerVitals current + BUFFED max (enchantments and vitae), as AC's bars
// GetPlayerBaseVitals unbuffed max (formula of base attributes + init + ranks)
// GetObjectAttribute raw 1 = base (init + ranks), raw 0 = buffed
// GetObjectAttribute2ndBaseLevel 1/3/5 = unbuffed max health/stamina/mana,
// 2/4/6 = the current value
// GetObjectSkill BUFFED level + training (0 inactive, 1 untrained, 2 trained,
// 3 specialized); GetObjectSkillBuffed raw 1 = base, 0 = buffed
// ReadPlayerEnchantments spell id + expiry in server seconds (double.MaxValue for no
// duration); vitae left out; count written, -1 when unknown
// GetServerTime last time sync + local time since (0 before the first)
// GetPlayerHeading 0 = east, counter-clockwise (the engine's NormalizeDecalHeading
// of AC's compass heading); the pose's quaternion is compass
// GetCurCoords EW = (lbX * 8 + x / 24 - 1019.5) / 10, NS likewise with lbY / y
// Only the player is known this well: other objects answer "unavailable" (0 / -1).
// Character titles aren't tracked: -1 (the SDK reads that as "not received").
// ============================================================================
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Headless.Host.Player;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
using RynthCore.PluginSdk;
namespace RynthCore.Headless.Host;
internal static unsafe partial class HostApi
{
static partial void FillPlayer(RynthCoreApiNative* api)
{
api->GetPlayerVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, uint*, uint*, uint*, uint*, int>)&GetPlayerVitals;
api->GetPlayerBaseVitalsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, uint*, uint*, int>)&GetPlayerBaseVitals;
api->GetObjectAttribute2ndBaseLevelFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, uint*, int>)&GetObjectAttribute2ndBaseLevel;
api->GetObjectSkillFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int*, int*, int>)&GetObjectSkill;
api->GetObjectSkillBuffedFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, int*, int>)&GetObjectSkillLevel;
api->GetObjectAttributeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int, uint*, int>)&GetObjectAttribute;
api->GetVitaeFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, float>)&GetVitae;
api->IsSpellKnownFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint, int>)&IsSpellKnown;
api->ReadKnownSpellsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, int>)&ReadKnownSpells;
api->ReadPlayerEnchantmentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, double*, int, int>)&ReadPlayerEnchantments;
api->ReadObjectEnchantmentsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint, uint*, double*, int, int>)&ReadObjectEnchantments;
api->GetServerTimeFn = (IntPtr)(delegate* unmanaged[Cdecl]<double>)&GetServerTime;
api->GetPlayerPoseFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, float*, float*, float*, float*, float*, float*, float*, int>)&GetPlayerPose;
api->GetPlayerHeadingFn = (IntPtr)(delegate* unmanaged[Cdecl]<float*, int>)&GetPlayerHeading;
api->GetCurCoordsFn = (IntPtr)(delegate* unmanaged[Cdecl]<double*, double*, int>)&GetCurCoords;
api->GetCharacterTitlesFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint*, int, uint*, int>)&GetCharacterTitles;
}
/// <summary>The context when the player's description is known (and, with an id, that id is the player).</summary>
private static HostContext? OwnPlayerCtx(uint objectId = 0)
{
HostContext? c = Ctx;
if (c == null || !c.PlayerKnown) return null;
if (objectId != 0 && objectId != c.World.Player.Id) return null;
return c;
}
// ── vitals ──────────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPlayerVitals(uint* health, uint* maxHealth, uint* stamina, uint* maxStamina, uint* mana, uint* maxMana)
{
try
{
if (health == null || maxHealth == null || stamina == null || maxStamina == null || mana == null || maxMana == null) return 0;
HostContext? c = OwnPlayerCtx();
if (c == null) return 0;
CharacterSheet s = c.Sheet();
if (!s.HasVital(1)) return 0;
uint h = s.VitalCurrent(1), mh = s.VitalBuffedMax(1);
uint st = s.VitalCurrent(2), mst = s.VitalBuffedMax(2);
uint m = s.VitalCurrent(3), mm = s.VitalBuffedMax(3);
*health = h; *maxHealth = mh;
*stamina = st; *maxStamina = mst;
*mana = m; *maxMana = mm;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPlayerBaseVitals(uint* baseMaxHp, uint* baseMaxStam, uint* baseMaxMana)
{
try
{
if (baseMaxHp == null || baseMaxStam == null || baseMaxMana == null) return 0;
HostContext? c = OwnPlayerCtx();
if (c == null) return 0;
CharacterSheet s = c.Sheet();
uint hp = s.VitalBaseMax(1), st = s.VitalBaseMax(2), mn = s.VitalBaseMax(3);
if (hp == 0 && st == 0 && mn == 0) return 0;
*baseMaxHp = hp; *baseMaxStam = st; *baseMaxMana = mn;
return 1;
}
catch { return 0; }
}
/// <summary>stype: 1 MaxHealth, 2 Health, 3 MaxStamina, 4 Stamina, 5 MaxMana, 6 Mana.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectAttribute2ndBaseLevel(uint objectId, uint stype, uint* value)
{
try
{
if (value == null || stype < 1 || stype > 6 || objectId == 0) return 0;
HostContext? c = OwnPlayerCtx(objectId);
if (c == null) return 0;
CharacterSheet s = c.Sheet();
uint vital = (stype + 1) / 2;
if (!s.HasVital(vital)) return 0;
uint v = (stype & 1) != 0 ? s.VitalBaseMax(vital) : s.VitalCurrent(vital);
if (v == 0) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static float GetVitae(uint playerId)
{
try
{
HostContext? c = OwnPlayerCtx(playerId);
return c == null || playerId == 0 ? 1.0f : c.Sheet().Vitae;
}
catch { return 1.0f; }
}
// ── attributes and skills ───────────────────────────────────────────────
/// <summary>stype 1 Strength .. 6 Self; raw 1 = base (init + ranks), 0 = buffed.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectAttribute(uint objectId, uint stype, int raw, uint* value)
{
try
{
if (value == null || stype < 1 || stype > 6 || objectId == 0) return 0;
HostContext? c = OwnPlayerCtx(objectId);
if (c == null) return 0;
CharacterSheet s = c.Sheet();
if (!s.HasAttribute(stype)) return 0;
uint v = raw != 0 ? s.AttributeBase(stype) : s.AttributeBuffed(stype);
if (v == 0) return 0;
*value = v;
return 1;
}
catch { return 0; }
}
/// <summary>The buffed level and the training class (0 inactive, 1 untrained, 2 trained, 3 specialized).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectSkill(uint objectId, uint skill, int* buffed, int* training)
{
try
{
if (buffed == null || training == null || objectId == 0) return 0;
HostContext? c = OwnPlayerCtx(objectId);
if (c == null) return 0;
CharacterSheet s = c.Sheet();
if (!s.TryGetSkill(skill, out SkillInfo si)) return 0;
int level = s.SkillBuffed(si);
*buffed = level;
*training = (int)si.Training;
return 1;
}
catch { return 0; }
}
/// <summary>raw 1 = base (attributes unbuffed, no enchantments), 0 = buffed.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetObjectSkillLevel(uint objectId, uint skill, int raw, int* level)
{
try
{
if (level == null || objectId == 0) return 0;
HostContext? c = OwnPlayerCtx(objectId);
if (c == null) return 0;
CharacterSheet s = c.Sheet();
if (!s.TryGetSkill(skill, out SkillInfo si)) return 0;
*level = raw != 0 ? s.SkillBase(si) : s.SkillBuffed(si);
return 1;
}
catch { return 0; }
}
// ── spells ──────────────────────────────────────────────────────────────
/// <summary>1 known, 0 not, -1 unknown (not the player / no description yet).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsSpellKnown(uint objectId, uint spellId)
{
try
{
if (objectId == 0) return -1;
HostContext? c = OwnPlayerCtx(objectId);
if (c == null) return -1;
return c.World.Player.Spells.Contains(spellId) ? 1 : 0;
}
catch { return -1; }
}
/// <summary>The spellbook (ascending ids); the count written, -1 when unknown or empty.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReadKnownSpells(uint* spellIds, int maxCount)
{
try
{
if (spellIds == null || maxCount <= 0) return -1;
HostContext? c = OwnPlayerCtx();
if (c == null) return -1;
uint[] book = c.World.Player.Spells.ToArray();
if (book.Length == 0) return -1;
Array.Sort(book);
int n = Math.Min(book.Length, maxCount);
for (int i = 0; i < n; i++) spellIds[i] = book[i];
return n;
}
catch { return -1; }
}
// ── enchantments ────────────────────────────────────────────────────────
private static int CopyOwnEnchantments(HostContext c, uint* spellIds, double* expiryTimes, int maxCount)
{
Enchantment[] list = c.World.Player.Enchantments.ToArray();
int n = 0;
foreach (Enchantment e in list)
{
if (n >= maxCount) break;
if (e.SpellId == CharacterSheet.VitaeSpell || e.SpellId == 0) continue;
spellIds[n] = e.SpellId;
expiryTimes[n] = c.EnchantmentExpiry(e);
n++;
}
return n;
}
/// <summary>The player's enchantments: spell id + expiry (server seconds). Count written; -1 when unknown.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReadPlayerEnchantments(uint* spellIds, double* expiryTimes, int maxCount)
{
try
{
if (maxCount <= 0) return 0;
if (spellIds == null || expiryTimes == null) return -1;
HostContext? c = OwnPlayerCtx();
return c == null ? -1 : CopyOwnEnchantments(c, spellIds, expiryTimes, maxCount);
}
catch { return -1; }
}
/// <summary>Only the player's own registry is known; any other object is -1 (unavailable).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int ReadObjectEnchantments(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
{
try
{
if (maxCount <= 0) return 0;
if (spellIds == null || expiryTimes == null || objectId == 0) return -1;
HostContext? c = OwnPlayerCtx(objectId);
return c == null ? -1 : CopyOwnEnchantments(c, spellIds, expiryTimes, maxCount);
}
catch { return -1; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static double GetServerTime()
{
try { return Ctx?.ServerTimeNow ?? 0; }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCharacterTitles(uint* ids, int maxCount, uint* currentTitle) => -1;
// ── pose ────────────────────────────────────────────────────────────────
private static bool TryOwnPosition(out WorldPosition p)
{
p = default;
HostContext? c = Ctx;
if (c == null || c.World.Player.Id == 0) return false;
if (c.World.PlayerObject?.Position is not { } pos || pos.Cell == 0) return false;
p = pos;
return true;
}
/// <summary>0 = east, counter-clockwise (degrees), from a yaw quaternion (AC's compass yaw: 0 = north, clockwise).</summary>
internal static float DecalHeadingFromQuaternion(float qw, float qz)
{
double yaw = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI); // counter-clockwise from north
double h = 90.0 + yaw;
h %= 360.0;
if (h < 0) h += 360.0;
if (h >= 360.0) h -= 360.0;
return (float)h;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPlayerPose(uint* objCellId, float* x, float* y, float* z, float* qw, float* qx, float* qy, float* qz)
{
try
{
if (objCellId == null || x == null || y == null || z == null || qw == null || qx == null || qy == null || qz == null) return 0;
if (!TryOwnPosition(out WorldPosition p)) return 0;
*objCellId = p.Cell;
*x = p.X; *y = p.Y; *z = p.Z;
*qw = p.Qw; *qx = p.Qx; *qy = p.Qy; *qz = p.Qz;
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPlayerHeading(float* headingDegrees)
{
try
{
if (headingDegrees == null) return 0;
if (!TryOwnPosition(out WorldPosition p)) return 0;
*headingDegrees = DecalHeadingFromQuaternion(p.Qw, p.Qz);
return 1;
}
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetCurCoords(double* northSouth, double* eastWest)
{
try
{
if (northSouth == null || eastWest == null) return 0;
if (!TryOwnPosition(out WorldPosition p)) return 0;
int lbX = (int)((p.Cell >> 24) & 0xFF);
int lbY = (int)((p.Cell >> 16) & 0xFF);
*eastWest = (lbX * 8.0 + p.X / 24.0 - 1019.5) / 10.0;
*northSouth = (lbY * 8.0 + p.Y / 24.0 - 1019.5) / 10.0;
return 1;
}
catch { return 0; }
}
}

View file

@ -0,0 +1,194 @@
// ============================================================================
// RynthCore.Headless - Host/HostApi.cs
// The RynthCore plugin API table (RynthCoreApiNative, version 92) for headless
// plugins. Each area fills its own slots from its own file (HostApi.Objects.cs,
// HostApi.Player.cs, HostApi.Actions.cs, ...); a slot left empty reads as "not
// available" to the SDK's Has* checks, which is the right answer for everything this
// host has no counterpart for (ImGui, D3D, the window, retail panels, shortcuts).
//
// Conventions follow the engine (its off-thread behaviour, since plugins never run on
// AC's thread there either): 1/0 for true/false, out-pointers written only on success,
// host-owned ANSI strings (HostContext.Ansi), UTF-16 chat text.
// Every function finds its character through HostContext.Current.
// ============================================================================
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginSdk;
namespace RynthCore.Headless.Host;
internal static unsafe partial class HostApi
{
public const uint ApiVersion = 92;
// Client hook flags the engine reports (bits 0..16); everything this host implements.
private const uint AllClientHooks = 0x1FFFF;
public static RynthCoreApiNative* Build()
{
var api = (RynthCoreApiNative*)Marshal.AllocHGlobal(sizeof(RynthCoreApiNative));
Unsafe.InitBlockUnaligned(api, 0, (uint)sizeof(RynthCoreApiNative));
api->Version = ApiVersion;
FillCore(api);
FillObjects(api);
FillPlayer(api);
FillActions(api);
return api;
}
static partial void FillObjects(RynthCoreApiNative* api);
static partial void FillPlayer(RynthCoreApiNative* api);
static partial void FillActions(RynthCoreApiNative* api);
private static HostContext? Ctx => HostContext.Current;
// ── core ────────────────────────────────────────────────────────────────
private static void FillCore(RynthCoreApiNative* api)
{
api->LogFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, void>)&Log;
api->ProbeClientHooksFn = (IntPtr)(delegate* unmanaged[Cdecl]<void>)&Nop;
api->GetClientHookFlagsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetClientHookFlags;
api->GetPlayerIdFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&GetPlayerId;
api->GetAccountNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetAccountName;
api->GetWorldNameFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetWorldName;
api->GetScreenModeFn = (IntPtr)(delegate* unmanaged[Cdecl]<int*, int>)&GetScreenMode;
api->GetUiHookFlagsFn = (IntPtr)(delegate* unmanaged[Cdecl]<uint>)&Zero;
api->SetFpsLimitFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, int, int, void>)&SetFpsLimit;
api->SetRadarSuppressedFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, void>)&NopInt;
api->SetPowerbarSuppressedFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, void>)&NopInt;
api->SetChatSuppressedFn = (IntPtr)(delegate* unmanaged[Cdecl]<int, void>)&NopInt;
api->IsPortalingFn = (IntPtr)(delegate* unmanaged[Cdecl]<int>)&IsPortaling;
api->GetServerInfoFn = (IntPtr)(delegate* unmanaged[Cdecl]<byte*, int, int>)&GetServerInfo;
api->GetEngineStatusJsonFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr>)&GetEngineStatusJson;
api->SendPluginCommandFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr, int>)&SendPluginCommand;
api->GetPluginSnapshotJsonFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr>)&GetPluginSnapshotJson;
api->GetPluginInterfaceFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint, IntPtr>)&GetPluginInterface;
api->GetPluginExportJsonFn = (IntPtr)(delegate* unmanaged[Cdecl]<IntPtr, IntPtr, IntPtr>)&GetPluginExportJson;
}
/// <summary>A named plugin's parameterless RynthPluginGet*Json export (its buffer), as the engine brokers it.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetPluginExportJson(IntPtr plugin, IntPtr export)
{
try
{
HostContext? c = Ctx;
string? name = plugin != IntPtr.Zero ? Marshal.PtrToStringAnsi(plugin) : null;
string? exp = export != IntPtr.Zero ? Marshal.PtrToStringAnsi(export) : null;
if (c?.Plugins == null || name == null || exp == null) return IntPtr.Zero;
if (!exp.StartsWith("RynthPluginGet", StringComparison.Ordinal) || !exp.EndsWith("Json", StringComparison.Ordinal)) return IntPtr.Zero;
IntPtr fn = c.Plugins.FindExport(name, exp);
return fn == IntPtr.Zero ? IntPtr.Zero : ((delegate* unmanaged[Cdecl]<IntPtr>)fn)();
}
catch { return IntPtr.Zero; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void Log(IntPtr message)
{
string? s = message != IntPtr.Zero ? Marshal.PtrToStringAnsi(message) : null;
if (s != null) Ctx?.Log("[Plugin] " + s);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void Nop() { }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void NopInt(int _) { }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint Zero() => 0;
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static void SetFpsLimit(int a, int b, int c) { }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetClientHookFlags() => AllClientHooks;
/// <summary>The player's id while in the world; 0 otherwise (plugins tear their session down on 0).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static uint GetPlayerId()
{
HostContext? c = Ctx;
return c != null && c.Session.State == Session.SessionState.InWorld ? c.World.Player.Id : 0;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetAccountName() => HostContext.Ansi(1, Ctx?.AccountName);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetWorldName() => HostContext.Ansi(2, Ctx?.Session.WorldName);
/// <summary>0x10000008 = in the world (the engine's value), 0 otherwise.</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetScreenMode(int* mode)
{
if (mode == null) return 0;
HostContext? c = Ctx;
*mode = c != null && c.Session.State == Session.SessionState.InWorld ? 0x10000008 : 0;
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int IsPortaling() => Ctx?.Portaling == true ? 1 : 0;
/// <summary>Flags: bit0 Aelrynth, bit1 staging, bit2 world name known (copied UTF-8 into the buffer).</summary>
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetServerInfo(byte* name, int capacity)
{
HostContext? c = Ctx;
string world = c?.Session.WorldName ?? "";
int flags = 0;
if (world.Length > 0 && HostContext.Utf8(world, name, capacity) >= 0) flags |= 4;
return flags;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetEngineStatusJson()
{
HostContext? c = Ctx;
string json = c == null ? "{}" :
$"{{\"host\":\"headless\",\"inWorld\":{(c.Session.State == Session.SessionState.InWorld ? "true" : "false")},\"playerId\":{c.World.Player.Id},\"objects\":{c.World.Objects.Count}}}";
return HostContext.Ansi(3, json);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value)
{
HostContext? c = Ctx;
string? name = plugin != IntPtr.Zero ? Marshal.PtrToStringAnsi(plugin) : null;
if (c?.Plugins == null || name == null) return 0;
IntPtr fn = c.Plugins.FindExport(name, "RynthPluginApplyRemoteCommand");
if (fn == IntPtr.Zero) return 0;
((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)fn)(action, value);
return 1;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetPluginSnapshotJson(IntPtr plugin)
{
HostContext? c = Ctx;
string? name = plugin != IntPtr.Zero ? Marshal.PtrToStringAnsi(plugin) : null;
if (c?.Plugins == null || name == null) return IntPtr.Zero;
IntPtr fn = c.Plugins.FindExport(name, "RynthPluginGetSnapshotJson");
return fn == IntPtr.Zero ? IntPtr.Zero : ((delegate* unmanaged[Cdecl]<IntPtr>)fn)();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr GetPluginInterface(IntPtr plugin, IntPtr iface, uint version)
{
HostContext? c = Ctx;
string? name = plugin != IntPtr.Zero ? Marshal.PtrToStringAnsi(plugin) : null;
if (c?.Plugins == null || name == null) return IntPtr.Zero;
IntPtr fn = c.Plugins.FindExport(name, "RynthPluginQueryInterface");
return fn == IntPtr.Zero ? IntPtr.Zero : ((delegate* unmanaged[Cdecl]<IntPtr, uint, IntPtr>)fn)(iface, version);
}
}
public sealed partial class HostContext
{
/// <summary>Between a PlayerTeleport and the LoginComplete we answer it with.</summary>
public bool Portaling { get; internal set; }
}

View file

@ -0,0 +1,158 @@
// ============================================================================
// RynthCore.Headless - Host/HostBridge.cs
// Turns one session's world model into plugin events, and drives the plugin host:
// - creates / updates (UpdateObject, state, motion, vectors, positions) / deletes;
// - containers: ViewContents of something not ours = OnViewObjectContents (and the
// ground container), every ViewContents = OnUpdateObjectInventory, a close =
// OnStopViewingObjectContents;
// - UpdateHealth, combat notices (attacker/defender damage, kills), enchantments;
// - chat as retail's chat window shows it ("X says, \"...\"", "X tells you, ...");
// - combat mode changes; teleports (IsPortaling for a moment);
// - login (once the player, its description and LoginComplete are there) and logout.
// Call Tick() from the session's loop after session.Tick().
// ============================================================================
using RynthCore.Headless.Messages;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Host;
public sealed class HostBridge
{
private readonly HostContext _ctx;
private readonly PluginHost _host;
private int _lastCombatMode = 1;
private long _portalUntil;
private bool _loggedIn;
public HostBridge(HostContext ctx, PluginHost host)
{
_ctx = ctx;
_host = host;
WorldState w = ctx.World;
HostEvents ev = ctx.Events;
w.ObjectCreated += o => ev.Enqueue(new PluginEvent.CreateObject(o.Id));
w.ObjectUpdated += o => ev.Enqueue(new PluginEvent.UpdateObject(o.Id));
w.ObjectStateChanged += o => ev.Enqueue(new PluginEvent.UpdateObject(o.Id));
w.ObjectMoved += id => ev.Enqueue(new PluginEvent.UpdateObject(id));
w.ObjectDeleted += id => ev.Enqueue(new PluginEvent.DeleteObject(id));
w.ContainerOpened += id =>
{
if (!IsOurs(id))
{
ctx.GroundContainer = id;
ev.Enqueue(new PluginEvent.ViewContents(id));
}
ev.Enqueue(new PluginEvent.UpdateObjectInventory(id));
};
w.ContainerClosed += id =>
{
if (ctx.GroundContainer == id) ctx.GroundContainer = 0;
ev.Enqueue(new PluginEvent.StopViewingContents(id));
};
w.HealthUpdated += (id, ratio) =>
{
(uint cur, uint max) = ctx.HealthOf(id, ratio);
ev.Enqueue(new PluginEvent.UpdateHealth(id, ratio, cur, max));
};
w.Combat += c =>
{
switch (c.EventType)
{
case WorldEvent.AttackerNotification when c.Damage > 0:
ev.Enqueue(new PluginEvent.CombatDamage(c.Damage, c.DamageType, c.Critical, true));
break;
case WorldEvent.DefenderNotification when c.Damage > 0:
ev.Enqueue(new PluginEvent.CombatDamage(c.Damage, c.DamageType, c.Critical, false));
break;
case WorldEvent.KillerNotification when c.Name.Length > 0:
ev.Enqueue(new PluginEvent.KillNotification(c.Name));
break;
}
};
w.EnchantmentAdded += e => ev.Enqueue(new PluginEvent.EnchantmentAdded(e.SpellId, e.Duration));
w.EnchantmentRemoved += id => ev.Enqueue(new PluginEvent.EnchantmentRemoved(id));
w.TransientMessage += t => ev.Enqueue(new PluginEvent.ChatWindowText(t, 0x05));
// Refusals that carry only a code: the line retail's chat window shows for them.
w.InventoryFailed += (_, code) => { if (RetailErrorText.For(code) is { } t) ev.Enqueue(new PluginEvent.ChatWindowText(t, 0x05)); };
w.Error += (code, text) => { if (text.Length == 0 && RetailErrorText.For(code) is { } t) ev.Enqueue(new PluginEvent.ChatWindowText(t, 0x05)); };
w.PlayerTeleported += () => _portalUntil = ctx.NowMs + 1500;
ctx.Session.Chat += line => ev.Enqueue(new PluginEvent.ChatWindowText(ChatText(line), (int)line.ChatType));
}
private bool IsOurs(uint container)
=> container == _ctx.World.Player.Id || _ctx.World.Get(container)?.ContainerId == _ctx.World.Player.Id;
/// <summary>The line as retail's chat window would print it.</summary>
public static string ChatText(ChatLine l) => l.ChatType switch
{
0x02 when l.Sender.Length > 0 => $"{l.Sender} says, \"{l.Text}\"",
0x03 when l.Sender.Length > 0 => $"{l.Sender} tells you, \"{l.Text}\"",
0x0C when l.Sender.Length > 0 => $"{l.Sender} {l.Text}",
_ => l.Text,
};
/// <summary>Call every host frame, after session.Tick().</summary>
public void Tick()
{
bool inWorld = _ctx.Session.State == SessionState.InWorld && _ctx.World.Player.DescriptionReceived && _ctx.World.PlayerObject != null;
if (inWorld && !_loggedIn)
{
_loggedIn = true;
_lastCombatMode = _ctx.CurrentCombatMode;
_host.LoginComplete();
}
else if (!inWorld && _loggedIn)
{
_loggedIn = false;
_host.Logout();
}
_ctx.Portaling = _ctx.NowMs < _portalUntil;
int mode = _ctx.CurrentCombatMode;
if (mode != _lastCombatMode)
{
_ctx.Events.Enqueue(new PluginEvent.CombatModeChange(mode, _lastCombatMode));
_lastCombatMode = mode;
}
_ctx.TickAreas();
_host.Tick();
}
}
public sealed partial class HostContext
{
/// <summary>The external container (corpse, chest) being viewed; 0 if none.</summary>
public uint GroundContainer { get; internal set; }
/// <summary>Current / max health for an UpdateHealth ratio, when the max is known (0, 0 otherwise).</summary>
public (uint Current, uint Max) HealthOf(uint id, float ratio)
{
uint max = MaxHealthOf(id);
return max == 0 ? (0u, 0u) : ((uint)MathF.Round(max * ratio), max);
}
// Areas override these (partial methods: no-op until an area provides them).
partial void MaxHealthHook(uint id, ref uint max);
public uint MaxHealthOf(uint id)
{
uint max = 0;
MaxHealthHook(id, ref max);
return max;
}
partial void TickObjects();
partial void TickPlayer();
partial void TickActions();
internal void TickAreas()
{
TickObjects();
TickPlayer();
TickActions();
}
}

View file

@ -0,0 +1,678 @@
// ============================================================================
// RynthCore.Headless - Host/HostContext.Actions.cs
// The ACTIONS area's state and logic: what the plugin API's action slots do
// (HostApi.Actions.cs is the thin unmanaged layer over this).
//
// Busy count (the engine's BusyCountHooks): +1 for every use (UseObject, UseObjectOn,
// UseEquippedItem) and cast the host sends, the acclient's m_cBusy actions, -1 for
// every server UseDone (0x01C7), each raising OnBusyCountIncremented / Decremented.
// Inventory sends (moves, splits, merges, gives, wields, closes) are not counted: the
// server answers them with the item's new place or InventoryServerSaveFailed, never a
// UseDone (the engine's raw sends don't count them either). ForceResetBusyCount drops
// the count to 0 with one decrement event per unit; a count nobody answers for
// BusyStaleMs is reset the same way (the engine's watchdog).
//
// Cast gate (GetCastBusyState): 1 from a cast until its UseDone (a fizzle ends with one
// too), at most CastGateMaxMs; there is no animation to watch here.
//
// Use-done / weenie-error sequences: as SmartBoxHooks counts them (UseDone; WeenieError
// 0x028A, WeenieErrorWithString 0x028B, InventoryServerSaveFailed 0x00A0 with its item).
//
// Selection: SelectItem (150 ms dedupe of the same target, like the engine) and
// SetSelectedObjectId; a change raises OnSelectedTargetChange(current, previous); the
// selected object leaving the world clears it.
//
// Chat: WriteToChat prints to the log and echoes the line to the plugins as chat-window
// text (as AC's chat window raises it), at most one line per WriteToChatMinMs like the
// engine's off-thread path. InvokeChatParser offers the line to every plugin's
// OnChatBarEnter (not again for a line a plugin sends from inside its own handler),
// then sends it on (Host/Actions/ChatLineRouter.cs).
//
// Confirmations: ArmConfirmation answers the next matching server prompt (0x0274) Yes
// or No by its "N percent" (the engine's ConfirmationResponder); an unarmed prompt is
// recorded as shown and left unanswered (nobody is there to click).
//
// Every clock here is the session's (Session.NowMs).
// ============================================================================
using RynthCore.Headless.Host.Actions;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Host;
public sealed partial class HostContext
{
public const long SelectDedupeMs = 150;
public const long WriteToChatMinMs = 100;
public const long CastGateMaxMs = 4000;
public const long BusyStaleMs = 20_000;
public const long ConfirmationMaxTimeoutMs = 120_000;
// MergeStackStatus codes (never renumber: ABI).
public const int MergeNone = 0, MergeQueued = 1, MergeSent = 2, MergeTargetFull = 3, MergeFailed = 4, MergeQueueFull = 5;
// ConfirmationOutcome codes (ABI).
public const int ConfirmNone = 0, ConfirmShown = 1, ConfirmAccepted = 2, ConfirmDeclined = 3, ConfirmSendFailed = 4;
private int _actBusy;
private long _actBusyChangedMs;
private int _actUseDoneSeq;
private uint _actUseDoneError;
private int _actErrorSeq;
private uint _actErrorCode, _actErrorEvent, _actErrorObject;
private long _actCastSentMs = -1;
private uint _actSelected, _actPrevSelected, _actLastSelectTarget;
private long _actLastSelectMs = long.MinValue / 2;
private long _actLastChatMs = long.MinValue / 2;
private bool _actInChatPreDispatch;
private readonly Dictionary<ulong, (int Status, int Amount, long At)> _actMerges = new();
private long _actJumpChargeMs = -1;
private bool _actArmed;
private uint _actArmedType;
private int _actArmedMinPercent;
private long _actArmedUntil;
private int _actConfirmSeq, _actConfirmPercent = -1, _actConfirmOutcome;
private uint _actConfirmType, _actConfirmContext;
private long _actConfirmAt;
private long ActNow => Session.NowMs;
private bool ActInWorld => Session.State == SessionState.InWorld && World.Player.Id != 0;
partial void InitActions()
{
World.UseDone += OnActUseDone;
World.Error += (code, text) => RecordWeenieError(text.Length > 0 ? WorldEvent.WeenieErrorWithString : WorldEvent.WeenieError, code, 0);
World.InventoryFailed += (item, err) => RecordWeenieError(WorldEvent.InventoryServerSaveFailed, err, item);
World.ObjectDeleted += id => { if (id != 0 && id == _actSelected) SetSelection(0); };
Session.RawMessage += OnActRawMessage;
Session.StateChanged += s =>
{
// Out of the world (logout, failure): nothing is owed any more (the engine's ResetSession).
if (s == SessionState.InWorld) return;
_actBusy = 0;
_actCastSentMs = -1;
_actSelected = _actPrevSelected = _actLastSelectTarget = 0;
_actArmed = false;
_actJumpChargeMs = -1;
};
}
partial void TickActions()
{
TickPendingWield();
if (_actBusy > 0 && ActNow - _actBusyChangedMs > BusyStaleMs)
{
Log($"[host] busy count {_actBusy} unanswered for {BusyStaleMs / 1000}s: reset");
ForceResetBusy();
}
}
// ── busy count, use-done, errors ────────────────────────────────────────
public int BusyCount => _actBusy;
public int UseDoneSeq => _actUseDoneSeq;
public (int Seq, uint Error) LastUseDone => (_actUseDoneSeq, _actUseDoneError);
public (int Seq, uint Error, uint EventType, uint ObjectId) LastWeenieError => (_actErrorSeq, _actErrorCode, _actErrorEvent, _actErrorObject);
/// <summary>1 while a cast waits for its UseDone (at most CastGateMaxMs), else 0.</summary>
public int CastBusyState => _actCastSentMs >= 0 && ActNow - _actCastSentMs < CastGateMaxMs ? 1 : 0;
private void BusyUp()
{
if (TraceActions) Log($"[act] busy {_actBusy} -> {_actBusy + 1}");
_actBusy++;
_actBusyChangedMs = ActNow;
Events.Enqueue(new PluginEvent.BusyIncremented());
}
private void OnActUseDone(uint error)
{
if (TraceActions) Log($"[act] UseDone 0x{error:X} (busy {_actBusy})");
_actUseDoneSeq++;
_actUseDoneError = error;
_actCastSentMs = -1;
if (_actBusy <= 0) return; // nothing of ours to pair (a use we never counted, or reset already)
_actBusy--;
_actBusyChangedMs = ActNow;
Events.Enqueue(new PluginEvent.BusyDecremented());
}
public void ForceResetBusy()
{
int was = _actBusy;
_actBusy = 0;
_actBusyChangedMs = ActNow;
for (int i = 0; i < was && i < 64; i++)
Events.Enqueue(new PluginEvent.BusyDecremented());
}
private void RecordWeenieError(uint eventType, uint code, uint objectId)
{
_actErrorSeq++;
_actErrorCode = code;
_actErrorEvent = eventType;
_actErrorObject = objectId;
}
// ── uses, casts, combat ─────────────────────────────────────────────────
/// <summary>Logs every action sent and every busy change (host diagnostics).</summary>
public bool TraceActions { get; set; }
public bool ActUse(uint obj)
{
if (!ActInWorld || obj == 0) return false;
// The retail client turns "use" on equipment it carries into a wield (GetAndWieldItem) or,
// for something already wielded, an unwield into the pack; the server never sees a Use
// for those (and ACE would ignore one). Plugins swap weapons and wands this way.
if (RetailUseOfEquipment(obj)) return true;
if (RetailUseInOpenContainer(obj)) return true;
Session.Use(obj);
BusyUp();
return true;
}
// "Use" on an item inside the open corpse or chest (or a pack in it) is a pick-up into the main pack in
// the retail client; ACE has no use for it ("couldn't find object", and a meta's /mt loot never got
// the item: a headless bot's 4Hives route, 2026-10-29).
private bool RetailUseInOpenContainer(uint obj)
{
uint open = World.OpenContainer, me = World.Player.Id;
if (open == 0 || me == 0 || World.Get(obj) is not { } o) return false;
uint holder = o.ContainerId;
if (holder != open && (holder == 0 || World.Get(holder)?.ContainerId != open)) return false;
Session.MoveItem(obj, me, 0);
return true;
}
private bool RetailUseOfEquipment(uint obj)
{
WorldObject? o = World.Get(obj);
uint me = World.Player.Id;
if (o == null || me == 0 || o.Desc.ValidLocations is not { } valid || valid == 0) return false;
if (o.WielderId == me)
{
Session.MoveItem(obj, me, 0);
return true;
}
uint holder = o.ContainerId;
bool carried = holder == me || (holder != 0 && World.Get(holder)?.ContainerId == me);
if (!carried) return false;
// A swap: ACE refuses a weapon while another is in hand (CheckWeaponCollision), so the client
// first puts away whatever holds the hands the new item needs, then wields it.
uint slot = WieldSlot(valid);
uint hands = HandsFor(slot);
var inTheWay = new List<uint>();
if (hands != 0)
foreach (var (id, loc) in World.Player.EquippedItems.ToList())
if (id != obj && (loc & hands) != 0)
{
Session.MoveItem(id, me, 0);
inTheWay.Add(id);
}
if (inTheWay.Count == 0)
{
Session.Wield(obj, slot);
return true;
}
// The wield goes out once the server has put those away (it checks the hands when the
// wield arrives); TickActions sends it, or gives up after a few seconds.
_actPendingWield = (obj, slot, inTheWay, ActNow + 4000);
return true;
}
private (uint Item, uint Slot, List<uint> Waiting, long Deadline)? _actPendingWield;
private void TickPendingWield()
{
if (_actPendingWield is not { } w) return;
uint me = World.Player.Id;
bool clear = w.Waiting.All(id => World.Get(id)?.WielderId != me);
if (clear) Session.Wield(w.Item, w.Slot);
if (clear || ActNow > w.Deadline) _actPendingWield = null;
}
private const uint MeleeWeapon = 0x100000, Shield = 0x200000, MissileWeapon = 0x400000, Held = 0x1000000, TwoHanded = 0x2000000;
private const uint Weapons = MeleeWeapon | MissileWeapon | Held | TwoHanded;
/// <summary>The wielded slots that must be emptied first: any weapon for a weapon; a shield or two-hander for a shield.</summary>
private static uint HandsFor(uint slot)
=> (slot & Weapons) != 0 ? Weapons | ((slot & TwoHanded) != 0 ? Shield : 0)
: (slot & Shield) != 0 ? Shield | TwoHanded
: 0;
/// <summary>Where a wield goes: one free side of a left/right pair (rings, bracelets), else the item's whole mask.</summary>
private uint WieldSlot(uint valid)
{
uint used = 0;
foreach (uint loc in World.Player.EquippedItems.Values) used |= loc;
foreach (uint pair in new[] { 0xC0000u /* fingers */, 0x30000u /* wrists */ })
{
if ((valid & pair) != pair) continue;
uint low = pair & ~(pair - 1), high = pair & ~low;
return (used & low) == 0 ? low : (used & high) == 0 ? high : low;
}
return valid;
}
public bool ActUseOn(uint source, uint target)
{
if (!ActInWorld || source == 0 || target == 0) return false;
Session.UseOn(source, target);
BusyUp();
return true;
}
public bool ActCast(uint target, int spellId)
{
if (!ActInWorld || spellId <= 0) return false;
// A self-targeted spell (SpellFlags 0x8) goes out untargeted, as the client's
// FreeHandsAndCastSpell sends it; anything else on its target.
bool self = target == 0 || (target == World.Player.Id && Spells?.Get((uint)spellId) is { SelfTargeted: true });
Session.Cast((uint)spellId, self ? 0 : target);
_actCastSentMs = ActNow;
BusyUp();
return true;
}
public bool ActChangeCombatMode(int mode)
{
if (!ActInWorld || mode is not (1 or 2 or 4 or 8)) return false;
Session.SetCombatMode((uint)mode);
return true;
}
public bool ActMelee(uint target, int height, float power)
{
if (!ActInWorld || target == 0 || height is < 1 or > 3 || !float.IsFinite(power)) return false;
Session.MeleeAttack(target, (uint)height, power);
return true;
}
public bool ActMissile(uint target, int height, float accuracy)
{
if (!ActInWorld || target == 0 || height is < 1 or > 3 || !float.IsFinite(accuracy)) return false;
Session.MissileAttack(target, (uint)height, accuracy);
return true;
}
/// <summary>The client's own attack on the selected target, by combat mode (melee / missile).</summary>
public bool ActNativeAttack(int height, float power)
{
if (!ActInWorld || _actSelected == 0) return false;
if (height is < 1 or > 3) height = (int)AttackHeight.Medium;
return CurrentCombatMode switch
{
2 => ActMelee(_actSelected, height, power),
4 => ActMissile(_actSelected, height, power),
_ => false,
};
}
public bool ActCancelAttack()
{
if (!ActInWorld) return false;
Session.CancelAttack();
return true;
}
public bool ActQueryHealth(uint target)
{
if (!ActInWorld || target == 0) return false;
Session.QueryHealth(target);
return true;
}
/// <summary>In the world, not portaling and no cast in flight.</summary>
public bool PlayerReady => ActInWorld && World.PlayerObject != null && !Portaling && CastBusyState == 0;
// ── inventory ───────────────────────────────────────────────────────────
/// <summary>True when <paramref name="container"/> is one of the player's own packs and it is full (the engine fails these closed).</summary>
private bool IsFullOwnedContainer(uint container, uint item)
{
uint me = World.Player.Id;
WorldObject? c = World.Get(container);
bool ours = container == me || (c != null && c.ContainerId == me);
if (!ours || c == null) return false;
if (World.Get(item)?.ContainerId == container) return false; // a move inside it
int capacity = c.Desc.ItemsCapacity ?? 0;
if (capacity <= 0) return false;
int count = World.Contents(container).Count(o => !o.IsContainer);
return count >= capacity;
}
private uint StackOf(uint id) => World.Get(id)?.StackSize is { } s && s > 0 ? s : 1;
/// <summary>Whole item, or <paramref name="amount"/> of a stack split off, into a container (slot 0).</summary>
public bool ActMoveItemExternal(uint obj, uint container, int amount)
{
if (!ActInWorld || obj == 0 || container == 0 || amount < 0) return false;
if (IsFullOwnedContainer(container, obj)) return false;
if (amount > 0 && amount < StackOf(obj)) Session.Split(obj, container, 0, amount);
else Session.MoveItem(obj, container, 0);
return true;
}
/// <summary>Whole move (0x0019) into a container at a slot.</summary>
public bool ActMoveItemInternal(uint obj, uint container, int slot, int amount)
{
if (!ActInWorld || obj == 0 || container == 0 || slot < 0 || amount <= 0) return false;
if (IsFullOwnedContainer(container, obj)) return false;
Session.MoveItem(obj, container, slot);
return true;
}
/// <summary>StackableSplitToContainer (0x0055): amount onto a slot.</summary>
public bool ActSplitStack(uint obj, uint container, int slot, int amount)
{
if (!ActInWorld || obj == 0 || container == 0 || slot < 0 || amount <= 0) return false;
Session.Split(obj, container, slot, amount);
return true;
}
/// <summary>
/// Salvage (0x027D) with a tool: the items the player carries, at most 100 (the engine's limit);
/// the count sent, 0 refused. The server answers with the salvage it made, as for the retail panel.
/// </summary>
public int ActSalvageDirect(uint tool, IReadOnlyList<uint> items)
{
if (!ActInWorld || tool == 0 || items.Count == 0 || items.Count > 100) return 0;
var carried = new HashSet<uint>(World.Inventory().Select(o => o.Id));
if (!carried.Contains(tool) || items.Any(id => id == 0 || id == tool || !carried.Contains(id))) return 0;
Session.Salvage(tool, items);
return items.Count;
}
/// <summary>PutItemInContainer (0x0019) at a placement: 1 sent, 0 refused.</summary>
public int ActPutItemInContainer(uint item, uint container, int placement)
{
if (!ActInWorld || item == 0 || container == 0 || placement < 0) return 0;
Session.MoveItem(item, container, placement);
return 1;
}
/// <summary>StackableMerge (0x0054) of as much of the source as fits the target; the outcome is kept for GetMergeStackResult.</summary>
public bool ActMergeStack(uint source, uint target)
{
if (!ActInWorld || source == 0 || target == 0 || source == target)
{
RecordMerge(source, target, MergeFailed, 0);
return false;
}
int sourceCount = (int)StackOf(source);
int targetCount = (int)(World.Get(target)?.StackSize ?? 0);
int max = MaxStackOf(source);
if (max <= 0) max = MaxStackOf(target);
int amount = sourceCount;
if (max > 0)
{
int room = max - targetCount;
if (room <= 0)
{
RecordMerge(source, target, MergeTargetFull, 0);
return false;
}
amount = Math.Min(sourceCount, room);
}
Session.Merge(source, target, amount);
RecordMerge(source, target, MergeSent, amount);
return true;
}
private int MaxStackOf(uint id)
{
WorldObject? o = World.Get(id);
if (o == null) return 0;
if (o.Desc.MaxStackSize is { } m && m > 0) return m;
return o.TryGetInt(11, out int v) ? v : 0;
}
private void RecordMerge(uint source, uint target, int status, int amount)
{
if (_actMerges.Count >= 512) _actMerges.Clear();
_actMerges[((ulong)source << 32) | target] = (status, amount, ActNow);
}
public int MergeResult(uint source, uint target, out int amount, out int ageMs)
{
amount = ageMs = 0;
if (!_actMerges.TryGetValue(((ulong)source << 32) | target, out var e)) return MergeNone;
amount = e.Amount;
ageMs = (int)Math.Clamp(ActNow - e.At, 0, int.MaxValue);
return e.Status;
}
/// <summary>GiveObjectRequest (0x00CD); amount 0 = the whole stack.</summary>
public bool ActGive(uint obj, uint target, int amount)
{
if (!ActInWorld || obj == 0 || target == 0 || amount < 0) return false;
Session.Give(target, obj, amount == 0 ? (int)StackOf(obj) : amount);
return true;
}
public bool ActWield(uint obj, uint equipMask)
{
if (!ActInWorld || obj == 0 || equipMask == 0) return false;
Session.Wield(obj, equipMask);
return true;
}
public bool ActCloseContainer(uint container)
{
if (!ActInWorld || container == 0) return false;
Session.StopViewing(container);
return true;
}
// ── selection ───────────────────────────────────────────────────────────
public uint SelectedId => _actSelected;
public uint PreviousSelectedId => _actPrevSelected;
/// <summary>The engine's SelectItem: the same target again within SelectDedupeMs is a no-op (still 1).</summary>
public bool ActSelectItem(uint obj)
{
if (!ActInWorld) return false;
long now = ActNow;
if (obj != 0 && obj == _actLastSelectTarget && now - _actLastSelectMs < SelectDedupeMs) return true;
_actLastSelectTarget = obj;
_actLastSelectMs = now;
SetSelection(obj);
return true;
}
public bool ActSetSelected(uint obj)
{
if (!ActInWorld) return false;
SetSelection(obj);
return true;
}
private void SetSelection(uint obj)
{
if (obj == _actSelected) return;
_actPrevSelected = _actSelected;
_actSelected = obj;
Events.Enqueue(new PluginEvent.SelectedTargetChange(_actSelected, _actPrevSelected));
}
// ── chat ────────────────────────────────────────────────────────────────
public bool ActWriteToChat(string? text, int chatType)
{
if (string.IsNullOrWhiteSpace(text)) return false;
string line = text.TrimEnd('\r', '\n');
if (line.Length == 0) return false;
foreach (char ch in line)
if (ch < 0x20 && ch != '\t') return false;
long now = ActNow;
if (now - _actLastChatMs < WriteToChatMinMs) return false;
_actLastChatMs = now;
Log($"[chat] {line}");
Events.Enqueue(new PluginEvent.ChatWindowText(line, chatType));
return true;
}
public bool ActInvokeChatParser(string? text)
{
string line = (text ?? "").TrimEnd('\r', '\n').Trim();
if (line.Length == 0) return false;
if (!_actInChatPreDispatch && Plugins != null)
{
_actInChatPreDispatch = true;
try
{
if (Plugins.ChatBarEnter(line)) return true;
}
finally { _actInChatPreDispatch = false; }
}
if (!ActInWorld) return false;
ChatRoute r = ChatLineRouter.Route(line);
switch (r.Kind)
{
case ChatRouteKind.Say: Session.Say(r.Text); return true;
case ChatRouteKind.Emote: Session.Emote(r.Text); return true;
case ChatRouteKind.SoulEmote: Session.SoulEmote(r.Text); return true;
case ChatRouteKind.Tell: Session.Tell(r.Target, r.Text); return true;
case ChatRouteKind.Unsupported: Log($"[host] chat '{line}' not sent: {r.Why}"); return false;
default: return false;
}
}
// ── movement ────────────────────────────────────────────────────────────
public bool ActSetAutoRun(bool on)
{
if (!ActInWorld) return false;
Session.SetAutoRun(on);
return true;
}
public bool ActSetMotion(uint motion, bool on, bool run = true)
{
if (!ActInWorld) return false;
return Session.SetDriveMotion(motion, on, run);
}
public bool ActStopCompletely()
{
if (!ActInWorld) return false;
Session.StopCompletely();
return true;
}
public bool ActTurnToHeading(float degrees)
{
if (!ActInWorld || !float.IsFinite(degrees) || World.PlayerObject?.Position == null) return false;
Session.FaceHeading(degrees);
return true;
}
// ── jumps ───────────────────────────────────────────────────────────────
/// <summary>A jump of <paramref name="extent"/> (0..1) with a horizontal velocity; the height follows ACE's formula from the Jump skill.</summary>
public bool ActJump(float extent, float vx = 0, float vy = 0)
{
if (!ActInWorld || World.PlayerObject?.Position == null || !float.IsFinite(extent)) return false;
extent = Math.Clamp(extent, 0f, 1f);
uint skill = World.Player.SkillTable.TryGetValue(22, out SkillInfo s) ? s.Init + s.Ranks : 0;
if (skill == 0) skill = 100;
float height = Math.Max(0.35f, (skill / (skill + 1300f) * 22.2f + 0.05f) * extent);
Session.Jump(extent, vx, vy, MathF.Sqrt(2f * 9.8f * height));
_actJumpChargeMs = -1;
return true;
}
public bool ActCommenceJump()
{
if (!ActInWorld) return false;
_actJumpChargeMs = ActNow;
return true;
}
/// <summary>The charge since CommenceJump (a full charge takes a second), 0 without one.</summary>
public float JumpCharge => _actJumpChargeMs < 0 ? 0f : Math.Clamp((ActNow - _actJumpChargeMs) / 1000f, 0f, 1f);
/// <summary>The charged jump with momentum from the keys: W forward, X back, Z / C strafe left / right (shift walks).</summary>
public bool ActLaunchJump(bool shift, bool w, bool x, bool z, bool c)
{
if (World.PlayerObject?.Position is not { } p) return false;
float h = ClientSession.HeadingDegrees(p) * MathF.PI / 180f;
float speed = shift ? MotionCommand.WalkSpeed : Session.MoveSpeed;
float fwd = (w ? speed : 0) - (x ? speed * ClientSession.BackwardsFactor : 0);
float side = (c ? MotionCommand.SidestepSpeed : 0) - (z ? MotionCommand.SidestepSpeed : 0);
float sin = MathF.Sin(h), cos = MathF.Cos(h);
return ActJump(JumpCharge, sin * fwd + cos * side, cos * fwd - sin * side);
}
// ── confirmations ───────────────────────────────────────────────────────
public int ActArmConfirmation(uint type, int minPercent, int timeoutMs)
{
if (timeoutMs <= 0) { _actArmed = false; return 1; }
if (type == 0 || minPercent < 0 || minPercent > 100 || timeoutMs > ConfirmationMaxTimeoutMs) return -3;
_actArmed = true;
_actArmedType = type;
_actArmedMinPercent = minPercent;
_actArmedUntil = ActNow + timeoutMs;
return 1;
}
public int LastConfirmation(out uint type, out uint context, out int percent, out int outcome, out int ageMs)
{
type = _actConfirmType;
context = _actConfirmContext;
percent = _actConfirmPercent;
outcome = _actConfirmOutcome;
ageMs = _actConfirmSeq == 0 ? 0 : (int)Math.Clamp(ActNow - _actConfirmAt, 0, int.MaxValue);
return _actConfirmSeq;
}
private void OnActRawMessage(uint opcode, ReadOnlyMemory<byte> message)
{
if (opcode != ServerOpcode.GameEvent) return;
try
{
if (!ServerMessage.TryFromWire(message.Span, out ServerMessage msg) || msg.EventType != GameEventType.ConfirmationRequest) return;
if (ConfirmationRequest.TryParse(msg.EventBody, out ConfirmationRequest req))
OnConfirmationRequest(req.ConfirmationType, req.ContextId, req.Text);
}
catch (Exception ex)
{
Log($"[host] confirmation request: {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>A server yes/no prompt: answered when armed for its type, else recorded as shown.</summary>
internal void OnConfirmationRequest(uint type, uint context, string text)
{
_actConfirmSeq++;
_actConfirmType = type;
_actConfirmContext = context;
_actConfirmPercent = ParseConfirmPercent(text);
_actConfirmAt = ActNow;
_actConfirmOutcome = ConfirmShown;
if (!_actArmed || _actArmedType != type || ActNow > _actArmedUntil) return;
_actArmed = false;
bool accept = _actArmedMinPercent <= 0 || (_actConfirmPercent >= 0 && _actConfirmPercent >= _actArmedMinPercent);
if (!ActInWorld) { _actConfirmOutcome = ConfirmSendFailed; return; }
Session.ConfirmationResponse(type, context, accept);
_actConfirmOutcome = accept ? ConfirmAccepted : ConfirmDeclined;
Log($"[host] confirmation type {type} ctx 0x{context:X8} percent {_actConfirmPercent}: answered {(accept ? "yes" : "no")}");
}
/// <summary>"... a 38 percent chance ..." -> 38; -1 when the text has no "N percent".</summary>
public static int ParseConfirmPercent(string text)
{
int at = text.IndexOf(" percent", StringComparison.Ordinal);
if (at <= 0) return -1;
int start = at;
while (start > 0 && char.IsAsciiDigit(text[start - 1])) start--;
if (start == at || at - start > 3) return -1;
return Math.Min(100, int.Parse(text.AsSpan(start, at - start)));
}
}

View file

@ -0,0 +1,196 @@
// ============================================================================
// RynthCore.Headless - Host/HostContext.Objects.cs
// The objects area's per-character state, kept from the world model's events:
// - identify replies: when (Unix seconds), success or not, the spell book, the
// creature profile's vitals (AppraisalHooks / ObjectQualityCache in the engine);
// - doors and levers: the last On / Off forward command of an UpdateMotion
// (DoMotionHooks);
// - when the server last said anything about an object (ObjectFreshness), for
// GetObjectServerAge and RemoveClientObject's 5 s rule.
// Everything for an object is dropped when it is deleted.
// ============================================================================
using RynthCore.Headless.Host.Objects;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Host;
public sealed partial class HostContext
{
/// <summary>A creature's vitals from its last identify's creature profile (health follows UpdateHealth).</summary>
public readonly record struct TargetVitals(uint Health, uint MaxHealth, uint Stamina, uint MaxStamina, uint Mana, uint MaxMana);
private readonly object _objGate = new();
private readonly Dictionary<uint, long> _objIdTime = new(); // Unix seconds of the last identify reply
private readonly HashSet<uint> _objAppraised = new();
private readonly Dictionary<uint, uint[]> _objSpells = new(); // spell book of the last identify
private readonly Dictionary<uint, TargetVitals> _objVitals = new();
private readonly Dictionary<uint, bool> _objMotionOn = new();
private readonly Dictionary<uint, long> _objHeardMs = new(); // NowMs of the server's last message about it
/// <summary>Doors' On (0x4000000B) / Off (0x4000000C) forward commands, by their low 16 bits as UpdateMotion carries them.</summary>
private const uint MotionOnLow = 0x000B, MotionOffLow = 0x000C;
public const long RemoveMinQuietMs = 5000;
partial void InitObjects()
{
WorldState w = World;
// Identifies the world model took before this context existed (a replay, a late host).
long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
foreach (WorldObject o in w.Objects.Values)
{
if (!o.Identified) continue;
_objAppraised.Add(o.Id);
_objIdTime[o.Id] = now;
}
w.ObjectCreated += o => Heard(o.Id);
w.ObjectUpdated += o => Heard(o.Id);
w.ObjectStateChanged += o => Heard(o.Id);
w.ObjectMoved += Heard;
w.ObjectDeleted += ForgetObjectState;
w.ObjectMotion += OnObjectMotion;
w.IdentifyDetailed += OnIdentifyDetails;
w.HealthUpdated += OnHealthRatio;
}
private void Heard(uint id)
{
lock (_objGate) _objHeardMs[id] = NowMs;
}
private void OnObjectMotion(uint id, InterpretedMotion m)
{
if (id != World.Player.Id) Heard(id);
uint low = m.ForwardCommand & 0xFFFF;
if (low is not (MotionOnLow or MotionOffLow)) return;
lock (_objGate) _objMotionOn[id] = low == MotionOnLow;
}
private void OnIdentifyDetails(IdentifyDetails d)
{
TargetVitals? v = null;
lock (_objGate)
{
_objAppraised.Add(d.ObjectId);
_objIdTime[d.ObjectId] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (d.Spells.Length > 0) _objSpells[d.ObjectId] = d.Spells;
else if (d.HasSpellBook) _objSpells.Remove(d.ObjectId);
// As the engine: max health even on a failed assess roll; nothing implausible.
if (d.HasCreatureProfile && d.HealthMax > 0 && d.HealthMax < 1_000_000)
{
v = new TargetVitals(Math.Min(d.Health, d.HealthMax), d.HealthMax, d.Stamina, d.StaminaMax, d.Mana, d.ManaMax);
_objVitals[d.ObjectId] = v.Value;
}
}
// The engine reports an identify's creature profile as a health update too.
if (v is { } tv)
Events.Enqueue(new PluginEvent.UpdateHealth(d.ObjectId, (float)tv.Health / tv.MaxHealth, tv.Health, tv.MaxHealth));
}
private void OnHealthRatio(uint id, float ratio)
{
Heard(id);
lock (_objGate)
{
if (_objVitals.TryGetValue(id, out TargetVitals v))
_objVitals[id] = v with { Health = (uint)MathF.Round(v.MaxHealth * Math.Clamp(ratio, 0f, 1f)) };
}
}
private void ForgetObjectState(uint id)
{
lock (_objGate)
{
_objIdTime.Remove(id);
_objAppraised.Remove(id);
_objSpells.Remove(id);
_objVitals.Remove(id);
_objMotionOn.Remove(id);
_objHeardMs.Remove(id);
}
}
partial void MaxHealthHook(uint id, ref uint max)
{
lock (_objGate)
if (_objVitals.TryGetValue(id, out TargetVitals v) && v.MaxHealth > 0) max = v.MaxHealth;
// The player's own health bar: the buffed maximum from the character sheet.
if (max == 0 && id != 0 && id == World.Player.Id) max = PlayerMaxVital(1);
}
// ── queries the API reads ──────────────────────────────────────────────
public bool HasAppraisalData(uint id)
{
lock (_objGate)
if (_objAppraised.Contains(id)) return true;
return World.Get(id)?.Identified == true;
}
/// <summary>Unix seconds of the last identify reply; 0 never.</summary>
public long LastIdTime(uint id)
{
lock (_objGate) return _objIdTime.TryGetValue(id, out long t) ? t : 0;
}
/// <summary>The last identify's spell book (the world model's copy for identifies before this context); null when none.</summary>
public uint[]? IdentifySpells(uint id)
{
lock (_objGate)
if (_objSpells.TryGetValue(id, out uint[]? s)) return s;
WorldObject? o = World.Get(id);
return o != null && o.Identified && o.SpellBook.Length > 0 ? o.SpellBook : null;
}
public bool TryGetTargetVitals(uint id, out TargetVitals v)
{
lock (_objGate) return _objVitals.TryGetValue(id, out v);
}
public bool TryGetMotionOn(uint id, out bool on)
{
lock (_objGate) return _objMotionOn.TryGetValue(id, out on);
}
/// <summary>Milliseconds since the server's last message about the object; -1 none seen (or deleted).</summary>
public long ServerAgeMs(uint id)
{
lock (_objGate)
return _objHeardMs.TryGetValue(id, out long t) ? Math.Max(0, NowMs - t) : -1;
}
/// <summary>Why <see cref="RemoveClientObject"/> would refuse, or null (the engine's DeleteObjectHooks.RemoveRefusal).</summary>
public string? RemoveRefusal(uint id)
{
if (id == 0) return "no object";
uint me = World.Player.Id;
if (me == 0 || id == me) return "the player";
WorldObject? o = World.Get(id);
if (o == null || !ObjectProps.Created(o)) return "not in the client's object table";
if ((o.ItemType & 0x10) == 0) return "not a creature";
if ((o.Desc.DescriptionFlags & ObjectProps.BfPlayer) != 0) return "a player";
long age = ServerAgeMs(id);
if (age >= 0 && age < RemoveMinQuietMs) return $"the server sent a message about it {age} ms ago";
return null;
}
/// <summary>
/// v83 RemoveClientObject: drops a ghost creature from the world model and tells the plugins
/// (OnDeleteObject). 1 removed, 0 refused.
/// </summary>
public int RemoveClientObject(uint id)
{
string? why = RemoveRefusal(id);
if (why != null)
{
Log($"RemoveClientObject 0x{id:X8}: refused - {why}.");
return 0;
}
if (!World.ForgetObject(id)) return 0;
ForgetObjectState(id);
Events.Enqueue(new PluginEvent.DeleteObject(id));
return 1;
}
}

View file

@ -0,0 +1,84 @@
// ============================================================================
// RynthCore.Headless - Host/HostContext.Player.cs
// The PLAYER area's state: the character sheet (Host/Player/CharacterSheet.cs) over
// the world model, the server clock, and when each enchantment started in server time.
//
// Enchantment times: ACE sends StartTime as seconds relative to "now" (0 at the cast,
// negative = already running that long) and the retail client stores it as server time
// (the received value plus its synchronized clock), so the engine's expiry is
// start + duration in server seconds, compared with GetServerTime. We do the same: each
// enchantment is stamped with the server time it arrived at (PlayerDescription,
// MagicUpdateEnchantment / ...Multiple); one we never saw arrive (the context was made
// after it came) is stamped the first time it is looked at.
// ============================================================================
using RynthCore.Headless.Dat;
using RynthCore.Headless.Host.Player;
using RynthCore.Headless.Messages;
namespace RynthCore.Headless.Host;
public sealed partial class HostContext
{
private readonly object _enchantGate = new();
// (spell, layer) -> (the wire StartTime, server time when it arrived)
private readonly Dictionary<(ushort Spell, ushort Layer), (double Wire, double Stamp)> _enchantStamps = new();
/// <summary>The skill / vital formula tables (null when the dats are missing: formulas degrade to init + ranks).</summary>
internal SkillTable? SkillFormulas { get; private set; }
partial void InitPlayer()
{
SkillFormulas = SkillTable.Shared;
StampAllEnchantments(clear: false);
World.PlayerDescribed += () => StampAllEnchantments(clear: true);
World.EnchantmentAdded += StampEnchantment;
}
/// <summary>The server's clock now (seconds): last time sync + local time since. 0 before the first.</summary>
public double ServerTimeNow => Session.ServerTimeNow;
private void StampAllEnchantments(bool clear)
{
double now = ServerTimeNow;
lock (_enchantGate)
{
if (clear) _enchantStamps.Clear();
foreach (Enchantment e in World.Player.Enchantments)
_enchantStamps[(e.SpellId, e.Layer)] = (e.StartTime, now);
}
}
private void StampEnchantment(Enchantment e)
{
double now = ServerTimeNow;
lock (_enchantGate) _enchantStamps[(e.SpellId, e.Layer)] = (e.StartTime, now);
}
/// <summary>When the enchantment started, in server-time seconds.</summary>
internal double EnchantmentStart(Enchantment e)
{
lock (_enchantGate)
{
if (!_enchantStamps.TryGetValue((e.SpellId, e.Layer), out var s) || s.Wire != e.StartTime)
{
s = (e.StartTime, ServerTimeNow);
_enchantStamps[(e.SpellId, e.Layer)] = s;
}
return s.Stamp + e.StartTime;
}
}
/// <summary>When it runs out, in server-time seconds; double.MaxValue for no duration (item spells: -1).</summary>
internal double EnchantmentExpiry(Enchantment e)
=> e.Duration > 0 ? EnchantmentStart(e) + e.Duration : double.MaxValue;
/// <summary>The player's character sheet as of now (cheap: computed on demand).</summary>
internal CharacterSheet Sheet() => new(World, SkillFormulas, EnchantmentStart);
/// <summary>True when the world model has the player's own description (stats, spells, enchantments).</summary>
internal bool PlayerKnown => World.Player.Id != 0 && World.Player.DescriptionReceived;
/// <summary>The player's buffed maximum of a vital (1 health, 2 stamina, 3 mana), 0 if unknown.</summary>
public uint PlayerMaxVital(uint vital) => PlayerKnown ? Sheet().VitalBuffedMax(vital) : 0;
}

View file

@ -0,0 +1,107 @@
// ============================================================================
// RynthCore.Headless - Host/HostContext.cs
// Everything one character's plugins can reach through the RynthCore API: its session
// (network + world model), the geometry, the spell table, the plugin event queue and
// the API's own bookkeeping (selection, busy count, use-done / error sequences, ...).
//
// The API functions are static [UnmanagedCallersOnly] methods, so they find their
// context through Current: set for the duration of every call into a plugin (all on
// the session's tick thread), with the most recently created context as the fallback
// for plugin threads that call in on their own (logging from a background load, ...).
// Partial: each API area keeps its own state in its own file.
// ============================================================================
using System.Runtime.InteropServices;
using RynthCore.Headless.Dat;
using RynthCore.Headless.Movement;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Host;
public sealed partial class HostContext
{
[ThreadStatic] private static HostContext? _current;
private static volatile HostContext? _fallback;
/// <summary>The context of the plugin call in progress (or the last one created).</summary>
public static HostContext? Current => _current ?? _fallback;
public ClientSession Session { get; }
public WorldState World => Session.World;
public GeometryWalk? Geometry { get; }
public SpellTable? Spells { get; }
public HostEvents Events { get; }
public string AccountName { get; }
public Action<string> LogSink { get; set; } = _ => { };
/// <summary>Milliseconds on the session's clock (same clock the session uses).</summary>
public long NowMs => Environment.TickCount64;
public HostContext(ClientSession session, string accountName, GeometryWalk? geometry, SpellTable? spells)
{
Session = session;
AccountName = accountName;
Geometry = geometry;
Spells = spells;
Events = new HostEvents(this);
_fallback = this;
InitAreas();
}
/// <summary>Makes this the current context until the returned scope is disposed.</summary>
public Scope Enter() => new(this);
public readonly struct Scope : IDisposable
{
private readonly HostContext? _prev;
public Scope(HostContext ctx)
{
_prev = _current;
_current = ctx;
}
public void Dispose() => _current = _prev;
}
public void Log(string line) => LogSink(line);
// Each area's partial file may add an initializer (called once from the constructor).
partial void InitObjects();
partial void InitPlayer();
partial void InitActions();
private void InitAreas()
{
InitObjects();
InitPlayer();
InitActions();
}
// ── strings handed to plugins ───────────────────────────────────────────
[ThreadStatic] private static Dictionary<int, IntPtr>? _ansi;
/// <summary>
/// An ANSI (single-byte) copy of <paramref name="s"/> the host owns, as the engine returns
/// names: one buffer per <paramref name="slot"/> and thread, freed by the next call for that
/// slot on that thread. Null (0) for null/whitespace.
/// </summary>
public static IntPtr Ansi(int slot, string? s)
{
_ansi ??= new Dictionary<int, IntPtr>();
if (_ansi.TryGetValue(slot, out IntPtr old) && old != IntPtr.Zero) Marshal.FreeHGlobal(old);
IntPtr p = string.IsNullOrWhiteSpace(s) ? IntPtr.Zero : Marshal.StringToHGlobalAnsi(s);
_ansi[slot] = p;
return p;
}
/// <summary>Writes a UTF-8 string NUL-terminated into a caller buffer; returns its byte length (not counting NUL), or -1 if it doesn't fit.</summary>
public static unsafe int Utf8(string s, byte* buffer, int capacity)
{
if (buffer == null || capacity <= 0) return -1;
byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
if (b.Length + 1 > capacity) return -1;
b.AsSpan().CopyTo(new Span<byte>(buffer, capacity));
buffer[b.Length] = 0;
return b.Length;
}
}

View file

@ -0,0 +1,102 @@
// ============================================================================
// RynthCore.Headless - Host/HostEvents.cs
// The plugin callbacks waiting to be delivered, collected from the world model and
// the API, drained once per host tick in the engine's order:
// busy +/-, combat mode, view contents / stop viewing, vendor open/close,
// inventory lists, creates, updates (one per object per drain), deletes, selection,
// health, combat damage, kills, enchantments added/removed, chat lines.
// Each queue is bounded; the oldest entry goes when one is full.
// ============================================================================
namespace RynthCore.Headless.Host;
public abstract record PluginEvent
{
public sealed record BusyIncremented : PluginEvent;
public sealed record BusyDecremented : PluginEvent;
public sealed record CombatModeChange(int Current, int Previous) : PluginEvent;
public sealed record ViewContents(uint Container) : PluginEvent;
public sealed record StopViewingContents(uint Container) : PluginEvent;
public sealed record VendorOpen(uint Vendor) : PluginEvent;
public sealed record VendorClose(uint Vendor) : PluginEvent;
public sealed record UpdateObjectInventory(uint Container) : PluginEvent;
public sealed record CreateObject(uint Id) : PluginEvent;
public sealed record UpdateObject(uint Id) : PluginEvent;
public sealed record DeleteObject(uint Id) : PluginEvent;
public sealed record SelectedTargetChange(uint Current, uint Previous) : PluginEvent;
public sealed record UpdateHealth(uint Target, float Ratio, uint CurrentHealth, uint MaxHealth) : PluginEvent;
public sealed record CombatDamage(uint Damage, uint DamageType, bool Critical, bool IsAttacker) : PluginEvent;
public sealed record KillNotification(string Text) : PluginEvent;
public sealed record EnchantmentAdded(uint SpellId, double Duration) : PluginEvent;
public sealed record EnchantmentRemoved(uint SpellId) : PluginEvent;
public sealed record ChatWindowText(string Text, int ChatType) : PluginEvent;
}
public sealed class HostEvents
{
public const int Cap = 4096;
private readonly HostContext _ctx;
private readonly object _gate = new();
private readonly List<PluginEvent> _pending = new();
public HostEvents(HostContext ctx) => _ctx = ctx;
public long Dropped { get; private set; }
public void Enqueue(PluginEvent e)
{
lock (_gate)
{
if (_pending.Count >= Cap)
{
_pending.RemoveAt(0);
Dropped++;
}
_pending.Add(e);
}
}
private static int Rank(PluginEvent e) => e switch
{
PluginEvent.BusyIncremented => 0,
PluginEvent.BusyDecremented => 1,
PluginEvent.CombatModeChange => 2,
PluginEvent.ViewContents => 3,
PluginEvent.StopViewingContents => 4,
PluginEvent.VendorOpen => 5,
PluginEvent.VendorClose => 6,
PluginEvent.UpdateObjectInventory => 7,
PluginEvent.CreateObject => 8,
PluginEvent.UpdateObject => 9,
PluginEvent.DeleteObject => 10,
PluginEvent.SelectedTargetChange => 11,
PluginEvent.UpdateHealth => 12,
PluginEvent.CombatDamage => 13,
PluginEvent.KillNotification => 14,
PluginEvent.EnchantmentAdded => 15,
PluginEvent.EnchantmentRemoved => 16,
PluginEvent.ChatWindowText => 17,
_ => 18,
};
/// <summary>Everything pending, in delivery order (stable within a kind); updates collapse to one per object.</summary>
public List<PluginEvent> Drain()
{
List<PluginEvent> batch;
lock (_gate)
{
batch = new List<PluginEvent>(_pending);
_pending.Clear();
}
var seenUpdates = new HashSet<uint>();
var deleted = new HashSet<uint>(batch.OfType<PluginEvent.DeleteObject>().Select(d => d.Id));
var result = new List<PluginEvent>(batch.Count);
foreach (PluginEvent e in batch.Select((e, i) => (e, i)).OrderBy(x => Rank(x.e)).ThenBy(x => x.i).Select(x => x.e))
{
if (e is PluginEvent.UpdateObject u && (!seenUpdates.Add(u.Id) || deleted.Contains(u.Id))) continue;
result.Add(e);
}
return result;
}
}

View file

@ -0,0 +1,267 @@
// ============================================================================
// RynthCore.Headless - Host/Objects/ObjectProps.cs
// An object's properties as the engine's per-key readers answer them off AC's thread
// (Compatibility/ClientObjectHooks.cs TryGetObject*Property), from the world model:
//
// 1. the object's property tables: what the server said about it as properties -
// the player's PlayerDescription and private updates, public UpdateProperty*
// messages, and the tables of every identify reply (merged in by WorldState);
// 2. the CreateObject / UpdateObject weenie header (the engine's PublicWeenieDesc
// snapshot), filed under the property ids the server took them from
// (PropertyWire.PwdLayout): a field the header didn't carry answers nothing.
//
// Exceptions, as in the engine: the client's own copies win for the stack size (12),
// the wielded location (10), the container (iid 2) and the wielder (iid 3) - they follow
// every split, merge, move and wield, where a table value is only as new as the last
// identify; the icon data ids (8, 50, 52) answer straight from the header.
//
// Int ids (ACE PropertyInt): 1 ItemType, 4 ClothingPriority, 5 EncumbranceVal (burden),
// 6 ItemsCapacity, 7 ContainersCapacity, 9 ValidLocations, 10 CurrentWieldedLocation,
// 11 MaxStackSize, 12 StackSize, 16 ItemUseable, 18 UiEffects, 19 Value, 50 AmmoType,
// 51 CombatUse, 91 MaxStructure, 92 Structure, 94 TargetType, 95 RadarBlipColor,
// 105 ItemWorkmanship (the header's float, rounded), 131 MaterialType,
// 133 ShowableOnRadar, 151 HookType, 152 HookItemType, 280 SharedCooldown.
// Float: 54 UseRadius, 167 CooldownDuration, 280 workmanship (the engine's own read,
// UtilityBelt's SalvageWorkmanship). Data id: 8 Icon, 28 Spell, 50 IconOverlay,
// 52 IconUnderlay. Instance id: 2 Container, 3 Wielder, 26 Monarch, 32 HouseOwner,
// 44 PetOwner. String: 1 Name, 20 PluralName.
// ============================================================================
using RynthCore.Engine.Compatibility;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Host.Objects;
internal static class ObjectProps
{
// ObjectDescriptionFlags (the header's bitfield).
public const uint BfPlayer = 0x8, BfAttackable = 0x10, BfPlayerKiller = 0x20, BfPkLite = 0x2000000;
/// <summary>The server created it (a CreateObject arrived), as opposed to a stub an inventory event made.</summary>
public static bool Created(WorldObject o) => o.Desc.Id != 0;
// ── ints ────────────────────────────────────────────────────────────────
public static bool TryGetInt(WorldObject o, uint stype, out int value)
{
value = 0;
switch (stype)
{
case 10: // the client's own wielded location; never a stale identify value
value = (int)o.WieldedLocation;
return value != 0;
case 12 when HasStack(o):
value = (int)o.StackSize;
return value > 0;
}
if (o.TryGetInt(stype, out value)) return true;
return TryGetHeaderInt(o, stype, out value);
}
private static bool HasStack(WorldObject o) => o.Desc.StackSize.HasValue || o.StackSize != 1;
/// <summary>The weenie header's int fields (zero / absent answers nothing).</summary>
public static bool TryGetHeaderInt(WorldObject o, uint stype, out int value)
{
ObjectCreateData d = o.Desc;
long v = stype switch
{
1 => d.ItemType,
4 => d.Priority ?? 0,
5 => d.Burden ?? 0,
6 => d.ItemsCapacity ?? 0,
7 => d.ContainersCapacity ?? 0,
9 => d.ValidLocations ?? 0,
10 => o.WieldedLocation,
11 => d.MaxStackSize ?? 0,
12 => HasStack(o) ? o.StackSize : 0,
16 => d.Usable ?? 0,
18 => d.UiEffects ?? 0,
19 => o.Value,
50 => d.AmmoType ?? 0,
51 => d.CombatUse ?? 0,
91 => d.MaxStructure ?? 0,
92 => d.Structure ?? 0,
94 => d.TargetType ?? 0,
95 => d.RadarColor ?? 0,
105 => d.Workmanship is float w && float.IsFinite(w) ? (long)MathF.Round(w) : 0,
131 => d.MaterialType ?? 0,
133 => d.RadarBehavior ?? 0,
151 => d.HookType ?? 0,
152 => d.HookItemTypes ?? 0,
280 => d.CooldownId ?? 0,
_ => 0,
};
value = unchecked((int)v);
return value != 0;
}
private static readonly uint[] HeaderIntStypes = { 1, 4, 5, 6, 7, 9, 10, 11, 12, 16, 18, 19, 50, 51, 91, 92, 94, 95, 105, 131, 133, 151, 152, 280 };
// ── the other kinds ────────────────────────────────────────────────────
public static bool TryGetInt64(WorldObject o, uint stype, out long value) => o.TryGetInt64(stype, out value);
public static bool TryGetBool(WorldObject o, uint stype, out bool value) => o.TryGetBool(stype, out value);
public static bool TryGetFloat(WorldObject o, uint stype, out double value)
{
if (o.TryGetFloat(stype, out value)) return true;
return TryGetHeaderFloat(o, stype, out value);
}
public static bool TryGetHeaderFloat(WorldObject o, uint stype, out double value)
{
ObjectCreateData d = o.Desc;
value = stype switch
{
54 => d.UseRadius ?? 0,
167 => d.CooldownDuration ?? 0,
280 => d.Workmanship ?? 0,
_ => 0,
};
return value != 0 && double.IsFinite(value);
}
public static bool TryGetString(WorldObject o, uint stype, out string value)
{
if (o.TryGetString(stype, out value) && value.Length > 0) return true;
value = stype switch
{
1 => o.Desc.Name,
20 => o.Desc.PluralName ?? "",
_ => "",
};
return value.Length > 0;
}
public static bool TryGetDataId(WorldObject o, uint stype, out uint value)
{
ObjectCreateData d = o.Desc;
// The icons straight from the header, 0 included (the engine's PWD icon read).
if (stype is 8 or 50 or 52 && Created(o))
{
value = stype switch { 8 => d.Icon, 50 => d.IconOverlay ?? 0, _ => d.IconUnderlay ?? 0 };
return true;
}
if (o.TryGetDataId(stype, out value)) return true;
value = stype switch
{
8 => d.Icon,
28 => d.Spell ?? 0,
50 => d.IconOverlay ?? 0,
52 => d.IconUnderlay ?? 0,
_ => 0,
};
return value != 0;
}
public static bool TryGetInstanceId(WorldObject o, uint stype, out uint value)
{
value = 0;
if (stype == 0) return false;
if (stype == 2 && o.ContainerId != 0) { value = o.ContainerId; return true; }
if (stype == 3 && o.WielderId != 0) { value = o.WielderId; return true; }
if (o.TryGetInstanceId(stype, out value) && value != 0) return true;
ObjectCreateData d = o.Desc;
value = stype switch
{
26 => d.Monarch ?? 0,
32 => d.HouseOwner ?? 0,
44 => d.PetOwner ?? 0,
_ => 0,
};
return value != 0;
}
// ── the whole set (GetObjectProperties) ─────────────────────────────────
/// <summary>The weenie header as a property bag (PwdLayout.FillBag's counterpart).</summary>
public static PropertyBag HeaderBag(WorldObject o)
{
var bag = new PropertyBag();
foreach (uint s in HeaderIntStypes)
if (TryGetHeaderInt(o, s, out int v)) bag.Ints[s] = v;
foreach (uint s in new uint[] { 54, 167 })
if (TryGetHeaderFloat(o, s, out double f)) bag.Floats[s] = f;
ObjectCreateData d = o.Desc;
if (d.Icon != 0) bag.DataIds[8] = d.Icon;
if (d.Spell is ushort sp && sp != 0) bag.DataIds[28] = sp;
if (d.IconOverlay is uint ov && ov != 0) bag.DataIds[50] = ov;
if (d.IconUnderlay is uint un && un != 0) bag.DataIds[52] = un;
if (o.ContainerId != 0) bag.InstanceIds[2] = o.ContainerId;
if (o.WielderId != 0) bag.InstanceIds[3] = o.WielderId;
if (d.Monarch is uint m && m != 0) bag.InstanceIds[26] = m;
if (d.HouseOwner is uint h && h != 0) bag.InstanceIds[32] = h;
if (d.PetOwner is uint p && p != 0) bag.InstanceIds[44] = p;
if (d.Name.Length > 0) bag.Strings[1] = d.Name;
if (!string.IsNullOrEmpty(d.PluralName)) bag.Strings[20] = d.PluralName;
return bag;
}
/// <summary>The property tables (PlayerDescription, updates, identifies) as a bag.</summary>
public static PropertyBag TableBag(WorldObject o)
{
var bag = new PropertyBag();
foreach (var kv in o.Ints) bag.Ints[kv.Key] = kv.Value;
foreach (var kv in o.Int64s) bag.Int64s[kv.Key] = kv.Value;
foreach (var kv in o.Bools) bag.Bools[kv.Key] = kv.Value;
foreach (var kv in o.Floats) bag.Floats[kv.Key] = kv.Value;
foreach (var kv in o.Strings) bag.Strings[kv.Key] = kv.Value;
foreach (var kv in o.DataIds) bag.DataIds[kv.Key] = kv.Value;
foreach (var kv in o.InstanceIds) bag.InstanceIds[kv.Key] = kv.Value;
return bag;
}
/// <summary>
/// The v84 record (ObjectPropertyRecord) for one object: the header under the tables, then the
/// client's own stack size, wielded location, container and wielder over both - what the
/// per-key reads above answer. Null when nothing is known about it.
/// </summary>
public static byte[]? Record(WorldObject o, bool isPlayer, bool appraised, long lastIdTime, IReadOnlyList<uint>? spells)
{
bool created = Created(o);
// The tables go in as the "qualities" source: Combine lays it over the header for players and others alike.
PropertyBag all = ObjectPropertyRecord.Combine(isPlayer, created ? HeaderBag(o) : null, TableBag(o), null, null, null);
if (o.WieldedLocation != 0) all.Ints[10] = (int)o.WieldedLocation;
else all.Ints.Remove(10);
if (all.Count == 0 && (spells == null || spells.Count == 0) && !created) return null;
ObjectPropertyFlags flags = ObjectPropertyFlags.None;
if (appraised) flags |= ObjectPropertyFlags.HasIdData;
if (isPlayer) flags |= ObjectPropertyFlags.IsPlayer;
if (created) flags |= ObjectPropertyFlags.HasCreateData;
return ObjectPropertyRecord.Encode(all, spells, flags, lastIdTime);
}
// ── attackable ──────────────────────────────────────────────────────────
/// <summary>
/// Retail's ClientCombatSystem::ObjectIsAttackable from what the client has: never the player;
/// a creature (ItemType 0x10) whose header has the Attackable bit (0x10: ACE sets it on monsters
/// and players, not on NPCs or vendors - but also on most items, hence the creature test); and
/// for another player (Player bit 0x8) only when both are player killers (0x20) or both PK-lite
/// (0x2000000).
/// </summary>
public static bool IsAttackable(WorldObject o, WorldObject? me)
{
if (!Created(o) || (me != null && o.Id == me.Id)) return false;
if ((o.ItemType & 0x10) == 0) return false;
uint bf = o.Desc.DescriptionFlags;
if ((bf & BfAttackable) == 0) return false;
if ((bf & BfPlayer) == 0) return true;
uint mine = me?.Desc.DescriptionFlags ?? 0;
return ((bf & BfPlayerKiller) != 0 && (mine & BfPlayerKiller) != 0)
|| ((bf & BfPkLite) != 0 && (mine & BfPkLite) != 0);
}
// ── heading ─────────────────────────────────────────────────────────────
/// <summary>Compass heading 0..360 (0 = north, clockwise) from a rotation quaternion (the engine's formula).</summary>
public static float Heading(float qw, float qz)
{
double physYawDeg = 2.0 * Math.Atan2(qz, qw) * (180.0 / Math.PI);
return (float)(((-physYawDeg) % 360.0 + 720.0) % 360.0);
}
}

View file

@ -0,0 +1,273 @@
// ============================================================================
// RynthCore.Headless - Host/Player/CharacterSheet.cs
// The player's attributes, vitals and skills as the client computes them: base
// (unenchanted) and buffed (enchanted) values, from what PlayerDescription and the
// private updates told us plus the portal dat formulas (Dat/SkillTable.cs).
//
// The rules (as ACE implements the retail ones; facts only, our own code):
// attribute base = init + ranks
// attribute buffed = round(base * Π mult + Σ (int)add), at least 10 (1 if base < 10)
// vital base max = init + ranks + formula(base attributes)
// (+ enlightenment * 2 + gear max health, health only)
// vital buffed max = round((init + ranks + formula(BUFFED attributes) [+ health extras])
// * Π mult * vitae + Σ add), at least 5 (1 if that total < 5)
// skill base = [usable] formula(base attributes) + init + ranks + aug base bonus
// skill buffed = round(([usable] formula(BUFFED attributes) + init + ranks + aug base)
// * Π mult * vitae + aug current bonus + Σ (int)add + attack/defense
// debuffs), at least 0
// "usable": trained / specialized, or untrained with the skill's dat MinLevel == 1.
// Enchantments that count: per spell category only the top layer (highest power level,
// then the level-8 aura self spells, then the newest / for set spells the highest id),
// among those whose StatModType has the stat-kind and the multiplicative/additive bit
// plus SingleStat with the stat's key, or MultipleStat with key 0 (not vitae).
// Vitae (spell 666) is its own multiplier: StatModValue, 1.0 = none.
// ============================================================================
using RynthCore.Headless.Dat;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Host.Player;
internal sealed class CharacterSheet
{
// EnchantmentTypeFlags
public const uint Attribute = 0x1, SecondAtt = 0x2, Skill = 0x10, SingleStat = 0x1000, MultipleStat = 0x2000,
Multiplicative = 0x4000, Additive = 0x8000, AttackSkills = 0x10000, DefenseSkills = 0x20000,
VitaeFlag = 0x800000, Cooldown = 0x1000000;
public const ushort VitaeSpell = 666;
// PropertyInt
private const uint AugSkilledMelee = 300, AugSkilledMissile = 301, AugSkilledMagic = 302, AugJackOfAllTrades = 326,
LumAugSkilledSpec = 344, LumAugAllSkills = 365, GearMaxHealth = 379, Enlightenment = 390;
// Blood Drinker / Defender / Heart Seeker / Spirit Drinker / Swift Killer / Hermetic Link Self VIII.
private static readonly HashSet<uint> Level8AuraSelf = new() { 4395, 4400, 4405, 4414, 4417, 4418 };
private static readonly HashSet<uint> MeleeSkills = new() { 45, 44, 46, 49, 41, 1, 4, 5, 9, 10, 11, 13 };
private static readonly HashSet<uint> MissileSkills = new() { 47, 2, 3, 8, 12 };
private static readonly HashSet<uint> MagicSkills = new() { 31, 32, 33, 43, 34 };
private static readonly HashSet<uint> AttackSkillSet = new() { 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 46, 44, 45, 47, 41, 34, 33, 43, 49 };
private static readonly HashSet<uint> DefenseSkillSet = new() { 6, 7, 15, 48 };
private readonly PlayerState _p;
private readonly WorldState _world;
private readonly SkillTable? _table;
private readonly List<(Enchantment E, double Start)> _ench;
/// <param name="startOf">The absolute (server-time) start of an enchantment, for the newest-layer tie-break.</param>
public CharacterSheet(WorldState world, SkillTable? table, Func<Enchantment, double> startOf)
{
_world = world;
_p = world.Player;
_table = table;
_ench = new List<(Enchantment, double)>(_p.Enchantments.Count);
foreach (Enchantment e in _p.Enchantments) _ench.Add((e, startOf(e)));
}
// ── properties ──────────────────────────────────────────────────────────
private int Int(uint key)
{
WorldObject? me = _world.PlayerObject;
if (me != null && me.Ints.TryGetValue(key, out int v)) return v;
return _p.Description != null && _p.Description.Ints.TryGetValue(key, out int d) ? d : 0;
}
/// <summary>1.0 = no vitae penalty, 0.95 = 5 %.</summary>
public float Vitae
{
get
{
foreach ((Enchantment e, _) in _ench)
if (e.SpellId == VitaeSpell) return e.StatModValue;
return 1.0f;
}
}
// ── enchantments ────────────────────────────────────────────────────────
/// <summary>The top layer per spell category among the enchantments that apply to (type, key).</summary>
public List<Enchantment> TopLayer(uint statModType, uint statModKey, bool handleMultiple)
{
uint multiple = 0;
if (handleMultiple)
{
multiple = statModType | MultipleStat;
statModType |= SingleStat;
}
var best = new Dictionary<ushort, (Enchantment E, double Start)>();
foreach ((Enchantment e, double start) in _ench)
{
if (e.SpellId == VitaeSpell) continue;
uint t = e.StatModType;
bool single = (t & statModType) == statModType && e.StatModKey == statModKey;
bool multi = handleMultiple && (t & multiple) == multiple && (t & VitaeFlag) == 0 && e.StatModKey == 0;
if (!single && !multi) continue;
if (!best.TryGetValue(e.Category, out var cur) || Beats(e, start, cur.E, cur.Start))
best[e.Category] = (e, start);
}
return best.Values.Select(x => x.E).ToList();
}
private static bool Beats(Enchantment a, double aStart, Enchantment b, double bStart)
{
if (a.PowerLevel != b.PowerLevel) return a.PowerLevel > b.PowerLevel;
bool a8 = Level8AuraSelf.Contains(a.SpellId), b8 = Level8AuraSelf.Contains(b.SpellId);
if (a8 != b8) return a8;
double ka = a.SpellSetId != 0 ? a.SpellId : aStart;
double kb = b.SpellSetId != 0 ? b.SpellId : bStart;
return ka > kb;
}
private float Multiplier(uint kind, uint key)
{
float m = 1.0f;
foreach (Enchantment e in TopLayer(kind | Multiplicative, key, true)) m *= e.StatModValue;
return m;
}
private int IntAdditive(uint kind, uint key)
{
int a = 0;
foreach (Enchantment e in TopLayer(kind | Additive, key, true)) a += (int)e.StatModValue;
return a;
}
private float FloatAdditive(uint kind, uint key)
{
float a = 0;
foreach (Enchantment e in TopLayer(kind | Additive, key, true)) a += e.StatModValue;
return a;
}
private static int RoundAway(double v) => (int)Math.Round(v, MidpointRounding.AwayFromZero);
// ── attributes ──────────────────────────────────────────────────────────
public bool HasAttribute(uint a) => _p.Attributes.ContainsKey(a);
/// <summary>Strength 1 .. Self 6: init + ranks.</summary>
public uint AttributeBase(uint a) => _p.Attributes.TryGetValue(a, out AttributeInfo i) ? i.Init + i.Ranks : 0;
public uint AttributeBuffed(uint a)
{
uint b = AttributeBase(a);
float total = (int)b * Multiplier(Attribute, a) + IntAdditive(Attribute, a);
int r = RoundAway(total);
int min = b >= 10 ? 10 : 1;
return (uint)Math.Max(min, r);
}
// ── vitals (1 Health, 2 Stamina, 3 Mana) ────────────────────────────────
/// <summary>The Attribute2nd max key the enchantments use: MaxHealth 1, MaxStamina 3, MaxMana 5.</summary>
private static uint MaxKey(uint vital) => vital * 2 - 1;
private SkillFormula VitalFormula(uint vital)
=> _table?.VitalFormula(vital) ?? vital switch
{
1 => new SkillFormula(0, 1, 0, 2, 2, 0), // Endurance / 2
2 => new SkillFormula(0, 1, 0, 1, 2, 0), // Endurance
_ => new SkillFormula(0, 1, 0, 1, 6, 0), // Self
};
private uint HealthExtras()
{
long extra = Int(Enlightenment) * 2L;
foreach (uint item in _p.Equipped.Keys)
if (_world.Get(item) is { } o && o.Ints.TryGetValue(GearMaxHealth, out int g)) extra += g;
return (uint)Math.Max(0, extra);
}
private uint VitalTotal(uint vital, bool buffedAttributes)
{
if (!_p.Vitals.TryGetValue(vital, out VitalInfo v)) return 0;
uint attr = VitalFormula(vital).Apply(buffedAttributes ? AttributeBuffed : AttributeBase);
uint total = v.Init + v.Ranks + attr;
if (vital == 1) total += HealthExtras();
return total;
}
public bool HasVital(uint vital) => _p.Vitals.ContainsKey(vital);
public uint VitalCurrent(uint vital) => _p.Vitals.TryGetValue(vital, out VitalInfo v) ? v.Current : 0;
/// <summary>Unbuffed maximum: no enchantments, no vitae.</summary>
public uint VitalBaseMax(uint vital) => VitalTotal(vital, buffedAttributes: false);
/// <summary>The maximum the client shows: buffed attributes, enchantments and vitae.</summary>
public uint VitalBuffedMax(uint vital)
{
if (!_p.Vitals.ContainsKey(vital)) return 0;
uint total = VitalTotal(vital, buffedAttributes: true);
uint key = MaxKey(vital);
float f = total * Multiplier(SecondAtt, key);
float vitae = Vitae;
if (vitae != 1.0f) f *= vitae;
int r = RoundAway(f + FloatAdditive(SecondAtt, key));
int min = total >= 5 ? 5 : 1;
return (uint)Math.Max(min, r);
}
// ── skills ──────────────────────────────────────────────────────────────
public bool TryGetSkill(uint id, out SkillInfo s) => _p.Skills.TryGetValue(id, out s);
private bool IsUsable(in SkillInfo s)
{
if (s.Training >= 2) return true;
if (s.Training == 1) return _table?.Get(s.Id)?.UsableUntrained ?? false;
return false;
}
private uint AugBase(in SkillInfo s)
{
long total = Int(LumAugAllSkills);
if (Int(AugSkilledMelee) > 0 && MeleeSkills.Contains(s.Id)) total += Int(AugSkilledMelee) * 10L;
else if (Int(AugSkilledMissile) > 0 && MissileSkills.Contains(s.Id)) total += Int(AugSkilledMissile) * 10L;
else if (Int(AugSkilledMagic) > 0 && MagicSkills.Contains(s.Id)) total += Int(AugSkilledMagic) * 10L;
if (s.Training >= 2 && Int(Enlightenment) != 0) total += Int(Enlightenment);
return (uint)Math.Max(0, total);
}
private uint AugCurrent(in SkillInfo s)
{
long total = 0;
if (Int(AugJackOfAllTrades) != 0) total += Int(AugJackOfAllTrades) * 5L;
if (s.Training == 3 && Int(LumAugSkilledSpec) != 0) total += Int(LumAugSkilledSpec) * 2L;
return (uint)Math.Max(0, total);
}
private uint SkillFormulaPart(in SkillInfo s, bool buffedAttributes)
{
if (!IsUsable(s)) return 0;
SkillFormula? f = _table?.Get(s.Id)?.Formula;
return f?.Apply(buffedAttributes ? AttributeBuffed : AttributeBase) ?? 0;
}
/// <summary>The unenchanted level: formula(base attributes) + init + ranks + augmentations.</summary>
public int SkillBase(in SkillInfo s) => (int)(SkillFormulaPart(s, false) + s.Init + s.Ranks + AugBase(s));
/// <summary>The level the client shows: buffed attributes, enchantments, vitae, augmentations.</summary>
public int SkillBuffed(in SkillInfo s)
{
uint total = SkillFormulaPart(s, true) + s.Init + s.Ranks + AugBase(s);
float f = total * Multiplier(Skill, s.Id);
float vitae = Vitae;
if (vitae != 1.0f) f *= vitae;
f += AugCurrent(s);
int additives = IntAdditive(Skill, s.Id);
if (DefenseSkillSet.Contains(s.Id)) additives += Debuff(Skill | Additive | DefenseSkills);
if (AttackSkillSet.Contains(s.Id)) additives += Debuff(Skill | Additive | AttackSkills);
return Math.Max(0, RoundAway(f + additives));
}
private int Debuff(uint type)
{
float a = 0;
foreach (Enchantment e in TopLayer(type, 0, false)) a += e.StatModValue;
return (int)Math.Round(a);
}
}

View file

@ -0,0 +1,338 @@
// ============================================================================
// RynthCore.Headless - Host/PluginHost.cs
// Loads managed RynthCore plugins for one character and drives them the way the
// engine's plugin pump does: Init with the API table, OnLoginComplete once the player
// is in the world (with OnCreateObject for everything already known), then every host
// tick: drain the queued events in the engine's order, then Tick. Every call runs with
// this character's HostContext current. A plugin whose call throws is marked failed
// and gets nothing more but Shutdown (as in the engine).
//
// Plugins must be managed builds for this process's bitness (x64 here: built with
// -p:PlatformTarget=x64 -p:RuntimeIdentifier=win-x64 -p:PublishAot=false).
// ============================================================================
using System.Reflection;
using System.Runtime.InteropServices;
using RynthCore.PluginSdk;
namespace RynthCore.Headless.Host;
public sealed unsafe class PluginHost : IDisposable
{
public sealed class Plugin
{
public required string Path;
public required string Name;
public required Dictionary<string, IntPtr> Exports;
internal PluginLoadContext? Context;
public bool Initialized, Failed, LoginDelivered;
public string? FailReason;
public IntPtr Export(string name) => Exports.TryGetValue(name, out IntPtr p) ? p : IntPtr.Zero;
}
private readonly HostContext _ctx;
private readonly List<Plugin> _plugins = new();
private RynthCoreApiNative* _api;
private bool _loginComplete;
public IReadOnlyList<Plugin> Plugins => _plugins;
public HostContext Context => _ctx;
public PluginHost(HostContext ctx)
{
_ctx = ctx;
_ctx.Plugins = this;
AcclientShims.Install();
}
// ── loading ─────────────────────────────────────────────────────────────
/// <summary>Loads a managed plugin DLL and initializes it. False (with the reason logged) on failure.</summary>
public bool Load(string path, string? sharedDir = null)
{
path = System.IO.Path.GetFullPath(path);
var alc = new PluginLoadContext("plugin " + System.IO.Path.GetFileName(path), System.IO.Path.GetDirectoryName(path)!, sharedDir);
Assembly asm;
var exports = new Dictionary<string, IntPtr>(StringComparer.Ordinal);
try
{
asm = alc.LoadPlugin(path);
foreach (Type t in asm.GetTypes())
foreach (MethodInfo m in t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
{
var uca = m.GetCustomAttribute<UnmanagedCallersOnlyAttribute>();
if (uca?.EntryPoint is { Length: > 0 } entry)
exports[entry] = m.MethodHandle.GetFunctionPointer();
}
}
catch (Exception ex)
{
_ctx.Log($"[host] can't load {path}: {ex.GetType().Name}: {ex.Message}");
alc.Unload();
return false;
}
var p = new Plugin { Path = path, Name = System.IO.Path.GetFileNameWithoutExtension(path), Exports = exports, Context = alc };
if (p.Export("RynthPluginInit") == IntPtr.Zero || p.Export("RynthPluginShutdown") == IntPtr.Zero)
{
_ctx.Log($"[host] {p.Name}: no RynthPluginInit/Shutdown export; skipped");
alc.Unload();
return false;
}
IntPtr nameFn = p.Export("RynthPluginName");
if (nameFn != IntPtr.Zero)
Call(p, () =>
{
IntPtr s = ((delegate* unmanaged[Cdecl]<IntPtr>)nameFn)();
if (s != IntPtr.Zero) p.Name = Marshal.PtrToStringAnsi(s) ?? p.Name;
});
if (_api == null) _api = HostApi.Build();
int rc = -1;
Call(p, () => rc = ((delegate* unmanaged[Cdecl]<RynthCoreApiNative*, int>)p.Export("RynthPluginInit"))(_api));
if (rc != 0)
{
p.Failed = true;
p.FailReason ??= $"Init returned {rc}";
_ctx.Log($"[host] {p.Name}: {p.FailReason}");
_plugins.Add(p);
return false;
}
p.Initialized = true;
_plugins.Add(p);
_ctx.Log($"[host] loaded {p.Name} ({exports.Count} exports)");
Call(p, "RynthPluginOnUIInitialized");
if (_loginComplete) DeliverLogin(p);
return true;
}
// ── driving ─────────────────────────────────────────────────────────────
/// <summary>The player is in the world: OnLoginComplete (once per login) with the objects already known.</summary>
public void LoginComplete()
{
if (_loginComplete) return;
_loginComplete = true;
foreach (Plugin p in Live()) DeliverLogin(p);
}
private void DeliverLogin(Plugin p)
{
if (p.LoginDelivered) return;
p.LoginDelivered = true;
// Objects created before the plugin could hear about them (the engine's replay).
foreach (uint id in _ctx.World.Objects.Keys.ToList())
Call(p, "RynthPluginOnCreateObject", id);
Call(p, "RynthPluginOnLoginComplete");
int mode = _ctx.CurrentCombatMode;
CallCombatMode(p, mode, 1);
}
public void Logout()
{
if (!_loginComplete) return;
_loginComplete = false;
foreach (Plugin p in Live())
{
p.LoginDelivered = false;
Call(p, "RynthPluginOnLogout");
}
}
/// <summary>One host frame: deliver queued events, then Tick every plugin.</summary>
public void Tick()
{
if (!_loginComplete) { _ctx.Events.Drain(); return; }
foreach (PluginEvent e in _ctx.Events.Drain())
foreach (Plugin p in Live())
Deliver(p, e);
foreach (Plugin p in Live())
Call(p, "RynthPluginTick");
}
/// <summary>
/// A typed or invoked chat line, offered to every plugin's OnChatBarEnter (shared eat flag).
/// True when a plugin consumed it.
/// </summary>
public bool ChatBarEnter(string text)
{
int* eat = (int*)NativeMemory.AllocZeroed(sizeof(int));
IntPtr s = Marshal.StringToHGlobalUni(text);
try
{
foreach (Plugin p in Live())
{
IntPtr fn = p.Export("RynthPluginOnChatBarEnter");
if (fn == IntPtr.Zero) continue;
Call(p, () => ((delegate* unmanaged[Cdecl]<IntPtr, int*, void>)fn)(s, eat));
if (*eat != 0) return true;
}
}
finally
{
Marshal.FreeHGlobal(s);
NativeMemory.Free(eat);
}
return false;
}
/// <summary>A plugin's export by name (first live plugin whose name matches), for brokers and bridges.</summary>
public IntPtr FindExport(string pluginName, string export)
{
Plugin? p = Live().FirstOrDefault(x => string.Equals(x.Name, pluginName, StringComparison.OrdinalIgnoreCase))
?? Live().FirstOrDefault(x => x.Name.Contains(pluginName, StringComparison.OrdinalIgnoreCase));
return p?.Export(export) ?? IntPtr.Zero;
}
private void Deliver(Plugin p, PluginEvent e)
{
switch (e)
{
case PluginEvent.BusyIncremented: Call(p, "RynthPluginOnBusyCountIncremented"); break;
case PluginEvent.BusyDecremented: Call(p, "RynthPluginOnBusyCountDecremented"); break;
case PluginEvent.CombatModeChange c: CallCombatMode(p, c.Current, c.Previous); break;
case PluginEvent.ViewContents v: Call(p, "RynthPluginOnViewObjectContents", v.Container); break;
case PluginEvent.StopViewingContents v: Call(p, "RynthPluginOnStopViewingObjectContents", v.Container); break;
case PluginEvent.VendorOpen v: Call(p, "RynthPluginOnVendorOpen", v.Vendor); break;
case PluginEvent.VendorClose v: Call(p, "RynthPluginOnVendorClose", v.Vendor); break;
case PluginEvent.UpdateObjectInventory u: Call(p, "RynthPluginOnUpdateObjectInventory", u.Container); break;
case PluginEvent.CreateObject c: Call(p, "RynthPluginOnCreateObject", c.Id); break;
case PluginEvent.UpdateObject u: Call(p, "RynthPluginOnUpdateObject", u.Id); break;
case PluginEvent.DeleteObject d: Call(p, "RynthPluginOnDeleteObject", d.Id); break;
case PluginEvent.SelectedTargetChange s:
{
IntPtr fn = p.Export("RynthPluginOnSelectedTargetChange");
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<uint, uint, void>)fn)(s.Current, s.Previous));
break;
}
case PluginEvent.UpdateHealth h:
{
IntPtr fn = p.Export("RynthPluginOnUpdateHealth");
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<uint, float, uint, uint, void>)fn)(h.Target, h.Ratio, h.CurrentHealth, h.MaxHealth));
break;
}
case PluginEvent.CombatDamage d:
{
IntPtr fn = p.Export("RynthPluginOnCombatDamage");
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<uint, uint, uint, uint, void>)fn)(d.Damage, d.DamageType, d.Critical ? 1u : 0u, d.IsAttacker ? 1u : 0u));
break;
}
case PluginEvent.KillNotification k: CallText(p, "RynthPluginOnKillNotification", k.Text); break;
case PluginEvent.EnchantmentAdded a:
{
IntPtr fn = p.Export("RynthPluginOnEnchantmentAdded");
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<uint, double, void>)fn)(a.SpellId, a.Duration));
break;
}
case PluginEvent.EnchantmentRemoved r: Call(p, "RynthPluginOnEnchantmentRemoved", r.SpellId); break;
case PluginEvent.ChatWindowText c:
{
IntPtr fn = p.Export("RynthPluginOnChatWindowText");
if (fn == IntPtr.Zero) break;
IntPtr s = Marshal.StringToHGlobalUni(c.Text);
int* eat = (int*)NativeMemory.AllocZeroed(sizeof(int));
try
{
Call(p, () => ((delegate* unmanaged[Cdecl]<IntPtr, int, int*, void>)fn)(s, c.ChatType, eat));
}
finally
{
Marshal.FreeHGlobal(s);
NativeMemory.Free(eat);
}
break;
}
}
}
private void CallCombatMode(Plugin p, int cur, int prev)
{
IntPtr fn = p.Export("RynthPluginOnCombatModeChange");
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<int, int, void>)fn)(cur, prev));
}
private void CallText(Plugin p, string export, string text)
{
IntPtr fn = p.Export(export);
if (fn == IntPtr.Zero) return;
IntPtr s = Marshal.StringToHGlobalUni(text);
try { Call(p, () => ((delegate* unmanaged[Cdecl]<IntPtr, void>)fn)(s)); }
finally { Marshal.FreeHGlobal(s); }
}
private void Call(Plugin p, string export)
{
IntPtr fn = p.Export(export);
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<void>)fn)());
}
private void Call(Plugin p, string export, uint arg)
{
IntPtr fn = p.Export(export);
if (fn != IntPtr.Zero) Call(p, () => ((delegate* unmanaged[Cdecl]<uint, void>)fn)(arg));
}
private void Call(Plugin p, Action call)
{
using HostContext.Scope _ = _ctx.Enter();
try
{
call();
}
catch (Exception ex)
{
p.Failed = true;
p.FailReason = $"{ex.GetType().Name}: {ex.Message}";
_ctx.Log($"[host] {p.Name} failed: {p.FailReason}");
}
}
private IEnumerable<Plugin> Live() => _plugins.Where(p => p.Initialized && !p.Failed).ToList();
public void Dispose()
{
foreach (Plugin p in _plugins.AsEnumerable().Reverse().Where(p => p.Initialized).ToList())
{
Call(p, "RynthPluginShutdown");
p.Initialized = false;
p.Context?.Unload();
}
_plugins.Clear();
if (_api != null)
{
Marshal.FreeHGlobal((IntPtr)_api);
_api = null;
}
}
}
public sealed partial class HostContext
{
/// <summary>The plugin host driving this context's plugins (set by PluginHost).</summary>
public PluginHost? Plugins { get; internal set; }
/// <summary>The player's combat mode (PropertyInt 40), NonCombat (1) when unknown.</summary>
public int CurrentCombatMode => World.PlayerObject is { } me && me.TryGetInt(40, out int m) && m != 0 ? m : 1;
}
/// <summary>
/// Stand-ins for the few fixed acclient addresses plugins read directly. RynthAi's meta
/// expressions read the game clock at 0x008379A8 without probing (getgameyear, ...); in this
/// process that address is unmapped, so a zeroed page is committed there (if free).
/// </summary>
internal static class AcclientShims
{
private static bool _done;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr VirtualAlloc(IntPtr address, UIntPtr size, uint type, uint protect);
public static void Install()
{
if (_done || !OperatingSystem.IsWindows()) return;
_done = true;
const uint MemCommitReserve = 0x3000, PageReadWrite = 0x04;
VirtualAlloc((IntPtr)0x00837000, (UIntPtr)0x1000, MemCommitReserve, PageReadWrite);
}
}

View file

@ -0,0 +1,60 @@
// ============================================================================
// RynthCore.Headless - Host/PluginLoadContext.cs
// One collectible AssemblyLoadContext per plugin load, like the engine's
// ManagedPlugins (src/RynthCore.Engine/Plugins/ManagedPlugins.cs, whose approach this
// follows): the plugin's own folder first, then a shared folder, else the default
// context (framework). Loaded from streams so the folder stays unlocked. Native
// libraries (cimgui) resolve from the same folders if present; headless plugins never
// draw, so a missing one only matters if something calls ImGui.
// Statics live per context, so each character's RynthAi is its own instance.
// ============================================================================
using System.Reflection;
using System.Runtime.Loader;
namespace RynthCore.Headless.Host;
internal sealed class PluginLoadContext : AssemblyLoadContext
{
private readonly string _dir;
private readonly string? _shared;
public PluginLoadContext(string name, string pluginDir, string? sharedDir) : base(name, isCollectible: true)
{
_dir = pluginDir;
_shared = sharedDir;
}
public Assembly LoadPlugin(string path) => LoadFile(path);
private Assembly LoadFile(string path)
{
using var dll = File.OpenRead(path);
string pdb = Path.ChangeExtension(path, ".pdb");
if (!File.Exists(pdb)) return LoadFromStream(dll);
using var sym = File.OpenRead(pdb);
return LoadFromStream(dll, sym);
}
private string? Pick(string file)
{
string a = Path.Combine(_dir, file);
string? b = _shared != null ? Path.Combine(_shared, file) : null;
bool ha = File.Exists(a), hb = b != null && File.Exists(b);
if (ha && hb) return File.GetLastWriteTimeUtc(a) >= File.GetLastWriteTimeUtc(b!) ? a : b;
return ha ? a : hb ? b : null;
}
protected override Assembly? Load(AssemblyName name)
{
string? path = Pick(name.Name + ".dll");
return path != null ? LoadFile(path) : null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string file = unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? unmanagedDllName : unmanagedDllName + ".dll";
string? path = Pick(file);
return path != null ? LoadUnmanagedDllFromPath(path) : IntPtr.Zero;
}
}

View file

@ -0,0 +1,22 @@
// ============================================================================
// RynthCore.Headless - Host/RetailErrorText.cs
// Some server refusals carry only an error code (a WeenieError, or an InventoryServerSaveFailed
// with one); the retail client prints its own text for them in the chat window. Plugins and metas
// watch that chat (e.g. a meta leaving a hive whose quest item is on its timer), so the host prints
// the same line. Only codes the retail client shows a line for are listed.
// ============================================================================
namespace RynthCore.Headless.Host;
internal static class RetailErrorText
{
private static readonly Dictionary<uint, string> Texts = new()
{
[0x001D] = "You're too busy!",
[0x043E] = "You have solved this quest too recently!",
[0x043F] = "You have solved this quest too many times!",
};
/// <summary>The chat line the retail client prints for this error code, or null when it prints none.</summary>
public static string? For(uint code) => Texts.TryGetValue(code, out string? t) ? t : null;
}

View file

@ -0,0 +1,178 @@
// ============================================================================
// RynthCore.Headless - Host/Status/RemoteMove.cs
// Hold-to-move from the phone (DrakRemote), the protocol RynthRemote speaks for a retail
// client; the rules are RynthRemote's MoveHold (RynthRemotePlugin/RemoteMove.cs, our own
// code), restated here so a headless character answers the phone the same way.
//
// Protocol 2: moveStart {"dir","deadmanMs"} (the phone promises keep-alives), then
// moveKeepAlive {"dirs":[...]} every ~200 ms while held; with none for deadmanMs (default
// 600, 300..3000) every held direction is let go. A keep-alive lets go of any held
// direction it no longer names, and never starts anything except to resume what the
// dead-man itself stopped within ResumeMs (never after an explicit stop).
// Legacy (a bare direction): a 2 s window re-armed by each repeated start.
// moveStop "stop" (or anything unreadable) lets go of everything; a direction, of that one.
// ============================================================================
using System.Text.Json;
namespace RynthCore.Headless.Host.Status;
public sealed class RemoteMove
{
public const long LegacyDeadMs = 2000;
public const long DefaultDeadMs = 600;
public const long MinDeadMs = 300;
public const long MaxDeadMs = 3000;
public const long ResumeMs = 1500;
public static readonly string[] Dirs = { "forward", "back", "left", "right" };
private readonly HashSet<string> _held = new(StringComparer.Ordinal);
private readonly HashSet<string> _resumable = new(StringComparer.Ordinal);
private bool _armed, _keepAliveMode;
private long _deadMs = LegacyDeadMs, _deadline, _resumableUntil;
public IReadOnlyCollection<string> Held => _held;
public bool KeepAliveMode => _keepAliveMode;
public static bool IsDir(string? d) => d != null && Array.IndexOf(Dirs, d) >= 0;
/// <summary>A press; the key changes to make ((dir, true) only when it wasn't already held).</summary>
public List<(string Dir, bool On)> Start(string dir, long? deadmanMs, long now)
{
var acts = new List<(string, bool)>(1);
if (!IsDir(dir)) return acts;
if (deadmanMs is long ms)
{
_keepAliveMode = true;
_deadMs = Math.Clamp(ms, MinDeadMs, MaxDeadMs);
}
else if (_held.Count == 0)
{
_keepAliveMode = false;
_deadMs = LegacyDeadMs;
}
_resumable.Clear();
if (_held.Add(dir)) acts.Add((dir, true));
_armed = true;
_deadline = now + _deadMs;
return acts;
}
/// <summary>A release; always reports it, held or not (an explicit stop must always stop).</summary>
public List<(string Dir, bool On)> Stop(string what)
{
var acts = new List<(string, bool)>(4);
_resumable.Clear();
if (what == "stop")
{
foreach (string d in Dirs) acts.Add((d, false));
_held.Clear();
}
else if (IsDir(what))
{
_held.Remove(what);
acts.Add((what, false));
}
if (_held.Count == 0) _armed = false;
return acts;
}
/// <summary>"Still held: these." Refreshes the dead-man and lets go of held directions not named.</summary>
public List<(string Dir, bool On)> KeepAlive(IReadOnlyCollection<string> dirs, long now)
{
var acts = new List<(string, bool)>(2);
if (_held.Count == 0)
{
if (_resumable.Count == 0 || now > _resumableUntil) return acts;
foreach (string d in dirs)
if (_resumable.Contains(d) && _held.Add(d)) acts.Add((d, true));
_resumable.Clear();
if (_held.Count == 0) return acts;
_armed = true;
_deadline = now + _deadMs;
return acts;
}
foreach (string d in _held.ToList())
if (!dirs.Contains(d)) { _held.Remove(d); acts.Add((d, false)); }
if (_held.Count == 0) { _armed = false; return acts; }
_deadline = now + _deadMs;
return acts;
}
/// <summary>Every tick: past the window, lets go of every direction; <paramref name="fired"/> says so.</summary>
public List<(string Dir, bool On)> Tick(long now, out bool fired)
{
fired = false;
var acts = new List<(string, bool)>(0);
if (!_armed || now <= _deadline) return acts;
fired = true;
if (_keepAliveMode && _held.Count > 0)
{
_resumable.Clear();
foreach (string d in _held) _resumable.Add(d);
_resumableUntil = now + ResumeMs;
}
foreach (string d in Dirs) acts.Add((d, false));
_held.Clear();
_armed = false;
return acts;
}
/// <summary>Lets go of everything at once (the session is going away).</summary>
public void Clear()
{
_held.Clear();
_resumable.Clear();
_armed = false;
}
// ── command values ──────────────────────────────────────────────────────
/// <summary>A moveStart value: a bare direction (legacy) or {"dir":"right","deadmanMs":600}.</summary>
public static bool TryParseStart(string? value, out string dir, out long? deadmanMs)
{
dir = "";
deadmanMs = null;
string v = (value ?? "").Trim();
if (v.Length == 0) return false;
if (v[0] != '{') { dir = v.ToLowerInvariant(); return IsDir(dir); }
try
{
using var doc = JsonDocument.Parse(v);
JsonElement r = doc.RootElement;
if (r.ValueKind != JsonValueKind.Object) return false;
if (r.TryGetProperty("dir", out JsonElement d) && d.ValueKind == JsonValueKind.String) dir = (d.GetString() ?? "").ToLowerInvariant();
deadmanMs = DefaultDeadMs;
if (r.TryGetProperty("deadmanMs", out JsonElement m) && m.ValueKind == JsonValueKind.Number && m.TryGetInt64(out long ms)) deadmanMs = ms;
return IsDir(dir);
}
catch (JsonException) { return false; }
}
/// <summary>A moveKeepAlive value: {"dirs":["forward","right"]}; unknown names are dropped.</summary>
public static bool TryParseKeepAlive(string? value, out List<string> dirs)
{
dirs = new List<string>(2);
try
{
using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(value) ? "{}" : value);
if (doc.RootElement.ValueKind != JsonValueKind.Object
|| !doc.RootElement.TryGetProperty("dirs", out JsonElement a) || a.ValueKind != JsonValueKind.Array) return false;
foreach (JsonElement e in a.EnumerateArray())
{
string d = e.ValueKind == JsonValueKind.String ? (e.GetString() ?? "").ToLowerInvariant() : "";
if (IsDir(d) && !dirs.Contains(d)) dirs.Add(d);
}
return true;
}
catch (JsonException) { return false; }
}
/// <summary>A moveStop value: "stop" or a direction; anything unreadable stops everything.</summary>
public static string ParseStop(string? value)
{
string v = (value ?? "").Trim().ToLowerInvariant();
return v == "stop" || IsDir(v) ? v : "stop";
}
}

View file

@ -0,0 +1,516 @@
// ============================================================================
// RynthCore.Headless - Host/Status/StatusExporter.cs
// What RynthRemote does for a retail client, for one headless character: the status
// files the StatusAgent and DrakRemote read, and the command inbox they write.
//
// Files, in the status folder, named by a per-character client id (one process hosts
// several characters, so the process id can't be the key; ids are odd and above a billion,
// so they never collide with a real process id):
// RynthCore.<id>.status.json the engine's "rynthcore.client-status/1" fields, plus
// RynthRemote's bot / enchantments / opos, plus
// headless: true, hostPid, hostProcess (so the agent can
// check the headless process is alive), every 1 s
// RynthCore.<id>.inventory.json RynthAi's RynthPluginGetInventoryJson, when it changes
// RynthCore.<id>.settings.json RynthAi's RynthPluginGetSettingsJson, when it changes
// RynthCore.<id>.character.json "rynthcore.character/1" sheet, when it changes
// commands\RynthCore.<id>.*.cmd.json drained every 200 ms (oldest first, deleted
// before they run): moveStart / moveStop / moveKeepAlive
// (RemoteMove: forward = autorun, back / left / right = held
// motions, the phone's dead-man), assess (identify); travel,
// raise, click and hideUi are refused (no RynthNav travel or
// raise senders here, nothing to click or hide); everything
// else to RynthAi's RynthPluginApplyRemoteCommand.
// Writes are tmp + replace, so readers never see a half file. Runs on the session thread.
// ============================================================================
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Session;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Host.Status;
public sealed unsafe class StatusExporter
{
public const string HostProcess = "rynth-headless";
private HostContext? _ctx;
private readonly string _account;
private readonly string _dir, _commands;
private readonly long _startMs;
private long _nextStatus, _nextExports, _nextCharacter, _nextCommands, _rateMark;
private int _ticks, _rate;
private string? _lastInventory, _lastSettings, _lastCharacter;
private long _xpStart = -1, _lumStart = -1, _xpStartMs;
private int _deathsStart = -1;
// Manual movement from the phone: held directions and the dead-man deadline.
private readonly RemoteMove _move = new();
public int ClientId { get; }
public string Account => _account;
public string ServerName { get; set; } = "";
public StatusExporter(string statusDir, int clientId, string account)
{
_dir = statusDir;
_commands = Path.Combine(statusDir, "commands");
ClientId = clientId;
_account = account;
_startMs = Now;
Directory.CreateDirectory(_dir);
Directory.CreateDirectory(_commands);
}
/// <summary>The current session's context; null between sessions (the status then reads "loading").</summary>
public HostContext? Context
{
get => _ctx;
set
{
_ctx = value;
_move.Clear();
_lastInventory = _lastSettings = _lastCharacter = null;
_nextStatus = 0;
}
}
private HostContext C => _ctx!;
private static long Now => Environment.TickCount64;
/// <summary>
/// A client id unique to this process and character slot (0..49). Odd, so never a real process id
/// (Windows pids are multiples of 4), and above a billion, so it reads as synthetic at a glance.
/// </summary>
public static int MakeClientId(int slot) => 1_000_000_001 + Environment.ProcessId % 1_000_000 * 100 + slot % 50 * 2;
public void Tick()
{
long now = Now;
_ticks++;
if (now - _rateMark >= 1000)
{
_rate = _ticks;
_ticks = 0;
_rateMark = now;
}
try
{
if (_ctx == null)
{
if (now >= _nextStatus) { _nextStatus = now + 1000; WriteAtomic($"RynthCore.{ClientId}.status.json", OfflineJson()); }
return;
}
if (now >= _nextCommands) { _nextCommands = now + 200; DrainCommands(); }
TickMove(now);
if (now >= _nextStatus) { _nextStatus = now + 1000; WriteAtomic($"RynthCore.{ClientId}.status.json", StatusJson()); }
if (now >= _nextExports)
{
_nextExports = now + 2000;
WriteIfChanged("RynthPluginGetInventoryJson", $"RynthCore.{ClientId}.inventory.json", ref _lastInventory);
WriteIfChanged("RynthPluginGetSettingsJson", $"RynthCore.{ClientId}.settings.json", ref _lastSettings);
}
if (now >= _nextCharacter)
{
_nextCharacter = now + 5000;
string? sheet = CharacterJson();
if (sheet != null && sheet != _lastCharacter)
{
WriteAtomic($"RynthCore.{ClientId}.character.json", sheet);
_lastCharacter = sheet;
}
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
/// <summary>The character is finished for good: its files go (the agent stops listing it).</summary>
public void Retire()
{
foreach (string kind in new[] { "status", "inventory", "settings", "character" })
{
try { File.Delete(Path.Combine(_dir, $"RynthCore.{ClientId}.{kind}.json")); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
}
// ── status ──────────────────────────────────────────────────────────────
/// <summary>Between sessions (connecting, or waiting to reconnect): reads as "loading".</summary>
private string OfflineJson()
{
var buf = new ArrayBufferWriter<byte>(512);
using (var j = new Utf8JsonWriter(buf))
{
j.WriteStartObject();
j.WriteString("schema", "rynthcore.client-status/1");
j.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
j.WriteString("host", Environment.MachineName);
j.WriteNumber("pid", ClientId);
j.WriteString("account", _account);
j.WriteString("character", LastCharacter);
j.WriteString("server", ServerName);
j.WriteNumber("uptimeSec", (Now - _startMs) / 1000);
j.WriteNumber("fps", 0);
j.WriteNumber("pluginTicksPerSec", 0);
j.WriteNumber("workingSetMB", Environment.WorkingSet / (1024 * 1024));
j.WriteBoolean("inWorld", false);
j.WriteNull("bot");
j.WriteBoolean("headless", true);
j.WriteNumber("hostPid", Environment.ProcessId);
j.WriteString("hostProcess", HostProcess);
j.WriteEndObject();
}
return Encoding.UTF8.GetString(buf.WrittenSpan);
}
/// <summary>The character name last seen in the world, or the configured one.</summary>
public string LastCharacter { get; set; } = "";
private string StatusJson()
{
WorldState w = C.World;
ClientSession s = C.Session;
WorldObject? me = w.PlayerObject;
bool inWorld = s.State == SessionState.InWorld && me != null;
var buf = new ArrayBufferWriter<byte>(4096);
using (var j = new Utf8JsonWriter(buf))
{
j.WriteStartObject();
j.WriteString("schema", "rynthcore.client-status/1");
j.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
j.WriteString("host", Environment.MachineName);
j.WriteNumber("pid", ClientId);
j.WriteString("engineVersion", "headless " + typeof(StatusExporter).Assembly.GetName().Version);
j.WriteNumber("apiVersion", (int)HostApi.ApiVersion);
j.WriteString("account", C.AccountName);
if (me?.Name is { Length: > 0 } nm) LastCharacter = nm;
j.WriteString("character", me?.Name ?? LastCharacter);
j.WriteString("server", ServerName.Length > 0 ? ServerName : s.WorldName);
j.WriteNumber("uptimeSec", (Now - _startMs) / 1000);
// No frames are drawn: the host frame rate stands in for fps, so the agent doesn't read "hung".
j.WriteNumber("fps", inWorld ? _rate : 0);
j.WriteNumber("pluginTicksPerSec", inWorld ? _rate : 0);
j.WriteNumber("workingSetMB", Environment.WorkingSet / (1024 * 1024));
j.WriteBoolean("inWorld", inWorld);
j.WriteNumber("queueDropped", C.Events.Dropped);
j.WriteNumber("reconciles", 0);
j.WriteNumber("forceClears", 0);
j.WriteBoolean("mainThreadFrozen", false);
j.WriteNumber("mainThreadStallMs", 0);
j.WriteNumber("pluginTicksPausedMs", 0);
int deaths = me != null && me.TryGetInt(43, out int d) ? d : 0; // NumDeaths
if (_deathsStart < 0 && me != null) _deathsStart = deaths;
j.WriteNumber("deaths", deaths);
j.WriteNumber("deathsSession", _deathsStart < 0 ? 0 : Math.Max(0, deaths - _deathsStart));
float vitae = inWorld ? Sheet()?.Vitae ?? 1f : 1f;
j.WriteNumber("vitaePct", Math.Round((1 - vitae) * 100, 1));
WriteRates(j, me);
j.WriteNumber("burdenPct", BurdenPct(me));
if (me?.Position is { } p)
{
uint lb = p.Cell >> 16;
bool indoor = (p.Cell & 0xFFFF) >= 0x100;
j.WriteString("area", lb.ToString("X4"));
j.WriteString("landblock", lb.ToString("X8"));
j.WriteBoolean("indoor", indoor);
if (indoor)
{
j.WriteNumber("wx", Math.Round(p.X + (lb >> 8) * 192.0, 2));
j.WriteNumber("wy", Math.Round(p.Y + (lb & 0xFF) * 192.0, 2));
j.WriteNumber("pz", Math.Round(p.Z, 2));
}
j.WriteStartObject("opos");
j.WriteString("cell", p.Cell.ToString("X8"));
j.WriteBoolean("indoor", indoor);
j.WriteNumber("wx", Math.Round(p.X + (lb >> 8) * 192.0, 2));
j.WriteNumber("wy", Math.Round(p.Y + (lb & 0xFF) * 192.0, 2));
j.WriteNumber("z", Math.Round(p.Z, 2));
j.WriteNumber("heading", Math.Round(ClientSession.HeadingDegrees(p), 1));
j.WriteEndObject();
}
else
{
j.WriteString("area", "");
j.WriteString("landblock", "");
j.WriteBoolean("indoor", false);
}
j.WriteNull("lastIssue");
j.WriteNumber("lastIssueAgeSec", -1);
// RynthRemote's additions.
j.WritePropertyName("bot");
string? bot = inWorld ? PluginJson("RynthPluginGetSnapshotJson") : null;
if (bot != null && IsJson(bot)) j.WriteRawValue(bot); else j.WriteNullValue();
j.WriteStartArray("enchantments");
if (inWorld)
{
double serverNow = C.ServerTimeNow;
foreach (Enchantment e in w.Player.ActiveEnchantments.Where(e => e.SpellId != 666)
.Select(e => (e, left: Remaining(e, serverNow))).OrderBy(x => x.left < 0 ? double.MaxValue : x.left).Select(x => x.e))
{
j.WriteStartObject();
j.WriteNumber("spellId", e.SpellId);
j.WriteNumber("secondsRemaining", Math.Round(Remaining(e, serverNow), 1));
j.WriteEndObject();
}
}
j.WriteEndArray();
j.WriteBoolean("raiseXp", false);
j.WriteNumber("moveProto", 2);
j.WriteBoolean("headless", true);
j.WriteNumber("hostPid", Environment.ProcessId);
j.WriteString("hostProcess", HostProcess);
j.WriteEndObject();
}
return Encoding.UTF8.GetString(buf.WrittenSpan);
}
private double Remaining(Enchantment e, double serverNow)
{
double expiry = C.EnchantmentExpiry(e);
return expiry == double.MaxValue ? -1 : Math.Max(0, expiry - serverNow);
}
private void WriteRates(Utf8JsonWriter j, WorldObject? me)
{
long xp = me != null && me.TryGetInt64(1, out long x) ? x : -1; // TotalExperience
long lum = me != null && me.TryGetInt64(6, out long l) ? l : -1; // AvailableLuminance
long now = Now;
if (xp >= 0 && (_xpStart < 0 || xp < _xpStart)) { _xpStart = xp; _lumStart = lum; _xpStartMs = now; }
double hours = Math.Max(1.0 / 60, (now - _xpStartMs) / 3_600_000.0);
long xpSession = xp >= 0 && _xpStart >= 0 ? xp - _xpStart : 0;
long lumSession = lum >= 0 && _lumStart >= 0 ? Math.Max(0, lum - _lumStart) : 0;
j.WriteNumber("xpPerHour", Math.Round(xpSession / hours));
j.WriteNumber("luminancePerHour", Math.Round(lumSession / hours));
j.WriteNumber("xpSession", xpSession);
}
private double BurdenPct(WorldObject? me)
{
if (me == null || !me.TryGetInt(5, out int burden)) return 0; // EncumbranceVal
uint str = Sheet()?.AttributeBuffed(1) ?? 0;
double capacity = 150.0 * str;
return capacity <= 0 ? 0 : Math.Round(burden / capacity * 100, 1);
}
private Player.CharacterSheet? Sheet() => C.PlayerKnown ? C.Sheet() : null;
// ── character sheet ─────────────────────────────────────────────────────
private string? CharacterJson()
{
if (!C.PlayerKnown || C.World.PlayerObject is not { } me) return null;
Player.CharacterSheet sheet = C.Sheet();
var buf = new ArrayBufferWriter<byte>(8192);
using (var j = new Utf8JsonWriter(buf))
{
j.WriteStartObject();
j.WriteString("schema", "rynthcore.character/1");
j.WriteNumber("pid", ClientId);
j.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"));
j.WriteString("name", me.Name);
j.WriteNumber("level", me.TryGetInt(25, out int level) ? level : 0);
j.WriteNumber("skillCredits", me.TryGetInt(24, out int credits) ? credits : 0);
j.WriteNumber("unassignedXp", me.TryGetInt64(2, out long avail) ? avail : 0);
j.WriteNumber("totalXp", me.TryGetInt64(1, out long total) ? total : 0);
string[] attrNames = { "", "Strength", "Endurance", "Quickness", "Coordination", "Focus", "Self" };
j.WriteStartArray("attributes");
for (uint a = 1; a <= 6; a++)
{
if (!sheet.HasAttribute(a)) continue;
j.WriteStartObject();
j.WriteNumber("id", a);
j.WriteString("name", attrNames[a]);
j.WriteNumber("base", sheet.AttributeBase(a));
j.WriteNumber("buffed", sheet.AttributeBuffed(a));
j.WriteEndObject();
}
j.WriteEndArray();
j.WriteStartArray("vitals");
foreach (var (v, id, name) in new[] { (1u, "health", "Health"), (2u, "stamina", "Stamina"), (3u, "mana", "Mana") })
{
if (!sheet.HasVital(v)) continue;
j.WriteStartObject();
j.WriteString("id", id);
j.WriteString("name", name);
j.WriteNumber("current", sheet.VitalCurrent(v));
j.WriteNumber("max", sheet.VitalBuffedMax(v));
j.WriteNumber("base", sheet.VitalBaseMax(v));
j.WriteEndObject();
}
j.WriteEndArray();
j.WriteStartArray("skills");
foreach (SkillInfo s in C.World.Player.SkillTable.Values.OrderBy(s => s.Id))
{
if (s.Training < 1) continue;
j.WriteStartObject();
j.WriteNumber("id", s.Id);
j.WriteString("name", C.SkillFormulas?.Get(s.Id)?.Name ?? $"Skill {s.Id}");
j.WriteString("training", s.Training switch { 3 => "specialized", 2 => "trained", _ => "untrained" });
j.WriteNumber("base", sheet.SkillBase(s));
j.WriteNumber("buffed", sheet.SkillBuffed(s));
j.WriteEndObject();
}
j.WriteEndArray();
j.WriteEndObject();
}
return Encoding.UTF8.GetString(buf.WrittenSpan);
}
// ── plugin exports ──────────────────────────────────────────────────────
private string? PluginJson(string export, string plugin = "RynthAi")
{
PluginHost? host = C.Plugins;
if (host == null) return null;
IntPtr fn = host.FindExport(plugin, export);
if (fn == IntPtr.Zero) return null;
using HostContext.Scope _ = C.Enter();
try
{
IntPtr p = ((delegate* unmanaged[Cdecl]<IntPtr>)fn)();
return p == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(p);
}
catch { return null; }
}
private void WriteIfChanged(string export, string file, ref string? last)
{
if (C.Session.State != SessionState.InWorld) return;
string? json = PluginJson(export);
if (json == null || json == last || !IsJson(json)) return;
WriteAtomic(file, json);
last = json;
}
private static bool IsJson(string s)
{
try { using var _ = JsonDocument.Parse(s); return true; }
catch (JsonException) { return false; }
}
private void WriteAtomic(string file, string content)
{
string path = Path.Combine(_dir, file);
string tmp = path + $".{ClientId}.tmp";
File.WriteAllText(tmp, content);
try { File.Move(tmp, path, overwrite: true); }
catch (IOException) { try { File.Delete(tmp); } catch (IOException) { } }
}
// ── commands ────────────────────────────────────────────────────────────
private void DrainCommands()
{
string[] files;
try { files = Directory.GetFiles(_commands, $"RynthCore.{ClientId}.*.cmd.json"); }
catch (IOException) { return; }
Array.Sort(files, StringComparer.Ordinal);
foreach (string f in files)
{
string text;
try
{
text = File.ReadAllText(f);
File.Delete(f);
}
catch (IOException) { continue; }
try
{
using var doc = JsonDocument.Parse(text);
string action = doc.RootElement.TryGetProperty("action", out var a) ? a.GetString() ?? "" : "";
string value = doc.RootElement.TryGetProperty("value", out var v) ? v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : v.ToString() : "";
Apply(action, value);
}
catch (JsonException) { C.Log($"[status] unreadable command {Path.GetFileName(f)}"); }
}
}
private void Apply(string action, string value)
{
C.Log($"[status] command {action} {value}");
ClientSession s = C.Session;
switch (action.ToLowerInvariant())
{
case "movestart":
if (RemoteMove.TryParseStart(value, out string dir, out long? deadman)) Motor(_move.Start(dir, deadman, Now));
break;
case "movekeepalive":
if (RemoteMove.TryParseKeepAlive(value, out List<string> dirs)) Motor(_move.KeepAlive(dirs, Now));
break;
case "movestop":
Motor(_move.Stop(RemoteMove.ParseStop(value)));
break;
case "assess":
if (uint.TryParse(value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? value[2..] : value,
value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? System.Globalization.NumberStyles.HexNumber : System.Globalization.NumberStyles.Integer,
null, out uint id) && id != 0)
s.Identify(id);
break;
case "travel":
case "travelstop":
case "raise":
case "click":
case "hideui":
_ctx?.Log($"[status] '{action}' is not available on a headless character");
break;
default:
// RynthAi's remote-command export queues it for its next tick (as RynthRemote sends it).
SendToPlugin("RynthAi", action, value);
break;
}
}
private void TickMove(long now)
{
var acts = _move.Tick(now, out bool fired);
if (!fired) return;
Motor(acts);
C.Log(_move.KeepAliveMode
? "[status] manual-move dead-man: no keep-alive from the phone - stopped"
: "[status] manual-move dead-man: no repeat from the phone for 2 s - stopped");
}
private void Motor(List<(string Dir, bool On)> acts)
{
foreach (var (dir, on) in acts) Motor(dir, on);
}
private void Motor(string dir, bool on)
{
ClientSession s = C.Session;
switch (dir)
{
case "forward": s.SetAutoRun(on); break;
case "back": s.SetDriveMotion(MotionCommand.WalkBackwards, on); break;
case "left": s.SetDriveMotion(MotionCommand.TurnLeft, on); break;
case "right": s.SetDriveMotion(MotionCommand.TurnRight, on); break;
}
}
private void SendToPlugin(string plugin, string action, string value)
{
PluginHost? host = C.Plugins;
IntPtr fn = host?.FindExport(plugin, "RynthPluginApplyRemoteCommand") ?? IntPtr.Zero;
if (fn == IntPtr.Zero) { C.Log($"[status] no {plugin} to take '{action}'"); return; }
IntPtr a = Marshal.StringToHGlobalAnsi(action), v = Marshal.StringToHGlobalAnsi(value);
using HostContext.Scope _ = C.Enter();
try { ((delegate* unmanaged[Cdecl]<IntPtr, IntPtr, void>)fn)(a, v); }
catch (Exception ex) { C.Log($"[status] {plugin} command failed: {ex.Message}"); }
finally
{
Marshal.FreeHGlobal(a);
Marshal.FreeHGlobal(v);
}
}
}

View file

@ -0,0 +1,88 @@
// ============================================================================
// RynthCore.Headless - Messages/GameActions.cs
// Client-to-server game actions (inside 0xF7B1: u32 sequence, u32 type, payload).
// Each builder returns the payload; ClientSession wraps and numbers it.
// ============================================================================
using RynthCore.Headless.Net;
namespace RynthCore.Headless.Messages;
public static class ActionType
{
public const uint MeleeAttack = 0x0008, MissileAttack = 0x000A, Talk = 0x0015, PutItemInContainer = 0x0019,
GetAndWieldItem = 0x001A, DropItem = 0x001B, UseWithTarget = 0x0035, Use = 0x0036, CastUntargeted = 0x0048,
CastTargeted = 0x004A, ChangeCombatMode = 0x0053, StackableMerge = 0x0054, StackableSplitToContainer = 0x0055,
StackableSplitTo3D = 0x0056, TeleToLifestone = 0x0063, LoginComplete = 0x00A1, IdentifyObject = 0x00C8,
GiveObjectRequest = 0x00CD, NoLongerViewingContents = 0x0195, StackableSplitToWield = 0x019B,
QueryHealth = 0x01BF, CancelAttack = 0x01B7, PingRequest = 0x01E9, ConfirmationResponse = 0x0275,
Salvage = 0x027D,
Jump = 0xF61B, MoveToState = 0xF61C, AutonomousPosition = 0xF753;
}
/// <summary>CombatMode flags.</summary>
public static class CombatMode
{
public const uint NonCombat = 1, Melee = 2, Missile = 4, Magic = 8;
}
public static class AttackHeight
{
public const uint High = 1, Medium = 2, Low = 3;
}
internal static class GameActions
{
private static byte[] U32s(params uint[] v)
{
var w = new WireWriter(v.Length * 4);
foreach (uint x in v) w.U32(x);
return w.ToArray();
}
public static byte[] Use(uint obj) => U32s(obj);
public static byte[] UseWithTarget(uint source, uint target) => U32s(source, target);
public static byte[] Identify(uint obj) => U32s(obj);
public static byte[] CastTargeted(uint target, uint spell) => U32s(target, spell);
public static byte[] CastUntargeted(uint spell) => U32s(spell);
public static byte[] ChangeCombatMode(uint mode) => U32s(mode);
public static byte[] MeleeAttack(uint target, uint height, float power)
=> new WireWriter(12).U32(target).U32(height).F32(Math.Clamp(power, 0f, 1f)).ToArray();
public static byte[] MissileAttack(uint target, uint height, float accuracy)
=> new WireWriter(12).U32(target).U32(height).F32(Math.Clamp(accuracy, 0f, 1f)).ToArray();
public static byte[] PutItemInContainer(uint item, uint container, int placement)
=> new WireWriter(12).U32(item).U32(container).I32(placement).ToArray();
public static byte[] GetAndWield(uint item, uint equipMask) => U32s(item, equipMask);
public static byte[] Drop(uint item) => U32s(item);
/// <summary>Salvage with a tool (the Ust): tool, count, then the item ids.</summary>
public static byte[] Salvage(uint tool, IReadOnlyList<uint> items)
{
var w = new WireWriter(8 + 4 * items.Count).U32(tool).U32((uint)items.Count);
foreach (uint id in items) w.U32(id);
return w.ToArray();
}
public static byte[] Give(uint target, uint item, int amount) => new WireWriter(12).U32(target).U32(item).I32(amount).ToArray();
public static byte[] Merge(uint from, uint to, int amount) => new WireWriter(12).U32(from).U32(to).I32(amount).ToArray();
public static byte[] SplitToContainer(uint stack, uint container, int placement, int amount)
=> new WireWriter(16).U32(stack).U32(container).I32(placement).I32(amount).ToArray();
public static byte[] SplitTo3D(uint stack, int amount) => new WireWriter(8).U32(stack).I32(amount).ToArray();
public static byte[] NoLongerViewing(uint container) => U32s(container);
public static byte[] QueryHealth(uint obj) => U32s(obj);
public static byte[] ConfirmationResponse(uint type, uint context, bool accept)
=> U32s(type, context, accept ? 1u : 0u);
/// <summary>
/// AutonomousPosition: position (cell, x, y, z, rotation w x y z), the instance,
/// server-control, teleport and force-position sequences, a contact byte, pad to 4.
/// </summary>
public static byte[] AutonomousPosition(WorldPosition p, ushort instance, ushort serverControl, ushort teleport,
ushort forcePosition, bool onGround)
{
var w = new WireWriter(48);
w.U32(p.Cell).F32(p.X).F32(p.Y).F32(p.Z).F32(p.Qw).F32(p.Qx).F32(p.Qy).F32(p.Qz);
w.U16(instance).U16(serverControl).U16(teleport).U16(forcePosition);
w.U8(onGround ? (byte)1 : (byte)0);
return w.Align4().ToArray();
}
}

View file

@ -0,0 +1,89 @@
// ============================================================================
// RynthCore.Headless - Messages/IdentifyDetails.cs
// What an identify reply (game event 0xC9, SetAppraiseInfo) says beyond its property
// tables, which PropertyWire.TryParseIdentify reads but only counts or partly keeps:
// the spell book's ids and the whole creature profile (health, stamina, mana and
// their maxima).
//
// Layout (ACE AppraiseInfo.Write), from the event type on: [type][guid][flags][success],
// then per flag in this order: int table (0x1), int64 (0x2000), bool (0x2), float (0x4),
// string (0x8), data id (0x1000) - each a PackableHashTable (u16 count, u16 buckets,
// entries) - then the spell book (0x10: u32 count, u32 ids), the armour profile (0x80:
// 8 f32), the creature profile (0x100: u32 flags, health, health max; flag 0x8 adds
// Str End Quick Coord Focus Self, Stamina Mana StaminaMax ManaMax; flag 0x1 adds u16
// highlights + u16 colors). The weapon and hook profiles that may follow are not needed.
// ============================================================================
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Messages;
public sealed record IdentifyDetails(uint ObjectId, uint Flags, bool Success, uint[] Spells, bool HasCreatureProfile,
uint Health, uint HealthMax, uint Stamina, uint StaminaMax, uint Mana, uint ManaMax)
{
public bool HasSpellBook => (Flags & 0x10) != 0;
}
public static class IdentifyDetailsReader
{
private const uint IdInt = 0x0001, IdBool = 0x0002, IdFloat = 0x0004, IdString = 0x0008, IdSpellBook = 0x0010,
IdArmor = 0x0080, IdCreature = 0x0100, IdDid = 0x1000, IdInt64 = 0x2000;
/// <summary>
/// Reads an identify reply starting at its event type (0xC9). A section that runs past the
/// end stops the read; what came before it is kept (spells read in full or not at all).
/// </summary>
public static bool TryParse(ReadOnlySpan<byte> msg, out IdentifyDetails details)
{
details = new IdentifyDetails(0, 0, false, Array.Empty<uint>(), false, 0, 0, 0, 0, 0, 0);
var r = new NetReader(msg);
if (!r.U32(out uint type) || type != 0xC9) return false;
if (!r.U32(out uint id) || !r.U32(out uint f) || !r.U32(out uint success) || id == 0) return false;
details = details with { ObjectId = id, Flags = f, Success = success != 0 };
if ((f & IdInt) != 0 && !SkipTable(ref r, 8)) return true;
if ((f & IdInt64) != 0 && !SkipTable(ref r, 12)) return true;
if ((f & IdBool) != 0 && !SkipTable(ref r, 8)) return true;
if ((f & IdFloat) != 0 && !SkipTable(ref r, 12)) return true;
if ((f & IdString) != 0 && !SkipStringTable(ref r)) return true;
if ((f & IdDid) != 0 && !SkipTable(ref r, 8)) return true;
if ((f & IdSpellBook) != 0)
{
if (!r.ListCount(out int n, 4)) return true;
var spells = new uint[n];
for (int i = 0; i < n; i++)
if (!r.U32(out spells[i])) return true;
details = details with { Spells = spells };
}
if ((f & IdArmor) != 0 && !r.Skip(32)) return true;
if ((f & IdCreature) != 0)
{
if (!r.U32(out uint cp) || !r.U32(out uint hp) || !r.U32(out uint hpMax)) return true;
uint st = 0, stMax = 0, mp = 0, mpMax = 0;
if ((cp & 0x8) != 0)
{
if (!r.Skip(24) || !r.U32(out st) || !r.U32(out mp) || !r.U32(out stMax) || !r.U32(out mpMax)) return true;
}
details = details with
{
HasCreatureProfile = true, Health = hp, HealthMax = hpMax,
Stamina = st, StaminaMax = stMax, Mana = mp, ManaMax = mpMax,
};
}
return true;
}
private static bool SkipTable(ref NetReader r, int entrySize)
=> r.TableCount(out int n, entrySize) && r.Skip(n * entrySize);
private static bool SkipStringTable(ref NetReader r)
{
if (!r.TableCount(out int n, 6)) return false;
for (int i = 0; i < n; i++)
if (!r.U32(out _) || !r.String16L(out _)) return false;
return true;
}
}

View file

@ -0,0 +1,113 @@
// ============================================================================
// RynthCore.Headless - Messages/LoginMessages.cs
// Login, character select, enter-world and logout messages, both directions.
// ============================================================================
using RynthCore.Headless.Net;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Messages;
internal static class Opcode
{
// client -> server
public const uint CharacterLogOff = 0xF653; // also the server's "logged off" reply
public const uint CharacterEnterWorld = 0xF657;
public const uint CharacterEnterWorldRequest = 0xF7C8;
public const uint GameAction = 0xF7B1;
public const uint DddInterrogationResponse = 0xF7E6;
// server -> client
public const uint ObjectCreate = 0xF745;
public const uint PlayerCreate = 0xF746;
public const uint ObjectDelete = 0xF747;
public const uint PlayerTeleport = 0xF751;
public const uint CharacterList = 0xF658;
public const uint CharacterError = 0xF659;
public const uint GameEvent = 0xF7B0;
public const uint AccountBoot = 0xF7DC;
public const uint EnterWorldServerReady = 0xF7DF;
public const uint ServerMessage = 0xF7E0;
public const uint ServerName = 0xF7E1;
public const uint DddInterrogation = 0xF7E5;
public const uint DddEnd = 0xF7EA;
public const uint HearSpeech = 0x02BB;
public const uint HearRangedSpeech = 0x02BC;
public const uint HearEmote = 0x01E0;
public const uint HearSoulEmote = 0x01E2;
}
internal static class GameActionType
{
public const uint Talk = 0x0015;
public const uint LoginComplete = 0x00A1;
}
internal sealed record CharacterEntry(uint Id, string Name, uint DeleteSeconds);
internal sealed record CharacterListData(IReadOnlyList<CharacterEntry> Characters, uint Slots, string Account, bool TurbineChat);
internal static class LoginMessages
{
public const string ClientVersion = "1802";
public const uint AuthAccountPassword = 2;
/// <summary>The LoginRequest optional section: version, auth type, time, account, password (plain text).</summary>
public static byte[] LoginRequest(string account, string password, uint unixTime)
{
var rest = new WireWriter(64);
rest.U32(AuthAccountPassword).U32(0).U32(unixTime).String16L(account).String16L("").String32L(password);
var w = new WireWriter(80);
w.String16L(ClientVersion).U32((uint)rest.Length).Bytes(rest.Span);
return w.ToArray();
}
public static byte[] EnterWorldRequest() => new WireWriter(4).U32(Opcode.CharacterEnterWorldRequest).ToArray();
public static byte[] EnterWorld(uint characterId, string account)
=> new WireWriter(32).U32(Opcode.CharacterEnterWorld).U32(characterId).String16L(account).ToArray();
/// <summary>"We have no dat iterations to report": the server then ends the DDD exchange without patching.</summary>
public static byte[] DddInterrogationResponse()
=> new WireWriter(12).U32(Opcode.DddInterrogationResponse).U32(1).I32(0).ToArray();
public static byte[] LogOff() => new WireWriter(4).U32(Opcode.CharacterLogOff).ToArray();
public static byte[] GameAction(uint sequence, uint type, ReadOnlySpan<byte> payload = default)
=> new WireWriter(12 + payload.Length).U32(Opcode.GameAction).U32(sequence).U32(type).Bytes(payload).ToArray();
public static byte[] TalkPayload(string text) => new WireWriter(8 + text.Length).String16L(text).ToArray();
public static bool TryParseCharacterList(ReadOnlySpan<byte> body, out CharacterListData list)
{
list = null!;
var r = new NetReader(body);
if (!r.U32(out _) || !r.ListCount(out int n, 8)) return false;
var chars = new List<CharacterEntry>(n);
for (int i = 0; i < n; i++)
{
if (!r.U32(out uint id) || !r.String16L(out string name) || !r.U32(out uint del)) return false;
chars.Add(new CharacterEntry(id, name, del));
}
if (!r.U32(out _) || !r.U32(out uint slots) || !r.String16L(out string account) || !r.U32(out uint turbine))
return false;
list = new CharacterListData(chars, slots, account, turbine != 0);
return true;
}
public static bool TryParseServerName(ReadOnlySpan<byte> body, out int online, out int max, out string name)
{
online = max = 0;
name = "";
var r = new NetReader(body);
return r.I32(out online) && r.I32(out max) && r.String16L(out name);
}
/// <summary>0xF7E0: text, then a ChatMessageType.</summary>
public static bool TryParseServerMessage(ReadOnlySpan<byte> body, out string text, out uint chatType)
{
chatType = 0;
var r = new NetReader(body);
return r.String16L(out text) && r.U32(out chatType);
}
}

View file

@ -0,0 +1,131 @@
// ============================================================================
// RynthCore.Headless - Messages/MotionMessages.cs
// The player's movement messages and the interpreted motion state the server echoes.
//
// MoveToState (game action 0xF61C): RawMotionState, the 32-byte position (cell, x y z,
// rotation w x y z), the instance / server-control / teleport / force-position
// sequences, a contact byte (0x1 on the ground, 0x2 standing long jump), pad to 4.
// RawMotionState: u32 = flags (low 11 bits) | command count << 11, then the fields whose
// flag is set, in bit order: current hold key 0x1, current style 0x2, forward command
// 0x4, forward hold key 0x8, forward speed 0x10, sidestep command 0x20, sidestep hold
// key 0x40, sidestep speed 0x80, turn command 0x100, turn hold key 0x200, turn speed
// 0x400. Omitted fields mean: hold key None, style NonCombat, forward Ready, speed 1.
//
// The server answers a MoveToState with an UpdateMotion for us too, with its own speeds:
// holding Run turns WalkForward into RunForward at the player's run rate, which is how
// the client learns how fast the server thinks it runs (4 m/s x run rate).
//
// Jump (0xF61B): extent, velocity x y z, the four sequences, then two u32 (object, spell)
// that ACE reads before acting; they are sent as 0.
// ============================================================================
using RynthCore.Headless.Net;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Messages;
public static class MotionCommand
{
public const uint Ready = 0x41000003, WalkForward = 0x45000005, WalkBackwards = 0x45000006, RunForward = 0x44000007,
TurnRight = 0x6500000D, TurnLeft = 0x6500000E, SideStepRight = 0x6500000F, SideStepLeft = 0x65000010;
public const uint HoldNone = 1, HoldRun = 2;
public const uint NonCombat = 0x8000003D;
/// <summary>Base ground speeds (m/s at speed 1): walk, run, sidestep.</summary>
public const float WalkSpeed = 3.12f, RunSpeed = 4.0f, SidestepSpeed = 1.25f;
}
/// <summary>What the player is pressing, as RawMotionState carries it.</summary>
public readonly record struct RawMotion(uint ForwardCommand = 0, bool Run = false, uint TurnCommand = 0, float TurnSpeed = 1f,
uint SidestepCommand = 0)
{
public static RawMotion Stop => new();
public static RawMotion RunForward => new(MotionCommand.WalkForward, Run: true);
public static RawMotion WalkForward => new(MotionCommand.WalkForward);
public bool Moving => ForwardCommand != 0 || TurnCommand != 0 || SidestepCommand != 0;
}
/// <summary>The interpreted motion state of an UpdateMotion (movement type 0).</summary>
public readonly record struct InterpretedMotion(uint Style, uint ForwardCommand, float ForwardSpeed, uint SidestepCommand,
float SidestepSpeed, uint TurnCommand, float TurnSpeed);
internal static class MotionMessages
{
private const uint FHoldKey = 0x1, FStyle = 0x2, FForward = 0x4, FForwardHold = 0x8, FForwardSpeed = 0x10,
FSidestep = 0x20, FSidestepHold = 0x40, FSidestepSpeed = 0x80, FTurn = 0x100, FTurnHold = 0x200, FTurnSpeed = 0x400;
public static void WriteRawMotion(WireWriter w, RawMotion m)
{
uint flags = 0;
if (m.Run) flags |= FHoldKey;
if (m.ForwardCommand != 0) flags |= FForward | FForwardHold;
if (m.SidestepCommand != 0) flags |= FSidestep | FSidestepHold;
if (m.TurnCommand != 0) flags |= FTurn | FTurnHold;
if (m.TurnCommand != 0 && m.TurnSpeed != 1f) flags |= FTurnSpeed;
uint hold = m.Run ? MotionCommand.HoldRun : MotionCommand.HoldNone;
w.U32(flags);
if ((flags & FHoldKey) != 0) w.U32(hold);
if ((flags & FForward) != 0) w.U32(m.ForwardCommand);
if ((flags & FForwardHold) != 0) w.U32(hold);
if ((flags & FSidestep) != 0) w.U32(m.SidestepCommand);
if ((flags & FSidestepHold) != 0) w.U32(hold);
if ((flags & FTurn) != 0) w.U32(m.TurnCommand);
if ((flags & FTurnHold) != 0) w.U32(hold);
if ((flags & FTurnSpeed) != 0) w.F32(m.TurnSpeed);
}
public static byte[] MoveToState(RawMotion m, WorldPosition p, ushort instance, ushort serverControl, ushort teleport,
ushort forcePosition, bool onGround)
{
var w = new WireWriter(80);
WriteRawMotion(w, m);
w.U32(p.Cell).F32(p.X).F32(p.Y).F32(p.Z).F32(p.Qw).F32(p.Qx).F32(p.Qy).F32(p.Qz);
w.U16(instance).U16(serverControl).U16(teleport).U16(forcePosition);
w.U8(onGround ? (byte)1 : (byte)0);
return w.Align4().ToArray();
}
public static byte[] Jump(float extent, float vx, float vy, float vz, ushort instance, ushort serverControl, ushort teleport, ushort forcePosition)
=> new WireWriter(32).F32(extent).F32(vx).F32(vy).F32(vz).U16(instance).U16(serverControl).U16(teleport).U16(forcePosition)
.U32(0).U32(0).ToArray();
/// <summary>
/// The interpreted state in an UpdateMotion body of movement type 0: u32 flags (bits 0-6) |
/// command count &lt;&lt; 7; then u16 style, u16 forward, u16 sidestep, u16 turn (each if
/// flagged; commands are their low 16 bits), then f32 forward / sidestep / turn speeds.
/// </summary>
public static bool TryInterpreted(ReadOnlySpan<byte> updateMotionBody, out InterpretedMotion m)
{
m = default;
var r = new NetReader(updateMotionBody);
if (!r.Skip(4 + 2 + 2 + 2 + 1 + 1) || !r.U8(out byte type) || !r.U8(out _) || !r.U16(out ushort stance) || type != 0)
return false;
if (!r.U32(out uint f)) return false;
uint style = 0x80000000u | stance, fwd = MotionCommand.Ready, side = 0, turn = 0;
float fs = 1, ss = 1, ts = 1;
ushort u16;
if ((f & 0x01) != 0) { if (!r.U16(out u16)) return false; style = 0x80000000u | u16; }
if ((f & 0x02) != 0) { if (!r.U16(out u16)) return false; fwd = Full(u16); }
if ((f & 0x08) != 0) { if (!r.U16(out u16)) return false; side = Full(u16); }
if ((f & 0x20) != 0) { if (!r.U16(out u16)) return false; turn = Full(u16); }
if ((f & 0x04) != 0 && !r.F32(out fs)) return false;
if ((f & 0x10) != 0 && !r.F32(out ss)) return false;
if ((f & 0x40) != 0 && !r.F32(out ts)) return false;
m = new InterpretedMotion(style, fwd, fs, side, ss, turn, ts);
return true;
}
/// <summary>The full motion id for the low 16 bits the server sends (the ones a player's state uses).</summary>
private static uint Full(ushort low) => low switch
{
0x0003 => MotionCommand.Ready,
0x0005 => MotionCommand.WalkForward,
0x0006 => MotionCommand.WalkBackwards,
0x0007 => MotionCommand.RunForward,
0x000D => MotionCommand.TurnRight,
0x000E => MotionCommand.TurnLeft,
0x000F => MotionCommand.SideStepRight,
0x0010 => MotionCommand.SideStepLeft,
_ => low,
};
}

View file

@ -0,0 +1,218 @@
// ============================================================================
// RynthCore.Headless - Messages/ObjectCreate.cs
// 0xF745 CreateObject and 0xF7DB UpdateObject (same body): guid, model data (walked
// over), physics data (position, setup, parent, sequences) and the whole weenie header.
//
// Alignment is to 4 bytes from the start of the message (opcode included); the body
// starts at 4, so aligning the body offset gives the same result.
// ============================================================================
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Messages;
public readonly record struct WorldPosition(uint Cell, float X, float Y, float Z, float Qw, float Qx, float Qy, float Qz)
{
public uint Landblock => Cell >> 16;
}
/// <summary>Everything CreateObject/UpdateObject says about an object. Absent optional fields are null.</summary>
public sealed class ObjectCreateData
{
public uint Id;
public string Name = "";
public uint WeenieClassId, Icon, ItemType, DescriptionFlags;
public uint PhysicsFlags, PhysicsState, SetupId, ParentId, ParentLocation;
public float? Scale;
public WorldPosition? Position;
public ushort[] Sequences = Array.Empty<ushort>();
public uint WeenieFlags, WeenieFlags2;
public string? PluralName;
public byte? ItemsCapacity, ContainersCapacity, RadarColor, RadarBehavior;
public ushort? AmmoType, Structure, MaxStructure, StackSize, MaxStackSize, Script, Burden, Spell, HookType;
public int? Value, CooldownId;
public uint? Usable, TargetType, UiEffects, ContainerId, WielderId, ValidLocations, CurrentWieldedLocation,
Priority, HouseOwner, HookItemTypes, Monarch, IconOverlay, IconUnderlay, MaterialType, PetOwner;
public float? UseRadius, Workmanship;
public sbyte? CombatUse;
public double? CooldownDuration;
/// <summary>The instance sequence (the object's "life": a recreated object has a newer one).</summary>
public ushort InstanceSequence => Sequences.Length == 9 ? Sequences[8] : (ushort)0;
}
public static class ObjectCreate
{
// PhysicsDescriptionFlag
private const uint CSetup = 0x1, MTable = 0x2, Velocity = 0x4, Acceleration = 0x8, Omega = 0x10, Parent = 0x20,
Children = 0x40, ObjScale = 0x80, Friction = 0x100, Elasticity = 0x200, STable = 0x800, PeTable = 0x1000,
DefaultScript = 0x2000, DefaultScriptIntensity = 0x4000, Position = 0x8000, Movement = 0x10000,
AnimationFrame = 0x20000, Translucency = 0x40000;
// WeenieHeaderFlags
private const uint WPluralName = 0x1, WItemsCapacity = 0x2, WContainersCapacity = 0x4, WValue = 0x8, WUsable = 0x10,
WUseRadius = 0x20, WMonarch = 0x40, WUiEffects = 0x80, WAmmoType = 0x100, WCombatUse = 0x200, WStructure = 0x400,
WMaxStructure = 0x800, WStackSize = 0x1000, WMaxStackSize = 0x2000, WContainer = 0x4000, WWielder = 0x8000,
WValidLocations = 0x10000, WCurrentlyWielded = 0x20000, WPriority = 0x40000, WTargetType = 0x80000,
WRadarColor = 0x100000, WBurden = 0x200000, WSpell = 0x400000, WRadarBehavior = 0x800000,
WWorkmanship = 0x1000000, WHouseOwner = 0x2000000, WHouseRestrictions = 0x4000000, WScript = 0x8000000,
WHookType = 0x10000000, WHookItemTypes = 0x20000000, WIconOverlay = 0x40000000, WMaterialType = 0x80000000;
// WeenieHeaderFlag2
private const uint W2IconUnderlay = 0x1, W2Cooldown = 0x2, W2CooldownDuration = 0x4, W2PetOwner = 0x8;
private const uint IncludesSecondHeader = 0x04000000;
private const uint IconType = 0x06000000;
public static bool TryParse(ReadOnlySpan<byte> body, out ObjectCreateData obj)
{
obj = new ObjectCreateData();
var r = new NetReader(body);
if (!r.U32(out obj.Id)) return false;
if (!SkipModelData(ref r)) return false;
if (!ReadPhysics(ref r, obj)) return false;
return ReadWeenieHeader(ref r, obj);
}
/// <summary>AC packed u32: u16, and if its high bit is set, a second u16 for the low word.</summary>
public static bool PackedU32(ref NetReader r, out uint v)
{
v = 0;
if (!r.U16(out ushort a)) return false;
if ((a & 0x8000) == 0) { v = a; return true; }
if (!r.U16(out ushort b)) return false;
v = ((uint)(a & 0x7FFF) << 16) | b;
return true;
}
private static bool PackedKnown(ref NetReader r, uint type, out uint v)
{
if (!PackedU32(ref r, out v)) return false;
if (v != 0) v |= type;
return true;
}
internal static bool Align(ref NetReader r) => r.Skip((4 - (r.Position & 3)) & 3);
private static bool SkipModelData(ref NetReader r)
{
if (!r.U8(out _) || !r.U8(out byte palettes) || !r.U8(out byte textures) || !r.U8(out byte parts)) return false;
if (palettes > 0 && !PackedU32(ref r, out _)) return false;
for (int i = 0; i < palettes; i++)
if (!PackedU32(ref r, out _) || !r.Skip(2)) return false;
for (int i = 0; i < textures; i++)
if (!r.Skip(1) || !PackedU32(ref r, out _) || !PackedU32(ref r, out _)) return false;
for (int i = 0; i < parts; i++)
if (!r.Skip(1) || !PackedU32(ref r, out _)) return false;
return Align(ref r);
}
internal static bool ReadPosition(ref NetReader r, out WorldPosition pos)
{
pos = default;
if (!r.U32(out uint cell) || !r.F32(out float x) || !r.F32(out float y) || !r.F32(out float z)
|| !r.F32(out float qw) || !r.F32(out float qx) || !r.F32(out float qy) || !r.F32(out float qz))
return false;
pos = new WorldPosition(cell, x, y, z, qw, qx, qy, qz);
return true;
}
private static bool ReadPhysics(ref NetReader r, ObjectCreateData o)
{
if (!r.U32(out uint flags) || !r.U32(out o.PhysicsState)) return false;
o.PhysicsFlags = flags;
if ((flags & Movement) != 0)
{
if (!r.U32(out uint len) || !r.Skip((int)len)) return false;
if (len > 0 && !r.Skip(4)) return false;
}
else if ((flags & AnimationFrame) != 0 && !r.Skip(4)) return false;
if ((flags & Position) != 0)
{
if (!ReadPosition(ref r, out WorldPosition p)) return false;
o.Position = p;
}
if ((flags & MTable) != 0 && !r.Skip(4)) return false;
if ((flags & STable) != 0 && !r.Skip(4)) return false;
if ((flags & PeTable) != 0 && !r.Skip(4)) return false;
if ((flags & CSetup) != 0 && !r.U32(out o.SetupId)) return false;
if ((flags & Parent) != 0 && (!r.U32(out o.ParentId) || !r.U32(out o.ParentLocation))) return false;
if ((flags & Children) != 0)
{
if (!r.ListCount(out int n, 8) || !r.Skip(n * 8)) return false;
}
if ((flags & ObjScale) != 0)
{
if (!r.F32(out float s)) return false;
o.Scale = s;
}
if ((flags & Friction) != 0 && !r.Skip(4)) return false;
if ((flags & Elasticity) != 0 && !r.Skip(4)) return false;
if ((flags & Translucency) != 0 && !r.Skip(4)) return false;
if ((flags & Velocity) != 0 && !r.Skip(12)) return false;
if ((flags & Acceleration) != 0 && !r.Skip(12)) return false;
if ((flags & Omega) != 0 && !r.Skip(12)) return false;
if ((flags & DefaultScript) != 0 && !r.Skip(4)) return false;
if ((flags & DefaultScriptIntensity) != 0 && !r.Skip(4)) return false;
o.Sequences = new ushort[9];
for (int i = 0; i < 9; i++)
if (!r.U16(out o.Sequences[i])) return false;
return Align(ref r);
}
private static bool ReadWeenieHeader(ref NetReader r, ObjectCreateData o)
{
if (!r.U32(out uint f) || !r.String16L(out o.Name)) return false;
if (!PackedU32(ref r, out o.WeenieClassId) || !PackedKnown(ref r, IconType, out o.Icon)) return false;
if (!r.U32(out o.ItemType) || !r.U32(out o.DescriptionFlags) || !Align(ref r)) return false;
o.WeenieFlags = f;
uint f2 = 0;
if ((o.DescriptionFlags & IncludesSecondHeader) != 0 && !r.U32(out f2)) return false;
o.WeenieFlags2 = f2;
uint u32; ushort u16; byte u8; float f32;
if ((f & WPluralName) != 0) { if (!r.String16L(out string pl)) return false; o.PluralName = pl; }
if ((f & WItemsCapacity) != 0) { if (!r.U8(out u8)) return false; o.ItemsCapacity = u8; }
if ((f & WContainersCapacity) != 0) { if (!r.U8(out u8)) return false; o.ContainersCapacity = u8; }
if ((f & WAmmoType) != 0) { if (!r.U16(out u16)) return false; o.AmmoType = u16; }
if ((f & WValue) != 0) { if (!r.I32(out int v)) return false; o.Value = v; }
if ((f & WUsable) != 0) { if (!r.U32(out u32)) return false; o.Usable = u32; }
if ((f & WUseRadius) != 0) { if (!r.F32(out f32)) return false; o.UseRadius = f32; }
if ((f & WTargetType) != 0) { if (!r.U32(out u32)) return false; o.TargetType = u32; }
if ((f & WUiEffects) != 0) { if (!r.U32(out u32)) return false; o.UiEffects = u32; }
if ((f & WCombatUse) != 0) { if (!r.U8(out u8)) return false; o.CombatUse = (sbyte)u8; }
if ((f & WStructure) != 0) { if (!r.U16(out u16)) return false; o.Structure = u16; }
if ((f & WMaxStructure) != 0) { if (!r.U16(out u16)) return false; o.MaxStructure = u16; }
if ((f & WStackSize) != 0) { if (!r.U16(out u16)) return false; o.StackSize = u16; }
if ((f & WMaxStackSize) != 0) { if (!r.U16(out u16)) return false; o.MaxStackSize = u16; }
if ((f & WContainer) != 0) { if (!r.U32(out u32)) return false; o.ContainerId = u32; }
if ((f & WWielder) != 0) { if (!r.U32(out u32)) return false; o.WielderId = u32; }
if ((f & WValidLocations) != 0) { if (!r.U32(out u32)) return false; o.ValidLocations = u32; }
if ((f & WCurrentlyWielded) != 0) { if (!r.U32(out u32)) return false; o.CurrentWieldedLocation = u32; }
if ((f & WPriority) != 0) { if (!r.U32(out u32)) return false; o.Priority = u32; }
if ((f & WRadarColor) != 0) { if (!r.U8(out u8)) return false; o.RadarColor = u8; }
if ((f & WRadarBehavior) != 0) { if (!r.U8(out u8)) return false; o.RadarBehavior = u8; }
if ((f & WScript) != 0) { if (!r.U16(out u16)) return false; o.Script = u16; }
if ((f & WWorkmanship) != 0) { if (!r.F32(out f32)) return false; o.Workmanship = f32; }
if ((f & WBurden) != 0) { if (!r.U16(out u16)) return false; o.Burden = u16; }
if ((f & WSpell) != 0) { if (!r.U16(out u16)) return false; o.Spell = u16; }
if ((f & WHouseOwner) != 0) { if (!r.U32(out u32)) return false; o.HouseOwner = u32; }
if ((f & WHouseRestrictions) != 0)
{
// version, open status, monarch, then a hash table of (character, access).
if (!r.Skip(12) || !r.TableCount(out int n, 8) || !r.Skip(n * 8)) return false;
}
if ((f & WHookItemTypes) != 0) { if (!r.U32(out u32)) return false; o.HookItemTypes = u32; }
if ((f & WMonarch) != 0) { if (!r.U32(out u32)) return false; o.Monarch = u32; }
if ((f & WHookType) != 0) { if (!r.U16(out u16)) return false; o.HookType = u16; }
if ((f & WIconOverlay) != 0) { if (!PackedKnown(ref r, IconType, out u32)) return false; o.IconOverlay = u32; }
if ((f2 & W2IconUnderlay) != 0) { if (!PackedKnown(ref r, IconType, out u32)) return false; o.IconUnderlay = u32; }
if ((f & WMaterialType) != 0) { if (!r.U32(out u32)) return false; o.MaterialType = u32; }
if ((f2 & W2Cooldown) != 0) { if (!r.I32(out int cd)) return false; o.CooldownId = cd; }
if ((f2 & W2CooldownDuration) != 0) { if (!r.F64(out double cdd)) return false; o.CooldownDuration = cdd; }
if ((f2 & W2PetOwner) != 0) { if (!r.U32(out u32)) return false; o.PetOwner = u32; }
return Align(ref r);
}
}

View file

@ -0,0 +1,336 @@
// ============================================================================
// RynthCore.Headless - Messages/PlayerDescription.cs
// Game event 0x0013: everything the server tells the player about itself at login.
//
// Order: property flags, weenie type, the property tables (int, int64, bool, double,
// string, data id, instance id, position), vector flags + "has health", attributes
// (6 primary x 12 bytes, 3 vitals x 16), skills (32-byte entries), spells, the
// enchantment registry, character options (options1, shortcuts, 8 spell bars,
// desired components, spellbook filters, options2, gameplay options), then the main
// pack list and the equipped list.
//
// The gameplay-options blob has no length on the wire. When it is present the two
// lists are found from the END of the message (nothing follows them): every candidate
// (equipped count, inventory count) whose counts and entries are consistent is
// considered, and the one with the most entries wins. Inventory can also be rebuilt
// from the CreateObject stream (each item carries its container/wielder), which the
// world model does anyway.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Messages;
public readonly record struct AttributeInfo(uint Ranks, uint Init, uint Xp)
{
public uint Base => Init + Ranks;
}
public readonly record struct VitalInfo(uint Ranks, uint Init, uint Xp, uint Current);
public readonly record struct SkillInfo(uint Id, ushort Ranks, ushort AdjustPP, uint Training, uint Xp, uint Init, uint Resistance, double LastUsed)
{
/// <summary>0 inactive, 1 untrained, 2 trained, 3 specialized.</summary>
public bool IsTrained => Training >= 2;
}
public readonly record struct Enchantment(
ushort SpellId, ushort Layer, ushort Category, uint PowerLevel, double StartTime, double Duration, uint CasterId,
float DegradeModifier, float DegradeLimit, double LastDegraded, uint StatModType, uint StatModKey, float StatModValue,
uint SpellSetId);
public readonly record struct PackEntry(uint Id, uint ContainerType);
public readonly record struct EquippedEntry(uint Id, uint Location, uint Priority);
public sealed class PlayerDescriptionData
{
public uint WeenieType;
public readonly Dictionary<uint, int> Ints = new();
public readonly Dictionary<uint, long> Int64s = new();
public readonly Dictionary<uint, bool> Bools = new();
public readonly Dictionary<uint, double> Floats = new();
public readonly Dictionary<uint, string> Strings = new();
public readonly Dictionary<uint, uint> DataIds = new();
public readonly Dictionary<uint, uint> InstanceIds = new();
public readonly Dictionary<uint, WorldPosition> Positions = new();
/// <summary>Strength (1) .. Self (6).</summary>
public readonly Dictionary<uint, AttributeInfo> Attributes = new();
/// <summary>Health (1), Stamina (2), Mana (3).</summary>
public readonly Dictionary<uint, VitalInfo> Vitals = new();
public readonly Dictionary<uint, SkillInfo> Skills = new();
public readonly HashSet<uint> Spells = new();
public readonly List<Enchantment> Enchantments = new();
public uint OptionFlags, SpellbookFilters;
public int Options1, Options2;
public readonly List<(uint Slot, uint ObjectId)> Shortcuts = new();
public readonly List<uint>[] SpellBars = Enumerable.Range(0, 8).Select(_ => new List<uint>()).ToArray();
public readonly Dictionary<uint, int> DesiredComponents = new();
public readonly List<PackEntry> Inventory = new();
public readonly List<EquippedEntry> Equipped = new();
/// <summary>False when the two lists could not be located (the world model then relies on CreateObject).</summary>
public bool InventoryFound;
}
public static class PlayerDescription
{
public const uint EventType = 0x0013;
// property flags
private const uint PInt = 0x01, PBool = 0x02, PDouble = 0x04, PDid = 0x08, PString = 0x10, PPosition = 0x20, PIid = 0x40, PInt64 = 0x80;
// vector flags
private const uint VAttribute = 0x001, VSkill = 0x002, VSpell = 0x100, VEnchantment = 0x200;
// character option flags
private const uint OShortcut = 0x1, OSquelch = 0x2, OMultiSpell = 0x4, ODesiredComps = 0x8, OExtMultiSpell = 0x10,
OSpellbookFilters = 0x20, OOptions2 = 0x40, OTimestampFormat = 0x80, OGenericQualities = 0x100,
OGameplayOptions = 0x200, OSpellLists8 = 0x400;
public const int EnchantmentSize = 60; // + 4 with a spell set id
/// <summary>Parses the event body (after the 12-byte event header).</summary>
public static bool TryParse(ReadOnlySpan<byte> body, out PlayerDescriptionData pd)
{
pd = new PlayerDescriptionData();
return Parse(body, pd);
}
private static bool Parse(ReadOnlySpan<byte> body, PlayerDescriptionData pd)
{
var r = new NetReader(body);
if (!r.U32(out uint pf) || !r.U32(out pd.WeenieType)) return false;
if ((pf & PInt) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.I32(out int v)) return false; pd.Ints[k] = v; return true; })) return false;
if ((pf & PInt64) != 0 && !Table(ref r, 12, (ref NetReader x, uint k) => { if (!x.U64(out ulong v)) return false; pd.Int64s[k] = (long)v; return true; })) return false;
if ((pf & PBool) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.U32(out uint v)) return false; pd.Bools[k] = v != 0; return true; })) return false;
if ((pf & PDouble) != 0 && !Table(ref r, 12, (ref NetReader x, uint k) => { if (!x.F64(out double v)) return false; pd.Floats[k] = v; return true; })) return false;
if ((pf & PString) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.String16L(out string v)) return false; pd.Strings[k] = v; return true; })) return false;
if ((pf & PDid) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.U32(out uint v)) return false; pd.DataIds[k] = v; return true; })) return false;
if ((pf & PIid) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.U32(out uint v)) return false; pd.InstanceIds[k] = v; return true; })) return false;
if ((pf & PPosition) != 0 && !Table(ref r, 36, (ref NetReader x, uint k) => { if (!ObjectCreate.ReadPosition(ref x, out WorldPosition p)) return false; pd.Positions[k] = p; return true; })) return false;
if (!r.U32(out uint vf) || !r.U32(out _)) return false;
if ((vf & VAttribute) != 0)
{
if (!r.U32(out uint mask)) return false;
for (int bit = 0; bit < 9; bit++)
{
if ((mask & (1u << bit)) == 0) continue;
if (!r.U32(out uint ranks) || !r.U32(out uint init) || !r.U32(out uint xp)) return false;
if (bit < 6)
{
pd.Attributes[(uint)bit + 1] = new AttributeInfo(ranks, init, xp);
}
else
{
if (!r.U32(out uint current)) return false;
pd.Vitals[(uint)bit - 5] = new VitalInfo(ranks, init, xp, current);
}
}
}
if ((vf & VSkill) != 0 && !Table(ref r, 32, (ref NetReader x, uint k) =>
{
if (!ReadSkillBody(ref x, k, out SkillInfo s)) return false;
pd.Skills[k] = s;
return true;
})) return false;
if ((vf & VSpell) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.Skip(4)) return false; pd.Spells.Add(k); return true; })) return false;
if ((vf & VEnchantment) != 0 && !ReadRegistry(ref r, pd.Enchantments)) return false;
// Character options.
if (!r.U32(out pd.OptionFlags) || !r.I32(out pd.Options1)) return false;
uint of = pd.OptionFlags;
if ((of & OShortcut) != 0)
{
if (!r.ListCount(out int n, 12)) return false;
for (int i = 0; i < n; i++)
{
if (!r.U32(out uint slot) || !r.U32(out uint obj) || !r.Skip(4)) return false;
pd.Shortcuts.Add((slot, obj));
}
}
if ((of & OSpellLists8) != 0)
{
for (int bar = 0; bar < 8; bar++)
{
if (!r.U32List(out uint[] ids)) return false;
pd.SpellBars[bar].AddRange(ids);
}
}
else if ((of & OMultiSpell) != 0 || (of & OExtMultiSpell) != 0)
{
int bars = (of & OExtMultiSpell) != 0 ? 7 : 5;
for (int bar = 0; bar < bars; bar++)
{
if (!r.U32List(out uint[] ids)) return false;
if (bar < 8) pd.SpellBars[bar].AddRange(ids);
}
}
else if (!r.U32List(out uint[] single))
{
return false;
}
else
{
pd.SpellBars[0].AddRange(single);
}
if ((of & ODesiredComps) != 0 && !Table(ref r, 8, (ref NetReader x, uint k) => { if (!x.I32(out int v)) return false; pd.DesiredComponents[k] = v; return true; })) return false;
if ((of & OSpellbookFilters) != 0 && !r.U32(out pd.SpellbookFilters)) return false;
if ((of & OOptions2) != 0 && !r.I32(out pd.Options2)) return false;
if ((of & (OSquelch | OTimestampFormat | OGenericQualities)) != 0)
{
// Never sent by ACE; their layouts aren't read here, so the lists are found from the end.
pd.InventoryFound = FindListsFromEnd(body, r.Position, pd);
return true;
}
if ((of & OGameplayOptions) == 0)
{
pd.InventoryFound = ReadLists(ref r, pd) && r.Remaining == 0;
if (!pd.InventoryFound) { pd.Inventory.Clear(); pd.Equipped.Clear(); }
return true;
}
pd.InventoryFound = FindListsFromEnd(body, r.Position, pd);
return true;
}
internal static bool ReadSkillBody(ref NetReader x, uint id, out SkillInfo s)
{
s = default;
if (!x.U16(out ushort ranks) || !x.U16(out ushort adj) || !x.U32(out uint training) || !x.U32(out uint xp)
|| !x.U32(out uint init) || !x.U32(out uint res) || !x.F64(out double last))
return false;
s = new SkillInfo(id, ranks, adj, training, xp, init, res, last);
return true;
}
private delegate bool EntryReader(ref NetReader r, uint key);
/// <summary>A packed hash table: u16 count, u16 buckets, then entries (u32 key + the rest).</summary>
private static bool Table(ref NetReader r, int minEntry, EntryReader entry)
{
if (!r.TableCount(out int n, minEntry)) return false;
for (int i = 0; i < n; i++)
if (!r.U32(out uint k) || !entry(ref r, k)) return false;
return true;
}
public static bool ReadEnchantment(ref NetReader r, out Enchantment e)
{
e = default;
if (!r.U16(out ushort spell) || !r.U16(out ushort layer) || !r.U16(out ushort cat) || !r.U16(out ushort hasSet)
|| !r.U32(out uint power) || !r.F64(out double start) || !r.F64(out double dur) || !r.U32(out uint caster)
|| !r.F32(out float dmod) || !r.F32(out float dlim) || !r.F64(out double last)
|| !r.U32(out uint smType) || !r.U32(out uint smKey) || !r.F32(out float smVal))
return false;
uint set = 0;
if (hasSet != 0 && !r.U32(out set)) return false;
e = new Enchantment(spell, layer, cat, power, start, dur, caster, dmod, dlim, last, smType, smKey, smVal, set);
return true;
}
public static bool ReadEnchantmentList(ref NetReader r, List<Enchantment> into)
{
if (!r.ListCount(out int n, EnchantmentSize)) return false;
for (int i = 0; i < n; i++)
{
if (!ReadEnchantment(ref r, out Enchantment e)) return false;
into.Add(e);
}
return true;
}
/// <summary>Registry: mask, then multiplicative, additive, cooldown lists, then one vitae enchantment.</summary>
private static bool ReadRegistry(ref NetReader r, List<Enchantment> into)
{
if (!r.U32(out uint mask)) return false;
if ((mask & 0x1) != 0 && !ReadEnchantmentList(ref r, into)) return false;
if ((mask & 0x2) != 0 && !ReadEnchantmentList(ref r, into)) return false;
if ((mask & 0x8) != 0 && !ReadEnchantmentList(ref r, into)) return false;
if ((mask & 0x4) != 0)
{
if (!ReadEnchantment(ref r, out Enchantment v)) return false;
into.Add(v);
}
return true;
}
private static bool ReadLists(ref NetReader r, PlayerDescriptionData pd)
{
if (!r.ListCount(out int n, 8)) return false;
for (int i = 0; i < n; i++)
{
if (!r.U32(out uint id) || !r.U32(out uint type)) return false;
pd.Inventory.Add(new PackEntry(id, type));
}
if (!r.ListCount(out int e, 12)) return false;
for (int i = 0; i < e; i++)
{
if (!r.U32(out uint id) || !r.U32(out uint loc) || !r.U32(out uint pri)) return false;
pd.Equipped.Add(new EquippedEntry(id, loc, pri));
}
return true;
}
private static bool FindListsFromEnd(ReadOnlySpan<byte> body, int earliest, PlayerDescriptionData pd)
{
int bestTotal = -1, bestI = 0, bestE = 0, bestPI = 0, bestPE = 0;
int end = body.Length;
for (int e = 0; ; e++)
{
int pE = end - 4 - 12 * e;
if (pE < earliest + 4) break;
if (U32(body, pE) != (uint)e || !EquippedOk(body, pE + 4, e)) continue;
for (int i = 0; ; i++)
{
int pI = pE - 4 - 8 * i;
if (pI < earliest) break;
if (U32(body, pI) != (uint)i || !InventoryOk(body, pI + 4, i)) continue;
if (i + e > bestTotal) { bestTotal = i + e; bestI = i; bestE = e; bestPI = pI; bestPE = pE; }
}
}
if (bestTotal < 0) return false;
for (int k = 0; k < bestI; k++)
pd.Inventory.Add(new PackEntry(U32(body, bestPI + 4 + 8 * k), U32(body, bestPI + 8 + 8 * k)));
for (int k = 0; k < bestE; k++)
pd.Equipped.Add(new EquippedEntry(U32(body, bestPE + 4 + 12 * k), U32(body, bestPE + 8 + 12 * k), U32(body, bestPE + 12 + 12 * k)));
return true;
}
private static uint U32(ReadOnlySpan<byte> b, int at) => BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(at));
// Object ids are far above counts, masks and types.
private const uint MinId = 0x1000;
private static bool InventoryOk(ReadOnlySpan<byte> b, int at, int n)
{
bool sawPackSlot = false;
for (int k = 0; k < n; k++)
{
uint id = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(at + 8 * k));
uint type = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(at + 8 * k + 4));
if (id < MinId || type > 2) return false;
if (type != 0) sawPackSlot = true;
else if (sawPackSlot) return false; // ordinary items come first
}
return true;
}
private static bool EquippedOk(ReadOnlySpan<byte> b, int at, int n)
{
for (int k = 0; k < n; k++)
{
uint id = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(at + 12 * k));
uint loc = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(at + 12 * k + 4));
if (id < MinId || loc == 0 || (loc & 0x80000000) != 0) return false;
}
return true;
}
}

View file

@ -0,0 +1,164 @@
// ============================================================================
// RynthCore.Headless - Messages/WorldMessages.cs
// Opcodes and readers for the messages that keep the world model current:
// positions, motion, state, inventory moves, vitals/attributes/skills, enchantments,
// use/attack results and combat notices. Property updates (0x02CD-0x02DA) and the
// identify reply (event 0x00C9) use the engine's PropertyWire.
//
// The Private/Public Update* messages start with a one-byte sequence, so their fields
// are not 4-byte aligned.
// ============================================================================
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Messages;
internal static class WorldOpcode
{
public const uint ParentEvent = 0xF749, PickupEvent = 0xF74A, SetState = 0xF74B, UpdateMotion = 0xF74C,
VectorUpdate = 0xF74E, UpdatePosition = 0xF748, UpdateObject = 0xF7DB;
public const uint SetStackSize = 0x0197, InventoryRemoveObject = 0x0024;
public const uint PrivateUpdateSkill = 0x02DD, PrivateUpdateAttribute = 0x02E3, PrivateUpdateVital = 0x02E7,
PublicUpdateVital = 0x02E8, PrivateUpdateVitalCurrent = 0x02E9;
public const uint PrivateUpdatePosition = 0x02DB, PublicUpdatePosition = 0x02DC;
}
internal static class WorldEvent
{
public const uint PutObjInContainer = 0x0022, WieldObject = 0x0023, CloseGroundContainer = 0x0052,
InventoryServerSaveFailed = 0x00A0, IdentifyObjectResponse = 0x00C9, ViewContents = 0x0196,
PutObjectIn3D = 0x019A, MagicRemoveSpell = 0x01A8, AttackDone = 0x01A7, VictimNotification = 0x01AC,
KillerNotification = 0x01AD, AttackerNotification = 0x01B1, DefenderNotification = 0x01B2,
EvasionAttacker = 0x01B3, EvasionDefender = 0x01B4, CombatCommenceAttack = 0x01B8, UpdateHealth = 0x01C0,
UseDone = 0x01C7, WeenieError = 0x028A, WeenieErrorWithString = 0x028B, MagicUpdateSpell = 0x02C1,
MagicUpdateEnchantment = 0x02C2, MagicRemoveEnchantment = 0x02C3, MagicUpdateMultipleEnchantments = 0x02C4,
MagicRemoveMultipleEnchantments = 0x02C5, MagicPurgeEnchantments = 0x02C6, MagicDispelEnchantment = 0x02C7,
MagicDispelMultipleEnchantments = 0x02C8, TransientString = 0x02EB, MagicPurgeBadEnchantments = 0x0312;
}
/// <summary>UpdatePosition 0xF748.</summary>
internal readonly record struct PositionUpdate(uint Id, uint Flags, WorldPosition Position, float Vx, float Vy, float Vz,
ushort InstanceSeq, ushort PositionSeq, ushort TeleportSeq, ushort ForcePositionSeq)
{
public bool Grounded => (Flags & 0x04) != 0;
}
/// <summary>UpdateMotion 0xF74C header plus the stance and (for an interpreted state) the forward command.</summary>
/// <summary>
/// UpdateMotion 0xF74C header, the stance, and for the move-to types (6 MoveToObject,
/// 7 MoveToPosition) the target, its origin and how close to get (DistanceToObject).
/// </summary>
public readonly record struct MotionUpdate(uint Id, ushort InstanceSeq, ushort MovementSeq, ushort ServerControlSeq,
bool Autonomous, byte MovementType, ushort Stance, uint TargetId, WorldPosition? Origin, float DistanceToObject);
internal static class WorldMessages
{
public static bool TryUpdatePosition(ReadOnlySpan<byte> b, out PositionUpdate u)
{
u = default;
var r = new NetReader(b);
if (!r.U32(out uint id) || !r.U32(out uint f) || !r.U32(out uint cell)
|| !r.F32(out float x) || !r.F32(out float y) || !r.F32(out float z))
return false;
float qw = 0, qx = 0, qy = 0, qz = 0;
if ((f & 0x08) == 0 && !r.F32(out qw)) return false;
if ((f & 0x10) == 0 && !r.F32(out qx)) return false;
if ((f & 0x20) == 0 && !r.F32(out qy)) return false;
if ((f & 0x40) == 0 && !r.F32(out qz)) return false;
float vx = 0, vy = 0, vz = 0;
if ((f & 0x01) != 0 && (!r.F32(out vx) || !r.F32(out vy) || !r.F32(out vz))) return false;
if ((f & 0x02) != 0 && !r.Skip(4)) return false;
if (!r.U16(out ushort inst) || !r.U16(out ushort pos) || !r.U16(out ushort tele) || !r.U16(out ushort force)) return false;
u = new PositionUpdate(id, f, new WorldPosition(cell, x, y, z, qw, qx, qy, qz), vx, vy, vz, inst, pos, tele, force);
return true;
}
public static bool TryUpdateMotion(ReadOnlySpan<byte> b, out MotionUpdate u)
{
u = default;
var r = new NetReader(b);
if (!r.U32(out uint id) || !r.U16(out ushort inst) || !r.U16(out ushort mov) || !r.U16(out ushort sc)
|| !r.U8(out byte auto) || !r.Skip(1) || !r.U8(out byte type) || !r.U8(out _) || !r.U16(out ushort stance))
return false;
uint target = 0;
WorldPosition? origin = null;
float dist = 0;
if (type is 6 or 8) r.U32(out target); // MoveToObject / TurnToObject: target guid first
if (type is 6 or 7 && r.U32(out uint cell) && r.F32(out float x) && r.F32(out float y) && r.F32(out float z))
{
origin = new WorldPosition(cell, x, y, z, 1, 0, 0, 0);
if (r.U32(out _) && r.F32(out float d)) dist = d; // MoveToParameters: flags, distance to object, ...
}
u = new MotionUpdate(id, inst, mov, sc, auto != 0, type, stance, target, origin, dist);
return true;
}
public static bool TrySetStackSize(ReadOnlySpan<byte> b, out uint id, out uint size, out uint value)
{
id = size = value = 0;
var r = new NetReader(b);
return r.Skip(1) && r.U32(out id) && r.U32(out size) && r.U32(out value);
}
/// <summary>PrivateUpdateAttribute 0x02E3: seq, attribute 1..6, ranks, init, xp.</summary>
public static bool TryPrivateAttribute(ReadOnlySpan<byte> b, out uint attr, out AttributeInfo a)
{
a = default; attr = 0;
var r = new NetReader(b);
if (!r.Skip(1) || !r.U32(out attr) || !r.U32(out uint ranks) || !r.U32(out uint init) || !r.U32(out uint xp)) return false;
a = new AttributeInfo(ranks, init, xp);
return true;
}
/// <summary>PrivateUpdateVital 0x02E7: seq, vital (1 MaxHealth, 3 MaxStamina, 5 MaxMana), ranks, init, xp, current.</summary>
public static bool TryPrivateVital(ReadOnlySpan<byte> b, out uint vital, out VitalInfo v)
{
v = default; vital = 0;
var r = new NetReader(b);
if (!r.Skip(1) || !r.U32(out uint id) || !r.U32(out uint ranks) || !r.U32(out uint init) || !r.U32(out uint xp)
|| !r.U32(out uint cur)) return false;
vital = (id + 1) / 2; // 1,3,5 -> 1,2,3
v = new VitalInfo(ranks, init, xp, cur);
return true;
}
/// <summary>PrivateUpdateAttribute2ndLevel 0x02E9: seq, vital (2 Health, 4 Stamina, 6 Mana), current.</summary>
public static bool TryPrivateVitalCurrent(ReadOnlySpan<byte> b, out uint vital, out uint current)
{
vital = current = 0;
var r = new NetReader(b);
if (!r.Skip(1) || !r.U32(out uint id) || !r.U32(out current)) return false;
vital = id / 2; // 2,4,6 -> 1,2,3
return true;
}
/// <summary>PrivateUpdateSkill 0x02DD: seq, then the 32-byte skill entry.</summary>
public static bool TryPrivateSkill(ReadOnlySpan<byte> b, out SkillInfo s)
{
s = default;
var r = new NetReader(b);
return r.Skip(1) && r.U32(out uint id) && PlayerDescription.ReadSkillBody(ref r, id, out s);
}
public static bool TryLayeredSpell(ref NetReader r, out ushort spell, out ushort layer)
{
layer = 0;
return r.U16(out spell) && r.U16(out layer);
}
public static bool TryU32(ReadOnlySpan<byte> b, out uint v)
{
var r = new NetReader(b);
return r.U32(out v);
}
public static bool TryU32U32(ReadOnlySpan<byte> b, out uint a, out uint c)
{
c = 0;
var r = new NetReader(b);
return r.U32(out a) && r.U32(out c);
}
}
/// <summary>Combat notices (attacker/defender/evasion/kill) as one simple shape.</summary>
public readonly record struct CombatNotice(uint EventType, string Name, uint DamageType, double HealthPercent, uint Damage, bool Critical);

View file

@ -0,0 +1,49 @@
// ============================================================================
// RynthCore.Headless - Movement/DoorObstacles.cs
// Doors are server objects, not in the dats. A door blocks exactly while its physics
// state lacks Ethereal (0x4): ACE makes it ethereal (SetState) as it opens and solid
// again when the close animation ends. This keeps the walker's dynamic obstacles in step
// with the doors the world model knows (CreateObject / SetState / delete).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Collision;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Walking;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Movement;
public sealed class DoorObstacles
{
private const uint DoorFlag = 0x1000; // ObjectDescriptionFlag.Door
private const uint Ethereal = 0x4; // PhysicsState.Ethereal
private readonly ModelTriangles _models;
public DynamicObstacles Obstacles { get; } = new();
public DoorObstacles(ModelReader models, DatDatabase portal) => _models = new ModelTriangles(models, portal);
/// <summary>Follows one session's world model.</summary>
public void Track(WorldState world)
{
world.ObjectCreated += Update;
world.ObjectUpdated += Update;
world.ObjectDeleted += id => Obstacles.Remove(id);
world.ObjectStateChanged += Update;
}
public void Update(WorldObject o)
{
if ((o.Desc.DescriptionFlags & DoorFlag) == 0) return;
if ((o.PhysicsState & Ethereal) != 0 || o.Position is not { } p || o.Desc.SetupId == 0)
{
Obstacles.Remove(o.Id);
return;
}
var tris = new List<CollisionTri>();
_models.Append(o.Desc.SetupId, new Vector3(p.X, p.Y, p.Z), new Quaternion(p.Qx, p.Qy, p.Qz, p.Qw), o.Desc.Scale ?? 1f, tris);
Obstacles.Set(o.Id, p.Cell >> 16, tris.Select(t => (t.A, t.B, t.C, t.Normal)));
}
}

View file

@ -0,0 +1,90 @@
// ============================================================================
// RynthCore.Headless - Movement/GeometryWalk.cs
// IWalkGeometry on RynthCore.Geometry's Walker: terrain heights, indoor cells and
// their walls, the outdoor world (buildings, statics, scenery) and closed doors.
// One per process is enough; the dat readers and caches inside are thread-safe and
// shared by every session (each session's doors: TrackDoors).
// ============================================================================
using System.Numerics;
using RynthCore.Geometry.Cells;
using RynthCore.Geometry.Collision;
using RynthCore.Geometry.Dat;
using RynthCore.Geometry.Models;
using RynthCore.Geometry.Terrain;
using RynthCore.Geometry.Walking;
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Movement;
public sealed class GeometryWalk : IWalkGeometry, IDisposable
{
private readonly DatDatabase _portal, _cell;
public TerrainSampler Terrain { get; }
public IndoorWorld Indoor { get; }
public ModelReader Models { get; }
public Walker Walker { get; private set; }
public OutdoorCollision World { get; }
public DoorObstacles Doors { get; }
private GeometryWalk(DatDatabase portal, DatDatabase cell)
{
_portal = portal;
_cell = cell;
Terrain = new TerrainSampler(portal, cell);
Models = new ModelReader(portal);
Indoor = new IndoorWorld(cell, portal, Models);
World = new OutdoorCollision(cell, portal, Terrain, Models, Indoor);
Doors = new DoorObstacles(Models, portal);
Walker = new Walker(Terrain, Indoor, new CompositeObstacles(new StaticObstacles(World), Doors.Obstacles));
}
/// <summary>Opens the dats in <paramref name="acFolder"/> (read-only, shared). Null if they aren't there.</summary>
public static GeometryWalk? Open(string acFolder)
{
var portal = new DatDatabase();
var cell = new DatDatabase();
if (!portal.Open(Path.Combine(acFolder, "client_portal.dat")) || !cell.Open(Path.Combine(acFolder, "client_cell_1.dat")))
{
portal.Dispose();
cell.Dispose();
return null;
}
return new GeometryWalk(portal, cell);
}
/// <summary>Keeps the closed doors of a session's world as obstacles.</summary>
public void TrackDoors(WorldState world) => Doors.Track(world);
public WalkResult Step(WorldPosition start, float dx, float dy)
{
StepResult r = Walker.Step(start.Cell, new Vector3(start.X, start.Y, start.Z), dx, dy);
var p = start with { Cell = r.Cell, X = r.Position.X, Y = r.Position.Y, Z = r.Position.Z };
return new WalkResult(p, r.Blocked, r.Why);
}
public IReadOnlyList<WorldPosition>? Plan(WorldPosition start, WorldPosition to, float stop) => Plan(start, to, stop, nearest: false);
/// <summary>With <paramref name="nearest"/>, an unreachable goal gives a path to the closest reachable point.</summary>
public IReadOnlyList<WorldPosition>? Plan(WorldPosition start, WorldPosition to, float stop, bool nearest)
{
// Don't search toward a spot nobody can stand on (inside a wall, off a ledge, in the void)
// unless it's somewhere the server wants us near (its move-to: get as close as the walls allow).
// An object to walk up to (stop >= 0.5) is itself solid, so that check is skipped then.
if (!nearest && stop < 0.5f && !Walker.CanStand(to.Cell, new Vector3(to.X, to.Y, to.Z))) return null;
var planner = new LocalPlanner(Walker);
(float dx, float dy) = Session.ClientSession.Delta(start, to);
var goal = new Vector2(start.X + dx, start.Y + dy);
List<PathPoint>? path = planner.Find(new PathPoint(start.Cell, new Vector3(start.X, start.Y, start.Z)), goal, stop, nearest);
return path?.Skip(1).Select(p => start with { Cell = p.Cell, X = p.Position.X, Y = p.Position.Y, Z = p.Position.Z }).ToList();
}
public void Dispose()
{
Terrain.Dispose();
_portal.Dispose();
_cell.Dispose();
}
}

View file

@ -0,0 +1,41 @@
// ============================================================================
// RynthCore.Headless - Movement/IWalkGeometry.cs
// How a step lands in the world: ground height, walls, and which cell the player is
// in afterwards (ACE trusts the client's cell id, so it has to be right). The real
// implementation sits on RynthCore.Geometry (terrain, indoor cells, models); FlatWalk
// is the fallback without dats: straight line, height kept, outdoor cell recomputed.
// ============================================================================
using RynthCore.Headless.Messages;
using RynthCore.Headless.Session;
namespace RynthCore.Headless.Movement;
/// <summary>Where a step ended. Blocked = it could not go (all) the way.</summary>
public readonly record struct WalkResult(WorldPosition Position, bool Blocked, string? Why = null);
public interface IWalkGeometry
{
/// <summary>
/// Moves from <paramref name="from"/> by (dx, dy) metres on the ground plane, in the frame
/// of from's landblock (so x/y may leave 0..192 outdoors). Returns the resolved position:
/// height on the ground or floor, cell id, and whether a wall or ledge stopped it.
/// The rotation is copied from <paramref name="from"/>.
/// </summary>
WalkResult Step(WorldPosition from, float dx, float dy);
/// <summary>
/// A short walkable detour from <paramref name="from"/> to within <paramref name="stop"/> of
/// <paramref name="to"/> (turning points after the start), or null when there is none or no planner.
/// </summary>
IReadOnlyList<WorldPosition>? Plan(WorldPosition from, WorldPosition to, float stop) => null;
/// <summary>As <see cref="Plan(WorldPosition, WorldPosition, float)"/>; with <paramref name="nearest"/> an unreachable goal gives a path to the closest reachable point.</summary>
IReadOnlyList<WorldPosition>? Plan(WorldPosition from, WorldPosition to, float stop, bool nearest) => Plan(from, to, stop);
}
public sealed class FlatWalk : IWalkGeometry
{
public WalkResult Step(WorldPosition from, float dx, float dy)
=> new(ClientSession.Relocate(from, from.X + dx, from.Y + dy), false);
}

View file

@ -0,0 +1,25 @@
// ============================================================================
// RynthCore.Headless - Net/Hash32.cs
// AC's packet checksum primitive: seed = length << 16, plus every little-endian
// u32 word, plus the 1-3 tail bytes placed high (shifts 24, 16, 8). Wraps mod 2^32.
// The length is part of the seed, so how data is split into spans matters.
// ============================================================================
using System.Buffers.Binary;
namespace RynthCore.Headless.Net;
internal static class Hash32
{
public static uint Compute(ReadOnlySpan<byte> data)
{
uint h = (uint)data.Length << 16;
int words = data.Length & ~3;
for (int i = 0; i < words; i += 4)
h += BinaryPrimitives.ReadUInt32LittleEndian(data.Slice(i));
int shift = 24;
for (int i = words; i < data.Length; i++, shift -= 8)
h += (uint)data[i] << shift;
return h;
}
}

View file

@ -0,0 +1,95 @@
// ============================================================================
// RynthCore.Headless - Net/Isaac.cs
// Bob Jenkins' ISAAC (public domain), with AC's seeding: the generator is initialised
// as if the seed array were all zero, then a = b = c = the 32-bit connection seed and
// one round runs. Words are handed out from index 255 down to 0, then another round.
//
// ServerSeed keys the server's packets, ClientSeed keys ours; each encrypted packet
// takes one word.
// ============================================================================
namespace RynthCore.Headless.Net;
internal sealed class Isaac
{
private const uint Golden = 0x9E3779B9;
private readonly uint[] _mem = new uint[256];
private readonly uint[] _rsl = new uint[256];
private uint _a, _b, _c;
private int _next;
public Isaac(uint seed)
{
uint a = Golden, b = Golden, c = Golden, d = Golden, e = Golden, f = Golden, g = Golden, h = Golden;
for (int i = 0; i < 4; i++)
Mix(ref a, ref b, ref c, ref d, ref e, ref f, ref g, ref h);
// Standard two-pass fill; _rsl is all zero here, so pass one adds nothing.
for (int pass = 0; pass < 2; pass++)
{
uint[] src = pass == 0 ? _rsl : _mem;
for (int i = 0; i < 256; i += 8)
{
a += src[i]; b += src[i + 1]; c += src[i + 2]; d += src[i + 3];
e += src[i + 4]; f += src[i + 5]; g += src[i + 6]; h += src[i + 7];
Mix(ref a, ref b, ref c, ref d, ref e, ref f, ref g, ref h);
_mem[i] = a; _mem[i + 1] = b; _mem[i + 2] = c; _mem[i + 3] = d;
_mem[i + 4] = e; _mem[i + 5] = f; _mem[i + 6] = g; _mem[i + 7] = h;
}
}
_a = _b = _c = seed;
Round();
}
/// <summary>The next key word.</summary>
public uint Next()
{
uint v = _rsl[_next];
if (_next == 0)
{
Round();
_next = 255;
}
else
{
_next--;
}
return v;
}
private void Round()
{
_b += ++_c;
for (int i = 0; i < 256; i++)
{
uint x = _mem[i];
switch (i & 3)
{
case 0: _a ^= _a << 13; break;
case 1: _a ^= _a >> 6; break;
case 2: _a ^= _a << 2; break;
case 3: _a ^= _a >> 16; break;
}
_a += _mem[(i + 128) & 255];
uint y = _mem[(int)((x >> 2) & 255)] + _a + _b;
_mem[i] = y;
_b = _mem[(int)((y >> 10) & 255)] + x;
_rsl[i] = _b;
}
_next = 255;
}
private static void Mix(ref uint a, ref uint b, ref uint c, ref uint d, ref uint e, ref uint f, ref uint g, ref uint h)
{
a ^= b << 11; d += a; b += c;
b ^= c >> 2; e += b; c += d;
c ^= d << 8; f += c; d += e;
d ^= e >> 16; g += d; e += f;
e ^= f << 10; h += e; f += g;
f ^= g >> 4; a += f; g += h;
g ^= h << 8; b += g; h += a;
h ^= a >> 9; c += h; a += b;
}
}

View file

@ -0,0 +1,202 @@
// ============================================================================
// RynthCore.Headless - Net/Packet.cs
// One AC datagram: the 20-byte header, the optional sections (in ascending flag-bit
// order) and the blob fragments, plus the checksum that seals them.
//
// Header: seq u32, flags u32, checksum u32, id u16, time u16, size u16, iteration u16.
// Checksum = Hash32(header with checksum = 0xBADD70DD)
// + payload, where payload = Hash32(all optional bytes)
// + sum over fragments of Hash32(frag header) + Hash32(frag data)
// and, with EncryptedChecksum, payload is XORed with one ISAAC word first.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Engine.Net;
namespace RynthCore.Headless.Net;
/// <summary>One message fragment as it travels: 16-byte header, then data.</summary>
internal readonly record struct Fragment(uint Sequence, uint Id, ushort Count, ushort Index, ushort Queue, byte[] Data)
{
public const int HeaderSize = 16;
public const int MaxSize = 464;
public const int MaxData = MaxSize - HeaderSize; // 448
}
internal static class Packet
{
public const int HeaderSize = 20;
public const int MaxBody = 464;
public const uint ChecksumPlaceholder = 0xBADD70DD;
public static uint HeaderHash(ReadOnlySpan<byte> header20)
{
Span<byte> h = stackalloc byte[HeaderSize];
header20.Slice(0, HeaderSize).CopyTo(h);
BinaryPrimitives.WriteUInt32LittleEndian(h.Slice(8), ChecksumPlaceholder);
return Hash32.Compute(h);
}
/// <summary>Payload hash of a whole datagram: optional sections as one span, then each fragment's header and data.</summary>
public static bool TryPayloadHash(ReadOnlySpan<byte> datagram, int optionalEnd, out uint hash)
{
hash = Hash32.Compute(datagram.Slice(HeaderSize, optionalEnd - HeaderSize));
uint flags = BinaryPrimitives.ReadUInt32LittleEndian(datagram.Slice(4));
if ((flags & PacketFlags.BlobFragments) == 0)
return true;
int end = HeaderSize + BinaryPrimitives.ReadUInt16LittleEndian(datagram.Slice(16));
int pos = optionalEnd;
while (pos < end)
{
if (pos + Fragment.HeaderSize > end) return false;
int size = BinaryPrimitives.ReadUInt16LittleEndian(datagram.Slice(pos + 10));
if (size < Fragment.HeaderSize || pos + size > end) return false;
hash += Hash32.Compute(datagram.Slice(pos, Fragment.HeaderSize));
hash += Hash32.Compute(datagram.Slice(pos + Fragment.HeaderSize, size - Fragment.HeaderSize));
pos += size;
}
return true;
}
/// <summary>
/// Builds a datagram. <paramref name="optional"/> is the optional-section bytes, already in
/// flag order. With a key the checksum is encrypted (and the flag added). Returns the bytes
/// and the sealed payload (payload hash, XORed with the key if any) for byte-identical resends.
/// </summary>
public static byte[] Build(uint seq, uint flags, ushort id, ushort time, ushort iteration,
ReadOnlySpan<byte> optional, IReadOnlyList<Fragment>? fragments, uint? key, out uint sealedPayload)
{
if (fragments is { Count: > 0 }) flags |= PacketFlags.BlobFragments;
if (key.HasValue) flags |= PacketFlags.EncryptedChecksum;
int size = optional.Length;
if (fragments != null)
foreach (Fragment f in fragments)
size += Fragment.HeaderSize + f.Data.Length;
if (size > MaxBody)
throw new InvalidOperationException($"packet body {size} > {MaxBody}");
var d = new byte[HeaderSize + size];
Span<byte> s = d;
BinaryPrimitives.WriteUInt32LittleEndian(s, seq);
BinaryPrimitives.WriteUInt32LittleEndian(s.Slice(4), flags);
BinaryPrimitives.WriteUInt16LittleEndian(s.Slice(12), id);
BinaryPrimitives.WriteUInt16LittleEndian(s.Slice(14), time);
BinaryPrimitives.WriteUInt16LittleEndian(s.Slice(16), (ushort)size);
BinaryPrimitives.WriteUInt16LittleEndian(s.Slice(18), iteration);
optional.CopyTo(s.Slice(HeaderSize));
uint payload = Hash32.Compute(optional);
int pos = HeaderSize + optional.Length;
if (fragments != null)
{
foreach (Fragment f in fragments)
{
Span<byte> fh = s.Slice(pos, Fragment.HeaderSize);
BinaryPrimitives.WriteUInt32LittleEndian(fh, f.Sequence);
BinaryPrimitives.WriteUInt32LittleEndian(fh.Slice(4), f.Id);
BinaryPrimitives.WriteUInt16LittleEndian(fh.Slice(8), f.Count);
BinaryPrimitives.WriteUInt16LittleEndian(fh.Slice(10), (ushort)(Fragment.HeaderSize + f.Data.Length));
BinaryPrimitives.WriteUInt16LittleEndian(fh.Slice(12), f.Index);
BinaryPrimitives.WriteUInt16LittleEndian(fh.Slice(14), f.Queue);
f.Data.CopyTo(s.Slice(pos + Fragment.HeaderSize));
payload += Hash32.Compute(fh) + Hash32.Compute(f.Data);
pos += Fragment.HeaderSize + f.Data.Length;
}
}
sealedPayload = key.HasValue ? payload ^ key.Value : payload;
Seal(d, sealedPayload);
return d;
}
/// <summary>Writes the checksum from the (current) header and an already sealed payload.</summary>
public static void Seal(byte[] datagram, uint sealedPayload)
=> BinaryPrimitives.WriteUInt32LittleEndian(datagram.AsSpan(8), HeaderHash(datagram) + sealedPayload);
}
/// <summary>A received datagram's header and optional sections.</summary>
internal sealed class InboundPacket
{
public uint Sequence, Flags, Checksum;
public ushort Id, Time, Size, Iteration;
public int OptionalEnd; // offset where fragments start
public uint[] Naks = Array.Empty<uint>();
public uint[] Rejects = Array.Empty<uint>();
public uint Ack;
public double TimeSync;
public ConnectRequestData? Connect;
public float EchoClientTime, EchoServerDelta;
public bool Has(uint flag) => (Flags & flag) != 0;
public bool Encrypted => Has(PacketFlags.EncryptedChecksum);
/// <summary>Header and optional sections; false if the sizes don't add up or a section can't be sized.</summary>
public static bool TryParse(ReadOnlySpan<byte> d, out InboundPacket p)
{
p = new InboundPacket();
if (d.Length < Packet.HeaderSize) return false;
p.Sequence = BinaryPrimitives.ReadUInt32LittleEndian(d);
p.Flags = BinaryPrimitives.ReadUInt32LittleEndian(d.Slice(4));
p.Checksum = BinaryPrimitives.ReadUInt32LittleEndian(d.Slice(8));
p.Id = BinaryPrimitives.ReadUInt16LittleEndian(d.Slice(12));
p.Time = BinaryPrimitives.ReadUInt16LittleEndian(d.Slice(14));
p.Size = BinaryPrimitives.ReadUInt16LittleEndian(d.Slice(16));
p.Iteration = BinaryPrimitives.ReadUInt16LittleEndian(d.Slice(18));
int end = Packet.HeaderSize + p.Size;
if (end > d.Length) return false;
if ((p.Flags & PacketFlags.Unsized & ~PacketFlags.LoginRequest) != 0) return false;
int pos = Packet.HeaderSize;
bool Need(int n, ref int at) => at + n <= end;
uint U32(ReadOnlySpan<byte> s, int at) => BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(at));
if (p.Has(PacketFlags.ServerSwitch)) { if (!Need(8, ref pos)) return false; pos += 8; }
if (p.Has(PacketFlags.RequestRetransmit) && !ReadList(d, end, ref pos, out p.Naks)) return false;
if (p.Has(PacketFlags.RejectRetransmit) && !ReadList(d, end, ref pos, out p.Rejects)) return false;
if (p.Has(PacketFlags.AckSequence)) { if (!Need(4, ref pos)) return false; p.Ack = U32(d, pos); pos += 4; }
if (p.Has(PacketFlags.LoginRequest)) pos = end; // the rest of the body (client to server only)
if (p.Has(PacketFlags.WorldLoginRequest)) { if (!Need(8, ref pos)) return false; pos += 8; }
if (p.Has(PacketFlags.ConnectRequest))
{
if (!Need(32, ref pos)) return false;
p.Connect = new ConnectRequestData(
BinaryPrimitives.ReadDoubleLittleEndian(d.Slice(pos)),
BinaryPrimitives.ReadUInt64LittleEndian(d.Slice(pos + 8)),
U32(d, pos + 16), U32(d, pos + 20), U32(d, pos + 24));
pos += 32;
}
if (p.Has(PacketFlags.ConnectResponse)) { if (!Need(8, ref pos)) return false; pos += 8; }
if (p.Has(PacketFlags.NetError)) { if (!Need(8, ref pos)) return false; pos += 8; }
if (p.Has(PacketFlags.NetErrorDisconnect)) { if (!Need(8, ref pos)) return false; pos += 8; }
if (p.Has(PacketFlags.CICMDCommand)) { if (!Need(8, ref pos)) return false; pos += 8; }
if (p.Has(PacketFlags.TimeSync)) { if (!Need(8, ref pos)) return false; p.TimeSync = BinaryPrimitives.ReadDoubleLittleEndian(d.Slice(pos)); pos += 8; }
if (p.Has(PacketFlags.EchoRequest)) { if (!Need(4, ref pos)) return false; pos += 4; }
if (p.Has(PacketFlags.EchoResponse))
{
if (!Need(8, ref pos)) return false;
p.EchoClientTime = BinaryPrimitives.ReadSingleLittleEndian(d.Slice(pos));
p.EchoServerDelta = BinaryPrimitives.ReadSingleLittleEndian(d.Slice(pos + 4));
pos += 8;
}
if (p.Has(PacketFlags.Flow)) { if (!Need(6, ref pos)) return false; pos += 6; }
p.OptionalEnd = pos;
return true;
}
private static bool ReadList(ReadOnlySpan<byte> d, int end, ref int pos, out uint[] list)
{
list = Array.Empty<uint>();
if (pos + 4 > end) return false;
uint n = BinaryPrimitives.ReadUInt32LittleEndian(d.Slice(pos));
pos += 4;
if (n > (uint)((end - pos) / 4)) return false;
list = new uint[n];
for (int i = 0; i < n; i++, pos += 4)
list[i] = BinaryPrimitives.ReadUInt32LittleEndian(d.Slice(pos));
return true;
}
}
/// <summary>The server's ConnectRequest: its clock, the cookie to echo, our net id and both ISAAC seeds.</summary>
internal sealed record ConnectRequestData(double ServerTime, ulong Cookie, uint ClientId, uint ServerSeed, uint ClientSeed);

View file

@ -0,0 +1,390 @@
// ============================================================================
// RynthCore.Headless - Net/Transport.cs
// The reliable layer under a session: the connect handshake, sequence numbers,
// checksums and ISAAC keys, acks, retransmit requests (NAKs) both ways, and
// reassembly of the server's fragments into whole messages.
//
// Rules we follow (see docs\HEADLESS.md):
// - LoginRequest is seq 0, ConnectResponse seq 1 (to port+1); our next sequenced
// packet is 2. Fragment sequence starts at 1.
// - Every new sequenced packet is encrypted with the next ClientSeed word. A resend is
// the same packet with the Retransmission flag: same payload, same key, header
// re-hashed. (The server matches keys in a look-ahead window, so re-keying a resend
// would waste keystream.)
// - Ack-only, NAK and Disconnect packets are plain and reuse our current sequence.
// - The server only resends when asked: a sequence gap is NAKed until it is filled or
// the server rejects it.
// - Server keys are matched in a look-ahead window like the server does with ours; a
// mismatch is counted, not fatal.
// Single-threaded: every call comes from the session's tick.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Engine.Net;
namespace RynthCore.Headless.Net;
/// <summary>Where datagrams go. <c>connectPort</c> = the server's port+1 (ConnectResponse only).</summary>
internal interface IDatagramLink
{
void Send(ReadOnlySpan<byte> datagram, bool connectPort);
bool TryReceive(out byte[] datagram);
}
/// <summary>Message groups (queue ids) in fragment headers. The server ignores them on input.</summary>
internal static class MessageQueue
{
public const ushort Event = 1, Control = 2, Weenie = 3, Login = 4, Database = 5, UI = 9;
}
internal sealed unsafe class Transport : IServerMessageSink
{
public const long ConnectResponseDelayMs = 200;
public const long ConnectResponseRepeatMs = 333;
public const long AckIntervalMs = 1000;
public const long KeepAliveMs = 5000;
public const long NakRepeatMs = 1000;
public const int MaxNakTries = 10;
public const int MaxNaksPerPacket = 115;
private readonly IDatagramLink _link;
private readonly Func<long> _now;
private readonly long _startMs;
private readonly FragmentReassembler _reassembler = new();
private readonly Queue<byte[]> _messages = new();
// Connection
private ConnectRequestData? _connect;
private ushort _clientId, _iteration;
private long _connectResponseDue = -1;
private bool _serverTalked; // anything after the ConnectRequest
private bool _disconnected;
// Outbound
private Isaac? _outKeys;
private uint _seq; // last sequence we used
private uint _fragSeq;
private readonly Dictionary<uint, SentPacket> _sent = new();
// Inbound
private InboundKeys? _inKeys;
private uint _highest = 1; // the server's packets start at 2 after the ConnectRequest
private readonly SortedDictionary<uint, NakState> _missing = new();
private bool _ackDirty;
private long _lastSendMs, _lastAckMs;
private uint _lastAckSent;
private sealed class SentPacket { public required byte[] Data; public required uint Sealed; public bool Resent; }
private sealed class NakState { public long LastMs = -NakRepeatMs; public int Tries; }
public Transport(IDatagramLink link, Func<long> nowMs)
{
_link = link;
_now = nowMs;
_startMs = nowMs();
}
// ── state and counters ──────────────────────────────────────────────────
public bool Connected => _connect != null;
public bool ServerTalked => _serverTalked;
public ConnectRequestData? ConnectData => _connect;
public uint LastSequenceSent => _seq;
public uint HighestReceived => _highest;
public uint ContiguousReceived => _missing.Count == 0 ? _highest : _missing.Keys.First() - 1;
public IReadOnlyCollection<uint> Missing => _missing.Keys;
public long PacketsIn, PacketsOut, Resends, NaksSent, NakRequestsServed, Rejected, BadPackets, BadChecksums, Duplicates;
public double LastServerTime;
/// <summary>The local clock (ms) when <see cref="LastServerTime"/> arrived.</summary>
public long LastServerTimeAtMs;
// ── sending ─────────────────────────────────────────────────────────────
private ushort TimeField => (ushort)(1 + (_now() - _startMs) / 500);
private void Emit(byte[] d, bool connectPort = false)
{
_link.Send(d, connectPort);
PacketsOut++;
_lastSendMs = _now();
}
/// <summary>The first packet: seq 0, LoginRequest only, plain. The body is from <see cref="Messages.LoginRequest"/>.</summary>
public void SendLoginRequest(ReadOnlySpan<byte> loginBody)
=> Emit(Packet.Build(0, PacketFlags.LoginRequest, 0, TimeField, 0, loginBody, null, null, out _));
/// <summary>Queues one whole message (u32 opcode first); one packet per fragment.</summary>
public void SendMessage(ReadOnlySpan<byte> message, ushort queue)
{
if (_outKeys == null)
throw new InvalidOperationException("not connected");
uint fragSeq = ++_fragSeq;
int count = Math.Max(1, (message.Length + Fragment.MaxData - 1) / Fragment.MaxData);
for (int i = 0; i < count; i++)
{
int off = i * Fragment.MaxData;
byte[] data = message.Slice(off, Math.Min(Fragment.MaxData, message.Length - off)).ToArray();
var frag = new Fragment(fragSeq, 0x80000000, (ushort)count, (ushort)i, queue, data);
uint seq = ++_seq;
byte[] d = Packet.Build(seq, 0, _clientId, TimeField, _iteration, ReadOnlySpan<byte>.Empty,
new[] { frag }, _outKeys.Next(), out uint sealedPayload);
_sent[seq] = new SentPacket { Data = d, Sealed = sealedPayload };
Emit(d);
}
}
/// <summary>Ends the session at once (plain Disconnect at the current sequence).</summary>
public void SendDisconnect()
{
if (_connect == null || _disconnected) return;
_disconnected = true;
Emit(Packet.Build(_seq, PacketFlags.Disconnect, _clientId, TimeField, _iteration, ReadOnlySpan<byte>.Empty, null, null, out _));
}
private void SendAck()
{
uint ack = ContiguousReceived;
Span<byte> body = stackalloc byte[4];
BinaryPrimitives.WriteUInt32LittleEndian(body, ack);
Emit(Packet.Build(_seq, PacketFlags.AckSequence, _clientId, TimeField, _iteration, body, null, null, out _));
_ackDirty = false;
_lastAckMs = _now();
_lastAckSent = ack;
}
private void SendNaks(long now)
{
var ids = new List<uint>();
var giveUp = new List<uint>();
foreach ((uint seq, NakState st) in _missing)
{
if (now - st.LastMs < NakRepeatMs) continue;
if (st.Tries >= MaxNakTries) { giveUp.Add(seq); continue; }
st.LastMs = now;
st.Tries++;
ids.Add(seq);
if (ids.Count == MaxNaksPerPacket) break;
}
foreach (uint seq in giveUp) { _missing.Remove(seq); Rejected++; }
if (ids.Count == 0) return;
var w = new WireWriter(4 + ids.Count * 4);
w.U32((uint)ids.Count);
foreach (uint id in ids) w.U32(id);
Emit(Packet.Build(_seq, PacketFlags.RequestRetransmit, _clientId, TimeField, _iteration, w.Span, null, null, out _));
NaksSent++;
}
/// <summary>Handshake resends, acks, keepalive and NAKs. Call every tick.</summary>
public void Tick()
{
if (_connect == null || _disconnected) return;
long now = _now();
if (_connectResponseDue >= 0 && now >= _connectResponseDue)
{
if (_serverTalked)
{
_connectResponseDue = -1;
}
else
{
Span<byte> cookie = stackalloc byte[8];
BinaryPrimitives.WriteUInt64LittleEndian(cookie, _connect.Cookie);
Emit(Packet.Build(1, PacketFlags.ConnectResponse, 0, TimeField, 0, cookie, null, null, out _), connectPort: true);
_connectResponseDue = now + ConnectResponseRepeatMs;
}
}
if (!_serverTalked) return;
if (_missing.Count > 0)
SendNaks(now);
if ((_ackDirty && now - _lastAckMs >= AckIntervalMs && ContiguousReceived != _lastAckSent)
|| now - _lastSendMs >= KeepAliveMs)
SendAck();
}
// ── receiving ───────────────────────────────────────────────────────────
/// <summary>The next whole server message (u32 opcode first), if any.</summary>
public bool TryDequeue(out byte[] message) => _messages.TryDequeue(out message!);
/// <summary>Drains the link. Returns how many datagrams were processed.</summary>
public int Pump()
{
int n = 0;
while (_link.TryReceive(out byte[] d))
{
Receive(d);
n++;
}
return n;
}
public void Receive(byte[] d)
{
PacketsIn++;
if (!InboundPacket.TryParse(d, out InboundPacket p)) { BadPackets++; return; }
if (!VerifyChecksum(d, p)) BadChecksums++;
if (p.Connect != null)
{
OnConnectRequest(p);
return;
}
if (_connect == null) return; // nothing is meaningful before the handshake
_serverTalked = true;
if (p.Has(PacketFlags.TimeSync)) { LastServerTime = p.TimeSync; LastServerTimeAtMs = _now(); }
if (p.Has(PacketFlags.AckSequence)) Prune(p.Ack);
if (p.Naks.Length > 0) Resend(p.Naks);
foreach (uint r in p.Rejects)
if (_missing.Remove(r)) Rejected++;
if (!TrackSequence(p)) { Duplicates++; return; }
if (p.Has(PacketFlags.BlobFragments))
fixed (byte* b = d)
_reassembler.ProcessDatagram(b, d.Length, _now(), this);
}
private bool VerifyChecksum(byte[] d, InboundPacket p)
{
if (!Packet.TryPayloadHash(d, p.OptionalEnd, out uint payload)) return false;
uint header = Packet.HeaderHash(d);
if (!p.Encrypted)
return header + payload == p.Checksum;
if (_inKeys == null) return false;
uint key = (p.Checksum - header) ^ payload;
return _inKeys.TryMatch(key, p.Has(PacketFlags.Retransmission));
}
private void OnConnectRequest(InboundPacket p)
{
if (_connect != null) return; // a repeat of the same handshake
ConnectRequestData c = p.Connect!;
_connect = c;
_clientId = (ushort)c.ClientId;
_iteration = p.Iteration;
_outKeys = new Isaac(c.ClientSeed);
_inKeys = new InboundKeys(c.ServerSeed);
_seq = 1; // ConnectResponse is seq 1
LastServerTime = c.ServerTime;
LastServerTimeAtMs = _now();
_connectResponseDue = _now() + ConnectResponseDelayMs;
_reassembler.Reset();
}
/// <summary>Sequence bookkeeping. False for a duplicate that should not be processed again.</summary>
private bool TrackSequence(InboundPacket p)
{
uint s = p.Sequence;
bool carriesData = p.Encrypted || p.Has(PacketFlags.BlobFragments);
if (!carriesData)
{
// Plain control packets. Ack-only and NAK packets reuse the sequence of the server's
// last encrypted packet, so a newer one means we lost that packet. A plain
// RejectRetransmit takes a fresh sequence of its own.
if (s > _highest)
{
bool consumes = p.Has(PacketFlags.RejectRetransmit);
for (uint m = _highest + 1; m < s; m++) AddMissing(m);
if (!consumes) AddMissing(s);
_highest = s;
_ackDirty = true;
}
return true;
}
if (s > _highest)
{
for (uint m = _highest + 1; m < s; m++) AddMissing(m);
_highest = s;
_ackDirty = true;
return true;
}
if (_missing.Remove(s))
{
_ackDirty = true;
return true;
}
return false;
}
private void AddMissing(uint seq)
{
if (seq >= 2 && !_missing.ContainsKey(seq))
_missing[seq] = new NakState();
}
private void Prune(uint ack)
{
if (_sent.Count == 0) return;
foreach (uint seq in _sent.Keys.Where(k => k <= ack).ToList())
_sent.Remove(seq);
}
private void Resend(uint[] seqs)
{
foreach (uint seq in seqs)
{
NakRequestsServed++;
if (!_sent.TryGetValue(seq, out SentPacket? sp)) continue;
if (!sp.Resent)
{
uint flags = BinaryPrimitives.ReadUInt32LittleEndian(sp.Data.AsSpan(4)) | PacketFlags.Retransmission;
BinaryPrimitives.WriteUInt32LittleEndian(sp.Data.AsSpan(4), flags);
Packet.Seal(sp.Data, sp.Sealed);
sp.Resent = true;
}
Emit(sp.Data);
Resends++;
}
}
void IServerMessageSink.OnServerMessage(uint fragmentSequence, byte* message, int length)
=> _messages.Enqueue(new ReadOnlySpan<byte>(message, length).ToArray());
}
/// <summary>
/// The server's keystream, matched the way the server matches ours: the expected words
/// are kept in a set, and a key that isn't there yet is looked for up to
/// <see cref="LookAhead"/> words further on. A resend reuses its original key.
/// </summary>
internal sealed class InboundKeys
{
public const int LookAhead = 256;
public const int MaxPending = 2048;
public const int UsedMemory = 2048;
private readonly Isaac _isaac;
private readonly HashSet<uint> _pending = new();
private readonly Queue<uint> _pendingOrder = new();
private readonly HashSet<uint> _used = new();
private readonly Queue<uint> _usedOrder = new();
public InboundKeys(uint serverSeed) => _isaac = new Isaac(serverSeed);
public bool TryMatch(uint key, bool retransmission)
{
if (_pending.Remove(key)) { Use(key); return true; }
if (retransmission && _used.Contains(key)) return true;
for (int i = 0; i < LookAhead; i++)
{
uint k = _isaac.Next();
if (k == key) { Use(k); return true; }
_pending.Add(k);
_pendingOrder.Enqueue(k);
while (_pendingOrder.Count > MaxPending)
_pending.Remove(_pendingOrder.Dequeue());
}
return false;
}
private void Use(uint key)
{
if (_used.Add(key)) _usedOrder.Enqueue(key);
while (_usedOrder.Count > UsedMemory)
_used.Remove(_usedOrder.Dequeue());
}
}

View file

@ -0,0 +1,94 @@
// ============================================================================
// RynthCore.Headless - Net/UdpLink.cs
// One UDP socket per session. Everything goes to the server's port except the
// ConnectResponse, which goes to port + 1; the server answers from both, so we
// accept datagrams from either (and nothing from any other address).
// Non-blocking: the session's tick drains it; Wait() sleeps until data or a timeout.
// ============================================================================
using System.Net;
using System.Net.Sockets;
namespace RynthCore.Headless.Net;
public sealed class UdpLink : IDatagramLink, IDisposable
{
private const int SioUdpConnReset = unchecked((int)0x9800000C);
private readonly Socket _socket;
private readonly IPEndPoint _server, _connect;
private readonly byte[] _buf = new byte[2048];
private EndPoint _from = new IPEndPoint(IPAddress.Any, 0);
public UdpLink(IPAddress host, int port)
{
_server = new IPEndPoint(host, port);
_connect = new IPEndPoint(host, port + 1);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { Blocking = false };
if (OperatingSystem.IsWindows())
_socket.IOControl(SioUdpConnReset, new byte[4], null); // an ICMP "port unreachable" must not break receives
_socket.Bind(new IPEndPoint(IPAddress.Any, 0));
}
public static UdpLink Open(string host, int port)
{
IPAddress ip = IPAddress.TryParse(host, out IPAddress? a)
? a
: Dns.GetHostAddresses(host).First(x => x.AddressFamily == AddressFamily.InterNetwork);
return new UdpLink(ip, port);
}
public long Ignored { get; private set; }
/// <summary>Sees every datagram (outbound = true for ours). For captures; must not keep the span.</summary>
public Action<bool, ReadOnlySpan<byte>>? Tap { get; set; }
void IDatagramLink.Send(ReadOnlySpan<byte> datagram, bool connectPort)
{
Tap?.Invoke(true, datagram);
_socket.SendTo(datagram, SocketFlags.None, connectPort ? _connect : _server);
}
bool IDatagramLink.TryReceive(out byte[] datagram)
{
datagram = Array.Empty<byte>();
while (_socket.Available > 0)
{
int n;
try
{
n = _socket.ReceiveFrom(_buf, ref _from);
}
catch (SocketException e) when (e.SocketErrorCode is SocketError.WouldBlock or SocketError.ConnectionReset or SocketError.MessageSize)
{
continue;
}
if (_from is not IPEndPoint ep || !ep.Address.Equals(_server.Address)
|| (ep.Port != _server.Port && ep.Port != _connect.Port))
{
Ignored++;
continue;
}
datagram = _buf.AsSpan(0, n).ToArray();
Tap?.Invoke(false, datagram);
return true;
}
return false;
}
/// <summary>Sleeps until a datagram is waiting or the timeout passes.</summary>
public void Wait(int timeoutMs) => _socket.Poll(timeoutMs * 1000, SelectMode.SelectRead);
/// <summary>Sleeps until any of the links has a datagram waiting, or the timeout passes (several sessions, one thread).</summary>
public static void WaitAny(IReadOnlyList<UdpLink> links, int timeoutMs)
{
if (links.Count == 0) { Thread.Sleep(timeoutMs); return; }
if (links.Count == 1) { links[0].Wait(timeoutMs); return; }
var read = new List<Socket>(links.Count);
foreach (UdpLink l in links) read.Add(l._socket);
try { Socket.Select(read, null, null, timeoutMs * 1000); }
catch (ObjectDisposedException) { Thread.Sleep(1); }
}
public void Dispose() => _socket.Dispose();
}

View file

@ -0,0 +1,88 @@
// ============================================================================
// RynthCore.Headless - Net/WireWriter.cs
// Growable little-endian writer for client-to-server messages, with AC's string
// and packing conventions. Reading uses the SDK's NetReader.
// ============================================================================
using System.Buffers.Binary;
using System.Text;
namespace RynthCore.Headless.Net;
internal sealed class WireWriter
{
private byte[] _buf;
private int _len;
public WireWriter(int capacity = 64) => _buf = new byte[capacity];
public int Length => _len;
public ReadOnlySpan<byte> Span => _buf.AsSpan(0, _len);
public byte[] ToArray() => _buf.AsSpan(0, _len).ToArray();
private Span<byte> Grow(int n)
{
if (_len + n > _buf.Length)
Array.Resize(ref _buf, Math.Max(_buf.Length * 2, _len + n));
Span<byte> s = _buf.AsSpan(_len, n);
_len += n;
return s;
}
public WireWriter U8(byte v) { Grow(1)[0] = v; return this; }
public WireWriter U16(ushort v) { BinaryPrimitives.WriteUInt16LittleEndian(Grow(2), v); return this; }
public WireWriter U32(uint v) { BinaryPrimitives.WriteUInt32LittleEndian(Grow(4), v); return this; }
public WireWriter I32(int v) { BinaryPrimitives.WriteInt32LittleEndian(Grow(4), v); return this; }
public WireWriter U64(ulong v) { BinaryPrimitives.WriteUInt64LittleEndian(Grow(8), v); return this; }
public WireWriter F32(float v) { BinaryPrimitives.WriteSingleLittleEndian(Grow(4), v); return this; }
public WireWriter F64(double v) { BinaryPrimitives.WriteDoubleLittleEndian(Grow(8), v); return this; }
public WireWriter Bytes(ReadOnlySpan<byte> v) { v.CopyTo(Grow(v.Length)); return this; }
/// <summary>Zero bytes up to the next multiple of 4 (from the start of this writer).</summary>
public WireWriter Align4()
{
int pad = (4 - (_len & 3)) & 3;
Grow(pad).Clear();
return this;
}
/// <summary>u16 length, single-byte characters, zero padding so 2 + length is a multiple of 4.</summary>
public WireWriter String16L(string s)
{
byte[] b = Encoding.Latin1.GetBytes(s);
if (b.Length >= 0xFFFF)
throw new ArgumentException("String16L too long", nameof(s));
U16((ushort)b.Length);
Bytes(b);
Grow((4 - ((2 + b.Length) & 3)) & 3).Clear();
return this;
}
/// <summary>
/// u32 byte count, then a length prefix (one byte below 128 characters, two bytes with
/// the high bit set otherwise), then the characters, then zero padding to 4.
/// Used for the LoginRequest password.
/// </summary>
public WireWriter String32L(string s)
{
byte[] b = Encoding.Latin1.GetBytes(s);
if (b.Length > 0x7FFF)
throw new ArgumentException("String32L too long", nameof(s));
int prefix = b.Length < 0x80 ? 1 : 2;
U32((uint)(prefix + b.Length));
if (prefix == 1)
U8((byte)b.Length);
else
U8((byte)((b.Length >> 8) | 0x80)).U8((byte)b.Length);
Bytes(b);
return Align4();
}
/// <summary>AC's packed u32: one u16 below 0x8000, else (high | 0x8000) then low.</summary>
public WireWriter PackedU32(uint v)
{
if (v < 0x8000)
return U16((ushort)v);
return U16((ushort)((v >> 16) | 0x8000)).U16((ushort)v);
}
}

View file

@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
RynthCore.Headless: our own Asheron's Call client, no acclient.exe (docs\HEADLESS.md).
P0: the protocol (checksums, ISAAC, packets, acks/NAKs), the login handshake and a
session that enters the world, chats and logs out.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>RynthCore.Headless</RootNamespace>
<AssemblyName>RynthCore.Headless</AssemblyName>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="HeadlessNetTests" />
<InternalsVisibleTo Include="HeadlessSessionTests" />
<InternalsVisibleTo Include="rynth-headless" />
<InternalsVisibleTo Include="HeadlessHostTests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<ProjectReference Include="..\RynthCore.Geometry\RynthCore.Geometry.csproj" />
</ItemGroup>
<ItemGroup>
<!-- Pure engine code (no acclient memory), shared as source like the offline tests do. -->
<Compile Include="..\RynthCore.Engine\Net\AcPacketWire.cs" Link="Engine\AcPacketWire.cs" />
<Compile Include="..\RynthCore.Engine\Net\FragmentReassembler.cs" Link="Engine\FragmentReassembler.cs" />
<Compile Include="..\RynthCore.Engine\Compatibility\PropertyWire.cs" Link="Engine\PropertyWire.cs" />
<Compile Include="..\RynthCore.Engine\Compatibility\ObjectPropertyRecord.cs" Link="Engine\ObjectPropertyRecord.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,67 @@
// ============================================================================
// RynthCore.Headless - Session/ClientSession.Actions.cs
// The player's actions (use, cast, attack, inventory moves, ...). Movement is in
// ClientSession.Movement.cs.
// ============================================================================
using RynthCore.Headless.Messages;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Session;
public sealed partial class ClientSession
{
public void Use(uint obj) => SendAction(ActionType.Use, GameActions.Use(obj));
public void UseOn(uint source, uint target) => SendAction(ActionType.UseWithTarget, GameActions.UseWithTarget(source, target));
public void Identify(uint obj) => SendAction(ActionType.IdentifyObject, GameActions.Identify(obj));
public void QueryHealth(uint obj) => SendAction(ActionType.QueryHealth, GameActions.QueryHealth(obj));
public void SetCombatMode(uint mode) => SendAction(ActionType.ChangeCombatMode, GameActions.ChangeCombatMode(mode));
/// <summary>Casts on a target (the player's own id for self spells), or untargeted when target is 0.</summary>
public void Cast(uint spell, uint target)
{
if (target == 0) SendAction(ActionType.CastUntargeted, GameActions.CastUntargeted(spell));
else SendAction(ActionType.CastTargeted, GameActions.CastTargeted(target, spell));
}
public void MeleeAttack(uint target, uint height = AttackHeight.Medium, float power = 0.5f)
=> SendAction(ActionType.MeleeAttack, GameActions.MeleeAttack(target, height, power));
public void MissileAttack(uint target, uint height = AttackHeight.Medium, float accuracy = 0.5f)
=> SendAction(ActionType.MissileAttack, GameActions.MissileAttack(target, height, accuracy));
public void CancelAttack() => SendAction(ActionType.CancelAttack, ReadOnlySpan<byte>.Empty);
/// <summary>Picks an item up into the main pack (the server asks us to walk over first if needed).</summary>
public void PickUp(uint item) => MoveItem(item, PlayerId, 0);
public void MoveItem(uint item, uint container, int placement)
=> SendAction(ActionType.PutItemInContainer, GameActions.PutItemInContainer(item, container, placement));
public void Wield(uint item, uint equipMask) => SendAction(ActionType.GetAndWieldItem, GameActions.GetAndWield(item, equipMask));
public void Drop(uint item) => SendAction(ActionType.DropItem, GameActions.Drop(item));
public void Salvage(uint tool, IReadOnlyList<uint> items) => SendAction(ActionType.Salvage, GameActions.Salvage(tool, items));
public void Give(uint target, uint item, int amount = 1) => SendAction(ActionType.GiveObjectRequest, GameActions.Give(target, item, amount));
public void Merge(uint from, uint to, int amount) => SendAction(ActionType.StackableMerge, GameActions.Merge(from, to, amount));
public void Split(uint stack, uint container, int placement, int amount)
=> SendAction(ActionType.StackableSplitToContainer, GameActions.SplitToContainer(stack, container, placement, amount));
public void StopViewing(uint container) => SendAction(ActionType.NoLongerViewingContents, GameActions.NoLongerViewing(container));
public void RecallLifestone() => SendAction(ActionType.TeleToLifestone, ReadOnlySpan<byte>.Empty);
public void ConfirmationResponse(uint type, uint context, bool accept)
=> SendAction(ActionType.ConfirmationResponse, GameActions.ConfirmationResponse(type, context, accept));
/// <summary>
/// A position moved to (x, y) in <paramref name="p"/>'s landblock frame. Outdoors the cell
/// (and, past an edge, the landblock) is recomputed; indoors the cell is kept.
/// </summary>
internal static WorldPosition Relocate(WorldPosition p, float x, float y)
{
if ((p.Cell & 0xFFFF) >= 0x100)
return p with { X = x, Y = y };
int lbx = (int)(p.Cell >> 24), lby = (int)((p.Cell >> 16) & 0xFF);
while (x < 0 && lbx > 0) { x += 192; lbx--; }
while (x >= 192 && lbx < 254) { x -= 192; lbx++; }
while (y < 0 && lby > 0) { y += 192; lby--; }
while (y >= 192 && lby < 254) { y -= 192; lby++; }
x = Math.Clamp(x, 0, 191.999f);
y = Math.Clamp(y, 0, 191.999f);
uint cell = (uint)((int)(x / 24) * 8 + (int)(y / 24) + 1);
return p with { Cell = ((uint)lbx << 24) | ((uint)lby << 16) | cell, X = x, Y = y };
}
}

View file

@ -0,0 +1,303 @@
// ============================================================================
// RynthCore.Headless - Session/ClientSession.Drive.cs
// Manual driving: what a plugin does with the movement keys (the host's SetAutoRun,
// SetMotion, DoMovement / StopMovement, StopCompletely, TurnToHeading), as opposed to
// a planned walk to a point (ClientSession.Movement.cs).
//
// The drive state is the keys held: autorun, a forward/backward command, a turn and a
// sidestep. While any of them is held, every StepMs the player moves along its heading
// (forward at MoveSpeed when running, sidestep and backwards slower) through the same
// Walker as a planned walk, and turns at TurnRateDegPerSec. What the server hears is
// the same as for a walk: a MoveToState with the keys whenever they change (the first
// one is the "run forward"), an AutonomousPosition every ReportMs while moving, and a
// MoveToState "stop" plus a final position when the keys are all released.
// TurnToHeading turns at once (like the engine's direct heading write); standing
// still, the new heading goes out with the next step's position report.
//
// Living with the other movers:
// - a drive command that moves cancels our own planned walk (quietly: the drive's
// MoveToState replaces the walk's run on the server);
// - a planned walk that starts while driving ends the drive (its stop goes out
// first, then the walk's own run);
// - the server's move-to (a use or pickup out of reach) pauses the drive: nothing is
// stepped and no MoveToState is sent while it lasts (one would cancel the server's
// pending action); the keys stay held and the drive resumes when the move-to ends;
// - a teleport releases every key (nothing is sent: we are in portal space).
//
// Also here: the few raw game actions the host's chat parser and jumps need.
// ============================================================================
using RynthCore.Headless.Messages;
using RynthCore.Headless.Movement;
using RynthCore.Headless.Net;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Session;
public sealed partial class ClientSession
{
/// <summary>Turn rate while a turn key is held (AC: 90 deg/s at turn speed 1, x1.5 running).</summary>
public const float TurnRateDegPerSec = 135f;
/// <summary>Backwards runs at this fraction of the forward speed (AC's backwards factor).</summary>
public const float BackwardsFactor = 0.65f;
private bool _driveAutoRun, _driveRun = true;
private uint _driveForward, _driveTurn, _driveSide;
private RawMotion _driveSent; // the keys the server last heard from the drive (Stop = none)
private long _driveLastStepMs;
private bool _driveHeadingDirty, _driveHooked;
/// <summary>The session clock (ms), for the host's timers.</summary>
internal long NowMs => _now();
/// <summary>True while the server is moving the player to something (a use / pickup out of reach).</summary>
public bool ServerMoving => Moving && _serverMove;
/// <summary>True while autorun is on.</summary>
public bool AutoRun => _driveAutoRun;
/// <summary>The movement keys held, as a MoveToState carries them.</summary>
public RawMotion DriveMotion
{
get
{
uint fwd = _driveAutoRun ? MotionCommand.WalkForward : _driveForward;
bool run = _driveAutoRun || _driveRun;
var m = new RawMotion(fwd, run, _driveTurn, 1f, _driveSide);
return m.Moving ? m : RawMotion.Stop;
}
}
/// <summary>True while a movement key is held (whether or not a server move-to has paused it).</summary>
public bool Driving => DriveMotion.Moving;
/// <summary>Autorun on / off (the engine's SetAutoRun).</summary>
public void SetAutoRun(bool on)
{
if (_driveAutoRun == on) return;
ApplyDrive(() => _driveAutoRun = on);
}
/// <summary>
/// Holds or releases one movement key (the engine's SetMotion / DoMovement / StopMovement):
/// WalkForward / RunForward, WalkBackwards, TurnRight / TurnLeft, SideStepRight / SideStepLeft.
/// <paramref name="run"/> is the run hold key. False for any other motion.
/// </summary>
public bool SetDriveMotion(uint motion, bool on, bool run = true)
{
switch (motion)
{
case MotionCommand.WalkForward:
case MotionCommand.RunForward:
if (on) ApplyDrive(() => { _driveForward = MotionCommand.WalkForward; _driveRun = run || motion == MotionCommand.RunForward; });
else if (_driveForward == MotionCommand.WalkForward) ApplyDrive(() => _driveForward = 0);
return true;
case MotionCommand.WalkBackwards:
if (on) ApplyDrive(() => { _driveForward = MotionCommand.WalkBackwards; _driveRun = run; _driveAutoRun = false; });
else if (_driveForward == MotionCommand.WalkBackwards) ApplyDrive(() => _driveForward = 0);
return true;
case MotionCommand.TurnRight:
case MotionCommand.TurnLeft:
if (on) ApplyDrive(() => _driveTurn = motion);
else if (_driveTurn == motion) ApplyDrive(() => _driveTurn = 0);
return true;
case MotionCommand.SideStepRight:
case MotionCommand.SideStepLeft:
if (on) ApplyDrive(() => _driveSide = motion);
else if (_driveSide == motion) ApplyDrive(() => _driveSide = 0);
return true;
case MotionCommand.Ready:
if (on) ApplyDrive(() => { _driveForward = 0; _driveAutoRun = false; });
return true;
default:
return false;
}
}
/// <summary>
/// Releases every key and stops (the engine's StopCompletely): the drive's stop goes out,
/// and our own planned walk ends too. The server's move-to is left alone.
/// </summary>
public void StopCompletely()
{
if (Moving && !_serverMove) StopMoving();
ApplyDrive(() => { _driveAutoRun = false; _driveForward = 0; _driveTurn = 0; _driveSide = 0; });
}
/// <summary>
/// Faces a compass heading (degrees, 0 = north, clockwise) at once. While driving it rides
/// the next position report; standing still it goes out with the next step (at most StepMs).
/// </summary>
public void FaceHeading(float headingDegrees)
{
if (State != SessionState.InWorld || World.PlayerObject is not { } me || me.Position is not { } p) return;
if (!float.IsFinite(headingDegrees)) return;
me.Position = WithHeading(p, headingDegrees * MathF.PI / 180f);
_driveHeadingDirty = true;
}
/// <summary>The player's compass heading in degrees (0 = north, clockwise), from its rotation.</summary>
public static float HeadingDegrees(WorldPosition p)
{
float deg = -2f * MathF.Atan2(p.Qz, p.Qw) * 180f / MathF.PI;
deg %= 360f;
return deg < 0 ? deg + 360f : deg;
}
// ── internals ───────────────────────────────────────────────────────────
private void ApplyDrive(Action change)
{
HookDrive();
long now = _now();
// Catch the position up to now under the old keys, then change them.
if (CanDrive) AdvanceDrive(now);
change();
if (State != SessionState.InWorld) return;
RawMotion m = DriveMotion;
if (m.Moving && Moving && !_serverMove)
{
// A drive key cancels our planned walk; the drive's MoveToState replaces its run.
_announced = false;
EndMove(false, "manual drive");
}
if (Moving && _serverMove) return; // paused: TickDrive sends it once the server's move-to ends
SendDrive(m, now);
}
/// <summary>The same keys held (no keys at all is one state, whatever the hold key or turn speed).</summary>
private static bool SameKeys(RawMotion a, RawMotion b)
=> a.Moving == b.Moving && (!a.Moving || (a.ForwardCommand == b.ForwardCommand && a.TurnCommand == b.TurnCommand
&& a.SidestepCommand == b.SidestepCommand && a.Run == b.Run));
private bool CanDrive => State == SessionState.InWorld && !Moving && _driveSent.Moving;
private void SendDrive(RawMotion m, long now)
{
if (SameKeys(m, _driveSent)) return;
WorldObject? me = World.PlayerObject;
if (me?.Position is not { } p) return;
bool starting = !_driveSent.Moving;
_driveSent = m;
SendMotion(m);
if (starting) _driveLastStepMs = now;
if (!m.Moving || starting) SendPosition(p);
_driveHeadingDirty = false;
}
private void HookDrive()
{
if (_driveHooked) return;
_driveHooked = true;
World.PlayerTeleported += ReleaseDriveQuietly;
StateChanged += s => { if (s != SessionState.InWorld) ReleaseDriveQuietly(); };
}
/// <summary>Every key released, nothing sent (portal space, or a walk that took over and says so itself).</summary>
private void ReleaseDriveQuietly()
{
_driveAutoRun = false;
_driveForward = _driveTurn = _driveSide = 0;
_driveSent = RawMotion.Stop;
_driveHeadingDirty = false;
}
private void TickDrive()
{
if (State != SessionState.InWorld) return;
long now = _now();
if (Moving)
{
if (!_serverMove && (_driveSent.Moving || Driving))
{
// Our planned walk took over: the drive stops (its stop first, then the walk's run).
if (_driveSent.Moving) SendMotion(RawMotion.Stop);
ReleaseDriveQuietly();
}
else if (_serverMove)
{
// Paused: the server's move-to replaces our motion on its side, so the keys
// still held go out afresh (with a position) once it ends.
_driveSent = RawMotion.Stop;
}
_driveLastStepMs = now;
return;
}
RawMotion m = DriveMotion;
if (!SameKeys(m, _driveSent)) SendDrive(m, now); // resuming after a server move-to
if (!m.Moving)
{
if (_driveHeadingDirty && now - _lastReportMs >= StepMs && World.PlayerObject?.Position is { } p)
{
SendPosition(p);
_driveHeadingDirty = false;
}
return;
}
if (now - _driveLastStepMs < StepMs) return;
AdvanceDrive(now);
if (now - _lastReportMs >= ReportMs && World.PlayerObject?.Position is { } q)
{
SendPosition(q);
_driveHeadingDirty = false;
}
}
/// <summary>Moves the player under the keys the server last heard, from the last step to now.</summary>
private void AdvanceDrive(long now)
{
RawMotion m = _driveSent;
long elapsed = now - _driveLastStepMs;
if (elapsed <= 0) return;
_driveLastStepMs = now;
if (!m.Moving || World.PlayerObject is not { } me || me.Position is not { } from) return;
float dt = Math.Min(elapsed, 3 * StepMs) / 1000f;
float heading = HeadingDegrees(from) * MathF.PI / 180f;
float turn = TurnRateDegPerSec * MathF.PI / 180f * dt;
if (m.TurnCommand == MotionCommand.TurnRight) heading += turn;
else if (m.TurnCommand == MotionCommand.TurnLeft) heading -= turn;
float speed = m.Run ? MoveSpeed : MotionCommand.WalkSpeed;
float forward = m.ForwardCommand switch
{
MotionCommand.WalkForward or MotionCommand.RunForward => speed,
MotionCommand.WalkBackwards => -speed * BackwardsFactor,
_ => 0f,
};
float side = m.SidestepCommand switch
{
MotionCommand.SideStepRight => MotionCommand.SidestepSpeed * (m.Run ? 1.5f : 1f),
MotionCommand.SideStepLeft => -MotionCommand.SidestepSpeed * (m.Run ? 1.5f : 1f),
_ => 0f,
};
float sin = MathF.Sin(heading), cos = MathF.Cos(heading);
float dx = (sin * forward + cos * side) * dt;
float dy = (cos * forward - sin * side) * dt;
WorldPosition turned = WithHeading(from, heading);
me.Position = dx != 0 || dy != 0 ? Walker.Step(turned, dx, dy).Position : turned;
}
// ── raw actions for the host (chat parser, jumps) ─────────────────────
/// <summary>/tell: game action 0x005D (message, then the target's name).</summary>
public void Tell(string target, string message)
=> SendAction(0x005D, new WireWriter(16 + message.Length + target.Length).String16L(message).String16L(target).ToArray());
/// <summary>/emote: game action 0x01DF.</summary>
public void Emote(string text) => SendAction(0x01DF, new WireWriter(8 + text.Length).String16L(text).ToArray());
/// <summary>/me (soul emote): game action 0x01E1.</summary>
public void SoulEmote(string text) => SendAction(0x01E1, new WireWriter(8 + text.Length).String16L(text).ToArray());
/// <summary>A jump (game action 0xF61B): extent 0..1 and the launch velocity (world frame, m/s).</summary>
public void Jump(float extent, float vx, float vy, float vz)
{
WorldObject? me = World.PlayerObject;
if (me == null) return;
SendAction(ActionType.Jump, MotionMessages.Jump(Math.Clamp(extent, 0f, 1f), vx, vy, vz,
me.InstanceSeq, me.ServerControlSeq, me.TeleportSeq, me.ForcePositionSeq));
}
}

View file

@ -0,0 +1,263 @@
// ============================================================================
// RynthCore.Headless - Session/ClientSession.Movement.cs
// Walking: to a point, to an object, or along a list of waypoints; turning.
//
// What ACE needs (non-PK players): the position the client reports is taken as given,
// cell id included (only >50 m jumps across landblocks, dungeon-to-dungeon moves and
// rising >10 m without a jump are refused), so the walk geometry decides ground height,
// walls and the cell. Two ways of moving:
//
// - our own walk (WalkTo / WalkPath / Approach): a MoveToState "run forward" at the
// start (the server animates us for everyone and echoes our run rate), an
// AutonomousPosition every ReportMs while moving, and a MoveToState "stop" plus a
// final position at the end;
// - the server's move-to (it wants us next to something before a use/pickup/give
// completes): AutonomousPosition only, every ServerMoveReportMs, because a
// MoveToState would cancel the server's pending action.
//
// Speed is 4 m/s x the run rate the server echoed (1.0 until it has), stepped every
// StepMs. Turning is instant (the new heading goes out with the next report).
// ============================================================================
using RynthCore.Headless.Messages;
using RynthCore.Headless.Movement;
using RynthCore.Headless.World;
namespace RynthCore.Headless.Session;
public sealed partial class ClientSession
{
public const long StepMs = 100;
public const long ReportMs = 500;
public const long ServerMoveReportMs = 200;
private readonly Queue<WorldPosition> _waypoints = new();
private readonly Queue<WorldPosition> _detour = new();
private int _plans;
public const int MaxPlans = 3;
private uint _moveTarget;
private float _moveStop;
private long _moveDeadline, _lastStepMs, _lastReportMs, _lastProgressMs;
private bool _serverMove, _announced;
private float _bestDistance;
/// <summary>How steps meet the world. FlatWalk until a geometry-backed walker is set.</summary>
public IWalkGeometry Walker { get; set; } = new FlatWalk();
/// <summary>True while the player is walking.</summary>
public bool Moving => _moveTarget != 0 || _waypoints.Count > 0;
/// <summary>A walk ended: arrived, or why not.</summary>
public event Action<bool, string>? MoveFinished;
/// <summary>Ground speed in m/s.</summary>
public float MoveSpeed => MotionCommand.RunSpeed * (World.PlayerRunRate ?? 1f);
/// <summary>Walks to within <paramref name="stop"/> metres of an object.</summary>
public void Approach(uint target, float stop = 0.5f, long timeoutMs = 30_000)
=> BeginMove(target, Array.Empty<WorldPosition>(), stop, timeoutMs, serverMove: false);
/// <summary>Walks to a point.</summary>
public void WalkTo(WorldPosition point, float stop = 0.2f, long timeoutMs = 60_000)
=> BeginMove(0, new[] { point }, stop, timeoutMs, serverMove: false);
/// <summary>Walks through each waypoint in turn (a route from a navigator).</summary>
public void WalkPath(IEnumerable<WorldPosition> waypoints, float stop = 0.3f, long timeoutMs = 300_000)
=> BeginMove(0, waypoints, stop, timeoutMs, serverMove: false);
/// <summary>Stops walking (and tells the server, if this was our own walk).</summary>
public void StopMoving() => EndMove(false, "stopped");
/// <summary>Faces a heading (degrees, 0 = north, clockwise) and reports it.</summary>
public void TurnTo(float headingDegrees)
{
if (World.PlayerObject?.Position is not { } p) return;
SendPosition(WithHeading(p, headingDegrees * MathF.PI / 180f));
}
/// <summary>Faces an object.</summary>
public void TurnToward(uint obj)
{
if (World.PlayerObject?.Position is not { } p || World.Get(obj)?.Position is not { } t) return;
(float dx, float dy) = Delta(p, t);
SendPosition(WithHeading(p, MathF.Atan2(dx, dy)));
}
/// <summary>Reports the player's position (AutonomousPosition).</summary>
public void SendPosition(WorldPosition p)
{
WorldObject? me = World.PlayerObject;
if (me == null) return;
me.Position = p;
SendAction(ActionType.AutonomousPosition,
GameActions.AutonomousPosition(p, me.InstanceSeq, me.ServerControlSeq, me.TeleportSeq, me.ForcePositionSeq, onGround: true));
_lastReportMs = _now();
}
private void SendMotion(RawMotion m)
{
WorldObject? me = World.PlayerObject;
if (me?.Position is not { } p) return;
SendAction(ActionType.MoveToState,
MotionMessages.MoveToState(m, p, me.InstanceSeq, me.ServerControlSeq, me.TeleportSeq, me.ForcePositionSeq, onGround: true));
}
private void BeginMove(uint target, IEnumerable<WorldPosition> points, float stop, long timeoutMs, bool serverMove)
{
if (Moving) EndMove(false, "replaced");
_moveTarget = target;
_waypoints.Clear();
_detour.Clear();
_plans = 0;
foreach (WorldPosition p in points) _waypoints.Enqueue(p);
_moveStop = stop;
_serverMove = serverMove;
_announced = false;
long now = _now();
_moveDeadline = now + timeoutMs;
_lastStepMs = now;
_lastProgressMs = now;
_bestDistance = float.MaxValue;
}
private void EndMove(bool arrived, string why)
{
if (!Moving) return;
bool tell = _announced && !_serverMove;
_moveTarget = 0;
_waypoints.Clear();
_detour.Clear();
if (tell)
{
SendMotion(RawMotion.Stop);
if (World.PlayerObject?.Position is { } p) SendPosition(p);
}
MoveFinished?.Invoke(arrived, why);
}
private void OnServerMoveTo(MotionUpdate m)
{
float stop = Math.Max(0.3f, m.DistanceToObject * 0.8f);
if (m.MovementType == 6 && m.TargetId != 0 && World.Get(m.TargetId)?.Position != null)
{
Info($"server asks to move to 0x{m.TargetId:X8} (within {m.DistanceToObject:F1} m)");
BeginMove(m.TargetId, Array.Empty<WorldPosition>(), stop, 15_000, serverMove: true);
}
else if (m.Origin is { } o)
{
Info($"server asks to move to a point in 0x{o.Cell:X8}");
BeginMove(0, new[] { o }, stop, 15_000, serverMove: true);
}
}
private void TickMovement()
{
if (!Moving || State != SessionState.InWorld) return;
long now = _now();
if (now - _lastStepMs < StepMs) return;
WorldObject? me = World.PlayerObject;
if (me?.Position is not { } from) { EndMove(false, "no position"); return; }
if (now > _moveDeadline) { EndMove(false, "timed out"); return; }
WorldPosition? goal = _moveTarget != 0 ? World.Get(_moveTarget)?.Position : _waypoints.Count > 0 ? _waypoints.Peek() : null;
if (goal is not { } to) { EndMove(false, "target gone"); return; }
bool lastLeg = _moveTarget != 0 || _waypoints.Count <= 1;
float stopAt = lastLeg ? _moveStop : 0.3f;
if (!SameFrame(from, to)) { EndMove(false, "target is in another dungeon / indoor landblock"); return; }
WorldPosition finalGoal = to;
float finalStop = stopAt;
if (_detour.Count > 0)
{
// Around an obstacle first: the detour's points, then on to the goal.
if (Distance2D(from, _detour.Peek()) <= 0.3f) { _detour.Dequeue(); return; }
to = _detour.Peek();
stopAt = 0.05f;
}
(float dx, float dy) = Delta(from, to);
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist <= stopAt + 0.05f)
{
if (_detour.Count > 0) { _detour.Dequeue(); return; }
if (!lastLeg) { _waypoints.Dequeue(); return; }
EndMove(true, "arrived");
return;
}
if (!_announced && !_serverMove)
{
SendMotion(RawMotion.RunForward);
_announced = true;
}
float dt = Math.Min(now - _lastStepMs, 3 * StepMs) / 1000f;
_lastStepMs = now;
float move = Math.Min(MoveSpeed * dt, dist - stopAt);
float heading = MathF.Atan2(dx, dy);
WalkResult r = Walker.Step(WithHeading(from, heading), dx / dist * move, dy / dist * move);
me.Position = r.Position;
float left = Distance2D(r.Position, finalGoal);
if (left < _bestDistance - 0.05f) { _bestDistance = left; _lastProgressMs = now; }
IReadOnlyList<WorldPosition>? detour = null;
if (r.Blocked && _plans < MaxPlans)
{
_plans++;
var sw = System.Diagnostics.Stopwatch.StartNew();
// The server's move-to only needs us within its use range: get as close as the walls allow.
detour = Walker.Plan(r.Position, finalGoal, finalStop, nearest: _serverMove);
Info($"blocked ({r.Why}) at 0x{r.Position.Cell:X8} ({r.Position.X:F1},{r.Position.Y:F1}); planned a detour to 0x{finalGoal.Cell:X8} ({finalGoal.X:F1},{finalGoal.Y:F1}): " +
$"{(detour == null ? "none" : detour.Count + " points")} in {sw.ElapsedMilliseconds} ms");
}
if (detour is { Count: 0 })
{
// The planner says we're already as close as the walls allow.
SendPosition(r.Position);
EndMove(true, "as close as it gets");
return;
}
if (detour is { Count: > 0 })
{
// Blocked: walk around (a short planned detour), then carry on.
_detour.Clear();
foreach (WorldPosition d in detour) _detour.Enqueue(d);
_lastProgressMs = now;
}
else if (r.Blocked && now - _lastProgressMs > 1500)
{
SendPosition(r.Position);
EndMove(false, $"blocked{(r.Why != null ? ": " + r.Why : "")}");
return;
}
long every = _serverMove ? ServerMoveReportMs : ReportMs;
if (now - _lastReportMs >= every || Distance2D(r.Position, to) <= stopAt + 0.05f) SendPosition(r.Position);
}
// ── frames ──────────────────────────────────────────────────────────────
/// <summary>Two positions can be walked between: outdoors anywhere, indoors within one landblock.</summary>
private static bool SameFrame(WorldPosition a, WorldPosition b)
=> a.Cell >> 16 == b.Cell >> 16 || ((a.Cell & 0xFFFF) < 0x100 && (b.Cell & 0xFFFF) < 0x100);
/// <summary>(dx, dy) from a to b in metres (landblocks are 192 m apart).</summary>
internal static (float, float) Delta(WorldPosition a, WorldPosition b)
{
float dx = b.X - a.X + ((int)(b.Cell >> 24) - (int)(a.Cell >> 24)) * 192f;
float dy = b.Y - a.Y + ((int)((b.Cell >> 16) & 0xFF) - (int)((a.Cell >> 16) & 0xFF)) * 192f;
return (dx, dy);
}
private static float Distance2D(WorldPosition a, WorldPosition b)
{
(float dx, float dy) = Delta(a, b);
return MathF.Sqrt(dx * dx + dy * dy);
}
/// <summary>Rotation about Z for a heading in radians (0 = north/+Y, clockwise). AC's forward is +Y.</summary>
internal static WorldPosition WithHeading(WorldPosition p, float heading)
{
float yaw = -heading;
return p with { Qw = MathF.Cos(yaw / 2), Qx = 0, Qy = 0, Qz = MathF.Sin(yaw / 2) };
}
}

View file

@ -0,0 +1,369 @@
// ============================================================================
// RynthCore.Headless - Session/ClientSession.cs
// One account's connection, from LoginRequest to Disconnect:
//
// Connecting LoginRequest sent, waiting for the ConnectRequest
// CharacterSelect handshake done; CharacterList / ServerName / DDD arrive
// EnteringWorld 0xF7C8 sent -> 0xF7DF ServerReady -> 0xF657 sent
// InWorld PlayerCreate seen; LoginComplete sent once our object exists
// LoggingOut 0xF653 sent, waiting for the server's 0xF653 + a fresh CharacterList
// Closed / Failed Disconnect sent (or the server went away)
//
// Single-threaded: the owner calls Tick() in a loop. Events fire from inside Tick.
// The password is used for the LoginRequest only and is never logged or stored here.
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Headless.Messages;
using RynthCore.Headless.Net;
using RynthCore.Headless.World;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.Session;
public enum SessionState { Idle, Connecting, CharacterSelect, EnteringWorld, InWorld, LoggingOut, Closed, Failed }
public sealed class SessionOptions
{
public required string Account { get; init; }
/// <summary>Selects by name (case-insensitive); null = stay at character select.</summary>
public string? Character { get; init; }
/// <summary>With no <see cref="Character"/>: enter the world as the first character listed.</summary>
public bool PickFirstCharacter { get; init; }
public long ConnectTimeoutMs { get; init; } = 10_000;
public long EnterWorldTimeoutMs { get; init; } = 30_000;
public long LogoutTimeoutMs { get; init; } = 20_000;
public long SilenceTimeoutMs { get; init; } = 45_000;
}
public sealed partial class ClientSession
{
private readonly SessionOptions _opt;
private readonly Transport _net;
private readonly Func<long> _now;
private long _stateSince;
private long _lastHeardMs;
private long _lastPackets;
private uint _actionSeq;
private bool _loginCompleteSent;
private bool _logoffConfirmed;
private string _serverAccount = "";
public SessionState State { get; private set; } = SessionState.Idle;
public string? FailReason { get; private set; }
public IReadOnlyList<(uint Id, string Name)> Characters { get; private set; } = Array.Empty<(uint, string)>();
public uint CharacterId { get; private set; }
public uint PlayerId { get; private set; }
public string WorldName { get; private set; } = "";
public int ObjectsSeen { get; private set; }
public double ServerTime => _net.LastServerTime;
/// <summary>The server's clock now: the last time sync plus the local time since it arrived (0 before the first).</summary>
public double ServerTimeNow => _net.LastServerTime <= 0 ? 0 : _net.LastServerTime + (_now() - _net.LastServerTimeAtMs) / 1000.0;
public WorldState World { get; }
public event Action<string>? Log;
public event Action<ChatLine>? Chat;
public event Action<ObjectSeen>? ObjectCreated;
public event Action<uint>? ObjectDeleted;
public event Action<SessionState>? StateChanged;
/// <summary>Every whole server message (opcode first), before the session handles it.</summary>
public event Action<uint, ReadOnlyMemory<byte>>? RawMessage;
internal Transport Transport => _net;
internal ClientSession(IDatagramLink link, SessionOptions options, Func<long> nowMs)
{
_opt = options;
_now = nowMs;
_net = new Transport(link, nowMs);
World = new WorldState(nowMs);
World.PlayerMoveTo += OnServerMoveTo;
World.PlayerCorrected += _ => { if (Moving) EndMove(false, "the server moved us"); };
}
public static ClientSession Connect(UdpLink link, SessionOptions options)
{
long t0 = Environment.TickCount64;
return new ClientSession(link, options, () => Environment.TickCount64 - t0);
}
public void Start(string password)
{
if (State != SessionState.Idle) throw new InvalidOperationException("already started");
_net.SendLoginRequest(LoginMessages.LoginRequest(_opt.Account, password, (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds()));
_lastHeardMs = _now();
SetState(SessionState.Connecting);
}
/// <summary>Local chat (or an @command).</summary>
public void Say(string text)
{
if (State != SessionState.InWorld) throw new InvalidOperationException("not in world");
SendAction(GameActionType.Talk, LoginMessages.TalkPayload(text));
}
/// <summary>Starts a clean logout; Tick sends the Disconnect once the server confirms.</summary>
public void Logout()
{
if (State == SessionState.InWorld || State == SessionState.EnteringWorld)
{
_net.SendMessage(LoginMessages.LogOff(), MessageQueue.Login);
SetState(SessionState.LoggingOut);
}
else if (State is SessionState.CharacterSelect or SessionState.Connecting)
{
Close("logout at character select");
}
}
/// <summary>Ends the session right away.</summary>
public void Close(string why)
{
if (State is SessionState.Closed or SessionState.Failed) return;
_net.SendDisconnect();
Info($"closed: {why}");
SetState(SessionState.Closed);
}
public bool Finished => State is SessionState.Closed or SessionState.Failed;
public void Tick()
{
if (Finished) return;
_net.Pump();
if (_net.PacketsIn != _lastPackets)
{
_lastPackets = _net.PacketsIn;
_lastHeardMs = _now();
}
while (_net.TryDequeue(out byte[] m))
Handle(m);
if (Finished) return;
TickDrive(); // before TickMovement: a walk that just started takes over from the drive first
TickMovement();
_net.Tick();
CheckTimers();
}
// ── timers ──────────────────────────────────────────────────────────────
private void CheckTimers()
{
long now = _now();
long inState = now - _stateSince;
switch (State)
{
case SessionState.Connecting when inState > _opt.ConnectTimeoutMs:
Fail("no answer from the server (ConnectRequest/CharacterList)");
return;
case SessionState.EnteringWorld when inState > _opt.EnterWorldTimeoutMs:
Fail("timed out entering the world");
return;
case SessionState.LoggingOut when inState > _opt.LogoutTimeoutMs:
Close("logout not confirmed in time");
return;
}
if (State != SessionState.Connecting && now - _lastHeardMs > _opt.SilenceTimeoutMs)
Fail($"server silent for {(now - _lastHeardMs) / 1000}s");
}
// ── messages ────────────────────────────────────────────────────────────
private void Handle(byte[] m)
{
if (!ServerMessage.TryFromWire(m, out ServerMessage msg)) return;
RawMessage?.Invoke(msg.Opcode, m);
World.Apply(msg);
ReadOnlySpan<byte> b = msg.Body;
switch (msg.Opcode)
{
case Opcode.CharacterList:
if (!LoginMessages.TryParseCharacterList(b, out CharacterListData list)) { Info("CharacterList: unparsed"); break; }
_serverAccount = list.Account;
Characters = list.Characters.Select(c => (c.Id, c.Name)).ToList();
if (State == SessionState.LoggingOut)
{
if (_logoffConfirmed) Close("logged out");
break;
}
Info($"characters: {string.Join(", ", Characters.Select(c => c.Name))}");
if (State == SessionState.Connecting) SetState(SessionState.CharacterSelect);
PickCharacter();
break;
case Opcode.ServerName:
if (LoginMessages.TryParseServerName(b, out int online, out int max, out string world))
{
WorldName = world;
Info($"server: {world} ({online}/{max} online)");
}
break;
case Opcode.DddInterrogation:
_net.SendMessage(LoginMessages.DddInterrogationResponse(), MessageQueue.Database);
break;
case Opcode.DddEnd:
break;
case Opcode.EnterWorldServerReady:
if (State == SessionState.EnteringWorld)
_net.SendMessage(LoginMessages.EnterWorld(CharacterId, _serverAccount), MessageQueue.Login);
break;
case Opcode.CharacterError:
Fail($"character error 0x{U32(b):X}");
break;
case Opcode.AccountBoot:
Fail("booted by the server");
break;
case Opcode.PlayerCreate:
// Our own CreateObject travels in another queue and may come first.
PlayerId = U32(b);
SetState(SessionState.InWorld);
if (World.Get(PlayerId) != null && !_loginCompleteSent)
SendLoginComplete();
break;
case Opcode.ObjectCreate:
ObjectsSeen++;
if (ObjectCreate.TryParse(b, out ObjectCreateData o))
{
ObjectCreated?.Invoke(new ObjectSeen(o.Id, o.Name, o.WeenieClassId, o.ItemType, o.Position?.Cell ?? 0));
if (o.Id == PlayerId && PlayerId != 0 && !_loginCompleteSent)
SendLoginComplete();
}
else
{
Info($"ObjectCreate 0x{U32(b):X8}: unparsed ({b.Length} bytes)");
}
break;
case Opcode.ObjectDelete:
ObjectDeleted?.Invoke(U32(b));
break;
case Opcode.PlayerTeleport:
if (State == SessionState.InWorld) SendLoginComplete();
break;
case Opcode.CharacterLogOff:
if (State == SessionState.LoggingOut) _logoffConfirmed = true;
break;
case Opcode.HearSpeech:
if (HearSpeech.TryParse(b, out HearSpeech hs))
Chat?.Invoke(new ChatLine(hs.ChatType, hs.SenderName, hs.SenderId, hs.Text));
break;
case Opcode.HearRangedSpeech:
if (HearRangedSpeech.TryParse(b, out HearRangedSpeech hr))
Chat?.Invoke(new ChatLine(hr.ChatType, hr.SenderName, hr.SenderId, hr.Text));
break;
case Opcode.HearEmote:
case Opcode.HearSoulEmote:
if (HearEmote.TryParse(b, msg.Opcode == Opcode.HearSoulEmote, out HearEmote he))
Chat?.Invoke(new ChatLine(0x0C, he.SenderName, he.SenderId, he.Text));
break;
case Opcode.ServerMessage:
if (LoginMessages.TryParseServerMessage(b, out string text, out uint type))
Chat?.Invoke(new ChatLine(type, "", 0, text));
break;
case Opcode.GameEvent:
HandleEvent(msg);
break;
}
}
private void HandleEvent(ServerMessage msg)
{
ReadOnlySpan<byte> e = msg.EventBody;
switch (msg.EventType)
{
case GameEventType.HearDirectSpeech:
if (HearDirectSpeech.TryParse(e, out HearDirectSpeech t))
Chat?.Invoke(new ChatLine(t.ChatType, t.SenderName, t.SenderId, t.Text));
break;
case GameEventType.ChannelBroadcast:
if (ChannelBroadcast.TryParse(e, out ChannelBroadcast c))
Chat?.Invoke(new ChatLine(0x08, c.SenderName, 0, c.Text));
break;
}
}
private void PickCharacter()
{
if (State != SessionState.CharacterSelect) return;
(uint Id, string Name) pick;
if (_opt.Character != null)
pick = Characters.FirstOrDefault(c => string.Equals(c.Name.TrimStart('+'), _opt.Character.TrimStart('+'), StringComparison.OrdinalIgnoreCase));
else if (_opt.PickFirstCharacter)
pick = Characters.FirstOrDefault();
else
return;
if (pick.Id == 0)
{
Fail(_opt.Character != null ? $"no character named '{_opt.Character}' on this account" : "no characters on this account");
return;
}
CharacterId = pick.Id;
Info($"entering world as {pick.Name} (0x{pick.Id:X8})");
_net.SendMessage(LoginMessages.EnterWorldRequest(), MessageQueue.Login);
SetState(SessionState.EnteringWorld);
}
private void SendLoginComplete()
{
// Sent with action sequence 0, like the retail client; it clears the "portal space" state.
_net.SendMessage(LoginMessages.GameAction(0, GameActionType.LoginComplete), MessageQueue.UI);
_loginCompleteSent = true;
Info("login complete sent");
}
private void SendAction(uint type, ReadOnlySpan<byte> payload)
{
_net.SendMessage(LoginMessages.GameAction(++_actionSeq, type, payload), MessageQueue.UI);
ActionSent?.Invoke(type, payload.Length >= 4 ? BinaryPrimitives.ReadUInt32LittleEndian(payload) : 0);
}
/// <summary>A game action went out (type, its first u32 argument or 0). For tracing.</summary>
public event Action<uint, uint>? ActionSent;
// ── helpers ─────────────────────────────────────────────────────────────
private static uint U32(ReadOnlySpan<byte> b) => b.Length >= 4 ? BinaryPrimitives.ReadUInt32LittleEndian(b) : 0;
private void SetState(SessionState s)
{
if (State == s) return;
State = s;
_stateSince = _now();
StateChanged?.Invoke(s);
}
private void Fail(string why)
{
if (Finished) return;
FailReason = why;
_net.SendDisconnect();
Info($"failed: {why}");
SetState(SessionState.Failed);
}
private void Info(string s) => Log?.Invoke(s);
public string Stats =>
$"in {_net.PacketsIn} out {_net.PacketsOut} resends {_net.Resends} naks {_net.NaksSent} " +
$"badsum {_net.BadChecksums} bad {_net.BadPackets} dup {_net.Duplicates} rejected {_net.Rejected} missing {_net.Missing.Count}";
}
public readonly record struct ChatLine(uint ChatType, string Sender, uint SenderId, string Text);
public readonly record struct ObjectSeen(uint Id, string Name, uint WeenieClassId, uint ItemType, uint Cell);

View file

@ -0,0 +1,74 @@
// ============================================================================
// RynthCore.Headless - World/PlayerState.cs
// The player's own state: properties, attributes, vitals, skills, spellbook,
// enchantments, the main pack order and what is equipped. Seeded by PlayerDescription,
// then kept current by the private updates and magic/inventory events.
//
// Vital maxima here are the BASE values (attribute contribution + init + ranks);
// enchantment-adjusted ("buffed") values come with the plugin host (P3).
// ============================================================================
using RynthCore.Headless.Messages;
namespace RynthCore.Headless.World;
public enum Vital : uint { Health = 1, Stamina = 2, Mana = 3 }
public sealed class PlayerState
{
public uint Id { get; internal set; }
public bool DescriptionReceived { get; internal set; }
internal readonly Dictionary<uint, AttributeInfo> Attributes = new();
internal readonly Dictionary<uint, VitalInfo> Vitals = new();
internal readonly Dictionary<uint, SkillInfo> Skills = new();
internal readonly HashSet<uint> Spells = new();
internal readonly List<Enchantment> Enchantments = new();
internal readonly List<uint> MainPack = new(); // ordinary items, server order
internal readonly List<uint> SidePacks = new(); // containers and foci, server order
internal readonly Dictionary<uint, uint> Equipped = new(); // item -> EquipMask
internal PlayerDescriptionData? Description;
public IReadOnlyDictionary<uint, AttributeInfo> AttributeTable => Attributes;
public IReadOnlyDictionary<uint, SkillInfo> SkillTable => Skills;
public IReadOnlyCollection<uint> SpellBook => Spells;
public IReadOnlyList<Enchantment> ActiveEnchantments => Enchantments;
public IReadOnlyList<uint> MainPackOrder => MainPack;
public IReadOnlyList<uint> SidePackOrder => SidePacks;
public IReadOnlyDictionary<uint, uint> EquippedItems => Equipped;
/// <summary>Strength 1 .. Self 6, base (init + ranks).</summary>
public uint BaseAttribute(uint attr) => Attributes.TryGetValue(attr, out AttributeInfo a) ? a.Base : 0;
public uint CurrentVital(Vital v) => Vitals.TryGetValue((uint)v, out VitalInfo i) ? i.Current : 0;
/// <summary>Base maximum: Endurance/2 (health), Endurance (stamina) or Self (mana), plus init + ranks.</summary>
public uint BaseMaxVital(Vital v)
{
if (!Vitals.TryGetValue((uint)v, out VitalInfo i)) return 0;
uint attr = v switch
{
Vital.Health => (BaseAttribute(2) + 1) / 2,
Vital.Stamina => BaseAttribute(2),
_ => BaseAttribute(6),
};
return attr + i.Init + i.Ranks;
}
public bool TryGetSkill(uint id, out SkillInfo s) => Skills.TryGetValue(id, out s);
internal void SetEnchantment(Enchantment e)
{
RemoveEnchantment(e.SpellId, e.Layer);
Enchantments.Add(e);
}
internal bool RemoveEnchantment(ushort spell, ushort layer)
=> Enchantments.RemoveAll(x => x.SpellId == spell && x.Layer == layer) > 0;
internal void RemoveFromPack(uint id)
{
MainPack.Remove(id);
SidePacks.Remove(id);
}
}

View file

@ -0,0 +1,97 @@
// ============================================================================
// RynthCore.Headless - World/WorldObject.cs
// One object the client knows about: what CreateObject/UpdateObject said, the
// properties public updates and identify replies added, and where it is.
// ============================================================================
using RynthCore.Headless.Messages;
namespace RynthCore.Headless.World;
public sealed class WorldObject
{
public WorldObject(uint id) => Id = id;
public uint Id { get; }
public ObjectCreateData Desc { get; internal set; } = new();
public string Name => Desc.Name;
public uint WeenieClassId => Desc.WeenieClassId;
public uint ItemType => Desc.ItemType;
public uint Icon => Desc.Icon;
/// <summary>The containing object (pack, corpse, chest); 0 = on the ground / not contained.</summary>
public uint ContainerId { get; internal set; }
/// <summary>The creature wielding it; 0 = not wielded.</summary>
public uint WielderId { get; internal set; }
public uint WieldedLocation { get; internal set; }
public uint StackSize { get; internal set; } = 1;
public int Value { get; internal set; }
public WorldPosition? Position { get; internal set; }
public float Vx { get; internal set; }
public float Vy { get; internal set; }
public float Vz { get; internal set; }
public uint PhysicsState { get; internal set; }
public ushort Stance { get; internal set; }
/// <summary>Last health fraction from UpdateHealth (creatures), or null if never queried.</summary>
public float? HealthRatio { get; internal set; }
// Sequences, kept for the player's own movement packets.
public ushort InstanceSeq { get; internal set; }
public ushort PositionSeq { get; internal set; }
public ushort TeleportSeq { get; internal set; }
public ushort ServerControlSeq { get; internal set; }
public ushort ForcePositionSeq { get; internal set; }
internal readonly Dictionary<uint, int> Ints = new();
internal readonly Dictionary<uint, long> Int64s = new();
internal readonly Dictionary<uint, bool> Bools = new();
internal readonly Dictionary<uint, double> Floats = new();
internal readonly Dictionary<uint, string> Strings = new();
internal readonly Dictionary<uint, uint> DataIds = new();
internal readonly Dictionary<uint, uint> InstanceIds = new();
internal uint[] SpellBook = Array.Empty<uint>();
public bool Identified { get; internal set; }
/// <summary>A CreateObject/UpdateObject has described it (false for placeholders from inventory events).</summary>
public bool Described { get; private set; }
public long CreatedMs { get; internal set; }
public long UpdatedMs { get; internal set; }
public bool TryGetInt(uint key, out int v) => Ints.TryGetValue(key, out v);
public bool TryGetInt64(uint key, out long v) => Int64s.TryGetValue(key, out v);
public bool TryGetBool(uint key, out bool v) => Bools.TryGetValue(key, out v);
public bool TryGetFloat(uint key, out double v) => Floats.TryGetValue(key, out v);
public bool TryGetString(uint key, out string v) => Strings.TryGetValue(key, out v!);
public bool TryGetDataId(uint key, out uint v) => DataIds.TryGetValue(key, out v);
public bool TryGetInstanceId(uint key, out uint v) => InstanceIds.TryGetValue(key, out v);
public IReadOnlyList<uint> Spells => SpellBook;
public bool IsCreature => (ItemType & 0x10) != 0;
public bool IsContainer => (ItemType & 0x200) != 0;
internal void Apply(ObjectCreateData d, long nowMs)
{
Described = true;
Desc = d;
ContainerId = d.ContainerId ?? 0;
WielderId = d.WielderId ?? 0;
WieldedLocation = d.CurrentWieldedLocation ?? 0;
StackSize = d.StackSize ?? 1;
Value = d.Value ?? 0;
if (d.Position.HasValue) Position = d.Position;
PhysicsState = d.PhysicsState;
if (d.Sequences.Length == 9)
{
PositionSeq = d.Sequences[0];
TeleportSeq = d.Sequences[4];
ServerControlSeq = d.Sequences[5];
ForcePositionSeq = d.Sequences[6];
InstanceSeq = d.Sequences[8];
}
UpdatedMs = nowMs;
if (CreatedMs == 0) CreatedMs = nowMs;
}
public override string ToString() => $"0x{Id:X8} {Name}";
}

View file

@ -0,0 +1,597 @@
// ============================================================================
// RynthCore.Headless - World/WorldState.cs
// The client's picture of the world, kept from the server's messages: the object
// table, the player's state, and the results of the player's actions (use done,
// errors, attack done, combat notices). ClientSession hands every message to Apply.
// Single-threaded (the session's tick).
// ============================================================================
using System.Buffers.Binary;
using RynthCore.Engine.Compatibility;
using RynthCore.Headless.Messages;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Headless.World;
public sealed class WorldState
{
private readonly Dictionary<uint, WorldObject> _objects = new();
private readonly Func<long> _now;
internal WorldState(Func<long> nowMs) => _now = nowMs;
public PlayerState Player { get; } = new();
public IReadOnlyDictionary<uint, WorldObject> Objects => _objects;
/// <summary>
/// The player's run rate as the server uses it (the RunForward speed in its echo of our
/// own motion); ground speed is 4 m/s times this. Null until the server has echoed a run.
/// </summary>
public float? PlayerRunRate { get; private set; }
/// <summary>The container the player last opened (ViewContents), 0 if none.</summary>
public uint OpenContainer { get; internal set; }
public event Action<WorldObject>? ObjectCreated;
public event Action<WorldObject>? ObjectUpdated;
/// <summary>SetState changed an object's physics state (doors opening/closing, ...).</summary>
public event Action<WorldObject>? ObjectStateChanged;
public event Action<uint>? ObjectDeleted;
/// <summary>UseDone: 0 = success, else a WeenieError code.</summary>
public event Action<uint>? UseDone;
public event Action<uint>? AttackDone;
/// <summary>WeenieError / WeenieErrorWithString (code, text or "").</summary>
public event Action<uint, string>? Error;
/// <summary>InventoryServerSaveFailed (item, error).</summary>
public event Action<uint, uint>? InventoryFailed;
public event Action<CombatNotice>? Combat;
/// <summary>An identify reply arrived (object, success).</summary>
public event Action<uint, bool>? Identified;
public event Action<Enchantment>? EnchantmentAdded;
public event Action<ushort>? EnchantmentRemoved;
public event Action<string>? TransientMessage;
public event Action? PlayerDescribed;
/// <summary>The server started moving the player to a target (MoveToObject / MoveToPosition motion).</summary>
public event Action<MotionUpdate>? PlayerMoveTo;
public event Action<uint>? ContainerOpened;
/// <summary>CloseGroundContainer: the server stopped showing us a container.</summary>
public event Action<uint>? ContainerClosed;
/// <summary>Motion / vector / position news about an object (not the player's own echoes).</summary>
public event Action<uint>? ObjectMoved;
/// <summary>UpdateHealth (game event 0x01C0): object, health fraction.</summary>
public event Action<uint, float>? HealthUpdated;
/// <summary>The server teleported the player (PlayerTeleport 0xF751).</summary>
public event Action? PlayerTeleported;
/// <summary>The server moved the player (teleport or a position correction).</summary>
public event Action<WorldPosition>? PlayerCorrected;
/// <summary>An UpdateMotion's interpreted state (movement type 0) for any object, the player's own included.</summary>
public event Action<uint, InterpretedMotion>? ObjectMotion;
/// <summary>An identify reply's spell book and creature profile; raised just before <see cref="Identified"/>.</summary>
public event Action<IdentifyDetails>? IdentifyDetailed;
public WorldObject? Get(uint id) => _objects.TryGetValue(id, out WorldObject? o) ? o : null;
public WorldObject? PlayerObject => Get(Player.Id);
/// <summary>Items inside <paramref name="container"/> (direct children).</summary>
public IEnumerable<WorldObject> Contents(uint container) => _objects.Values.Where(o => o.ContainerId == container);
/// <summary>Everything the player carries: the main pack, side packs and their contents, and wielded items.</summary>
public IEnumerable<WorldObject> Inventory()
{
uint me = Player.Id;
var packs = new HashSet<uint> { me };
foreach (WorldObject o in _objects.Values)
if (o.ContainerId == me && o.IsContainer) packs.Add(o.Id);
return _objects.Values.Where(o => o.Id != me && (packs.Contains(o.ContainerId) || o.WielderId == me));
}
/// <summary>Straight-line distance in metres between two objects in the same landblock (null otherwise).</summary>
public float? Distance(uint a, uint b)
{
WorldPosition? pa = Get(a)?.Position, pb = Get(b)?.Position;
if (pa is not { } x || pb is not { } y) return null;
return Geometry.Distance(x, y);
}
internal void Apply(ServerMessage msg)
{
ReadOnlySpan<byte> b = msg.Body;
long now = _now();
switch (msg.Opcode)
{
case Opcode.ObjectCreate:
case WorldOpcode.UpdateObject:
if (!ObjectCreate.TryParse(b, out ObjectCreateData d)) return;
// New if never seen, or only known as a placeholder (from a ViewContents / inventory
// event that arrived before the object's own CreateObject, as ACE sends corpse contents).
bool isNew = !_objects.TryGetValue(d.Id, out WorldObject? o) || !o.Described;
o ??= new WorldObject(d.Id);
o.Apply(d, now);
_objects[d.Id] = o;
if (d.Id == Player.Id) break;
if (isNew) ObjectCreated?.Invoke(o); else ObjectUpdated?.Invoke(o);
break;
case Opcode.ObjectDelete:
if (WorldMessages.TryU32(b, out uint del) && _objects.Remove(del))
{
Player.RemoveFromPack(del);
Player.Equipped.Remove(del);
ObjectDeleted?.Invoke(del);
}
break;
case Opcode.PlayerCreate:
if (WorldMessages.TryU32(b, out uint pid))
{
Player.Id = pid;
OnPlayerKnown();
}
break;
case WorldOpcode.UpdatePosition:
if (WorldMessages.TryUpdatePosition(b, out PositionUpdate pu) && _objects.TryGetValue(pu.Id, out WorldObject? po))
{
// Our own position: the server echoes what we reported (already behind us
// while we walk). Take it only when it is a teleport or a correction (the
// teleport / force-position sequence moved), or when we have none yet.
bool mine = pu.Id == Player.Id;
bool correction = pu.TeleportSeq != po.TeleportSeq || pu.ForcePositionSeq != po.ForcePositionSeq;
if (!mine || correction || po.Position == null)
{
po.Position = pu.Position;
if (mine && correction) PlayerCorrected?.Invoke(pu.Position);
}
po.Vx = pu.Vx; po.Vy = pu.Vy; po.Vz = pu.Vz;
po.InstanceSeq = pu.InstanceSeq;
po.PositionSeq = pu.PositionSeq;
po.TeleportSeq = pu.TeleportSeq;
po.ForcePositionSeq = pu.ForcePositionSeq;
po.UpdatedMs = now;
if (!mine) ObjectMoved?.Invoke(pu.Id);
}
break;
case WorldOpcode.UpdateMotion:
if (WorldMessages.TryUpdateMotion(b, out MotionUpdate mu) && _objects.TryGetValue(mu.Id, out WorldObject? mo))
{
mo.Stance = mu.Stance;
mo.ServerControlSeq = mu.ServerControlSeq;
if (mu.Id != Player.Id) ObjectMoved?.Invoke(mu.Id);
if (mu.Id == Player.Id && !mu.Autonomous && mu.MovementType is 6 or 7)
PlayerMoveTo?.Invoke(mu);
if (mu.Id == Player.Id && MotionMessages.TryInterpreted(b, out InterpretedMotion im)
&& im.ForwardCommand == MotionCommand.RunForward && im.ForwardSpeed > 0.5f && im.ForwardSpeed < 10f)
PlayerRunRate = im.ForwardSpeed;
if (ObjectMotion != null && MotionMessages.TryInterpreted(b, out InterpretedMotion om)) ObjectMotion(mu.Id, om);
}
break;
case Opcode.PlayerTeleport:
if (ForgetOnTeleport) ForgetSurroundings();
PlayerTeleported?.Invoke();
break;
case WorldOpcode.VectorUpdate:
if (WorldMessages.TryU32(b, out uint vid) && vid != Player.Id && _objects.ContainsKey(vid)) ObjectMoved?.Invoke(vid);
break;
case WorldOpcode.SetState:
if (WorldMessages.TryU32U32(b, out uint sid, out uint state) && _objects.TryGetValue(sid, out WorldObject? so))
{
so.PhysicsState = state;
ObjectStateChanged?.Invoke(so);
}
break;
case WorldOpcode.PickupEvent:
// The object left the 3D world (picked up by someone).
if (WorldMessages.TryU32(b, out uint picked) && _objects.TryGetValue(picked, out WorldObject? pk))
pk.Position = null;
break;
case WorldOpcode.ParentEvent:
if (WorldMessages.TryU32U32(b, out uint parent, out uint child) && _objects.TryGetValue(child, out WorldObject? co))
{
co.WielderId = parent;
co.Position = null;
}
break;
case WorldOpcode.SetStackSize:
if (WorldMessages.TrySetStackSize(b, out uint stackId, out uint size, out uint value) && _objects.TryGetValue(stackId, out WorldObject? st))
{
st.StackSize = size;
st.Value = (int)value;
ObjectUpdated?.Invoke(st);
}
break;
case WorldOpcode.InventoryRemoveObject:
if (WorldMessages.TryU32(b, out uint gone))
{
_objects.Remove(gone);
Player.RemoveFromPack(gone);
Player.Equipped.Remove(gone);
ObjectDeleted?.Invoke(gone);
}
break;
case WorldOpcode.PrivateUpdateAttribute:
if (WorldMessages.TryPrivateAttribute(b, out uint attr, out AttributeInfo ai)) Player.Attributes[attr] = ai;
break;
case WorldOpcode.PrivateUpdateVital:
if (WorldMessages.TryPrivateVital(b, out uint vital, out VitalInfo vi)) Player.Vitals[vital] = vi;
break;
case WorldOpcode.PrivateUpdateVitalCurrent:
if (WorldMessages.TryPrivateVitalCurrent(b, out uint vc, out uint cur) && vc is >= 1 and <= 3)
{
Player.Vitals.TryGetValue(vc, out VitalInfo old);
Player.Vitals[vc] = old with { Current = cur };
}
break;
case WorldOpcode.PrivateUpdateSkill:
if (WorldMessages.TryPrivateSkill(b, out SkillInfo si)) Player.Skills[si.Id] = si;
break;
case Opcode.GameEvent:
ApplyEvent(msg, now);
break;
default:
if (PropertyWire.IsPropertyUpdateOpcode(msg.Opcode))
ApplyProperty(msg);
break;
}
}
private void ApplyProperty(ServerMessage msg)
{
// PropertyWire reads from the opcode on.
Span<byte> whole = new byte[msg.Body.Length + 4];
BinaryPrimitives.WriteUInt32LittleEndian(whole, msg.Opcode);
msg.Body.CopyTo(whole.Slice(4));
if (!PropertyWire.TryParsePropertyUpdate(whole, out PropertyUpdate u)) return;
uint id = u.IsPrivate ? Player.Id : u.ObjectId;
if (!_objects.TryGetValue(id, out WorldObject? o)) return;
switch (u.Kind)
{
case PropertyKind.Int: o.Ints[u.Key] = (int)u.Integer; break;
case PropertyKind.Int64: o.Int64s[u.Key] = u.Integer; break;
case PropertyKind.Bool: o.Bools[u.Key] = u.Integer != 0; break;
case PropertyKind.Float: o.Floats[u.Key] = u.Real; break;
case PropertyKind.String: o.Strings[u.Key] = u.Text ?? ""; break;
case PropertyKind.DataId: o.DataIds[u.Key] = (uint)u.Integer; break;
case PropertyKind.InstanceId:
o.InstanceIds[u.Key] = (uint)u.Integer;
if (u.Key == 2) o.ContainerId = (uint)u.Integer; // Container
if (u.Key == 3) o.WielderId = (uint)u.Integer; // Wielder
break;
}
if (id != Player.Id) ObjectUpdated?.Invoke(o);
}
private void ApplyEvent(ServerMessage msg, long now)
{
ReadOnlySpan<byte> e = msg.EventBody;
var r = new NetReader(e);
switch (msg.EventType)
{
case PlayerDescription.EventType:
if (!PlayerDescription.TryParse(e, out PlayerDescriptionData pd)) return;
ApplyDescription(pd);
break;
case WorldEvent.PutObjInContainer:
if (r.U32(out uint item) && r.U32(out uint container) && r.I32(out int slot) && r.U32(out uint ctype))
{
WorldObject o = GetOrStub(item);
o.ContainerId = container;
o.WielderId = 0;
o.WieldedLocation = 0;
o.Position = null;
Player.Equipped.Remove(item);
if (container == Player.Id)
{
Player.RemoveFromPack(item);
List<uint> list = ctype == 0 ? Player.MainPack : Player.SidePacks;
list.Insert(Math.Clamp(slot, 0, list.Count), item);
}
else
{
Player.RemoveFromPack(item);
}
ObjectUpdated?.Invoke(o);
}
break;
case WorldEvent.WieldObject:
if (r.U32(out uint wItem) && r.I32(out int loc))
{
WorldObject o = GetOrStub(wItem);
o.WielderId = Player.Id;
o.ContainerId = 0;
o.WieldedLocation = (uint)loc;
Player.RemoveFromPack(wItem);
Player.Equipped[wItem] = (uint)loc;
ObjectUpdated?.Invoke(o);
}
break;
case WorldEvent.PutObjectIn3D:
if (r.U32(out uint dropped) && _objects.TryGetValue(dropped, out WorldObject? dObj))
{
dObj.ContainerId = 0;
dObj.WielderId = 0;
Player.RemoveFromPack(dropped);
Player.Equipped.Remove(dropped);
ObjectUpdated?.Invoke(dObj);
}
break;
case WorldEvent.ViewContents:
if (r.U32(out uint vc) && r.ListCount(out int n, 8))
{
for (int i = 0; i < n; i++)
if (r.U32(out uint cid) && r.U32(out _)) GetOrStub(cid).ContainerId = vc;
OpenContainer = vc;
ContainerOpened?.Invoke(vc);
}
break;
case WorldEvent.CloseGroundContainer:
if (r.U32(out uint closed))
{
if (closed == OpenContainer) OpenContainer = 0;
ContainerClosed?.Invoke(closed);
}
break;
case WorldEvent.IdentifyObjectResponse:
{
Span<byte> whole = new byte[e.Length + 4];
BinaryPrimitives.WriteUInt32LittleEndian(whole, msg.EventType);
e.CopyTo(whole.Slice(4));
if (!PropertyWire.TryParseIdentify(whole, out IdentifyRecord rec)) return;
if (_objects.TryGetValue(rec.ObjectId, out WorldObject? io) && rec.Success)
{
PropertyBag bag = rec.Properties;
foreach (var kv in bag.Ints) io.Ints[kv.Key] = kv.Value;
foreach (var kv in bag.Int64s) io.Int64s[kv.Key] = kv.Value;
foreach (var kv in bag.Bools) io.Bools[kv.Key] = kv.Value;
foreach (var kv in bag.Floats) io.Floats[kv.Key] = kv.Value;
foreach (var kv in bag.Strings) io.Strings[kv.Key] = kv.Value;
foreach (var kv in bag.DataIds) io.DataIds[kv.Key] = kv.Value;
foreach (var kv in bag.InstanceIds) io.InstanceIds[kv.Key] = kv.Value;
io.Identified = true;
}
if (IdentifyDetailsReader.TryParse(whole, out IdentifyDetails det))
{
if (io != null && rec.Success && det.HasSpellBook) io.SpellBook = det.Spells;
IdentifyDetailed?.Invoke(det);
}
Identified?.Invoke(rec.ObjectId, rec.Success);
break;
}
case WorldEvent.UpdateHealth:
if (r.U32(out uint hid) && r.F32(out float ratio))
{
if (_objects.TryGetValue(hid, out WorldObject? ho)) ho.HealthRatio = ratio;
HealthUpdated?.Invoke(hid, ratio);
}
break;
case WorldEvent.UseDone:
if (r.U32(out uint ud)) UseDone?.Invoke(ud);
break;
case WorldEvent.AttackDone:
if (r.U32(out uint ad)) AttackDone?.Invoke(ad);
break;
case WorldEvent.WeenieError:
if (r.U32(out uint we)) Error?.Invoke(we, "");
break;
case WorldEvent.WeenieErrorWithString:
if (r.U32(out uint ws) && r.String16L(out string wtext)) Error?.Invoke(ws, wtext);
break;
case WorldEvent.InventoryServerSaveFailed:
if (r.U32(out uint fi) && r.U32(out uint ferr)) InventoryFailed?.Invoke(fi, ferr);
break;
case WorldEvent.TransientString:
if (r.String16L(out string ts)) TransientMessage?.Invoke(ts);
break;
case WorldEvent.AttackerNotification:
if (r.String16L(out string dn) && r.U32(out uint dt) && r.F64(out double hp) && r.U32(out uint dmg) && r.U32(out uint crit))
Combat?.Invoke(new CombatNotice(msg.EventType, dn, dt, hp, dmg, crit != 0));
break;
case WorldEvent.DefenderNotification:
if (r.String16L(out string an) && r.U32(out uint adt) && r.F64(out double ahp) && r.U32(out uint admg) && r.U32(out _) && r.U32(out uint acrit))
Combat?.Invoke(new CombatNotice(msg.EventType, an, adt, ahp, admg, acrit != 0));
break;
case WorldEvent.EvasionAttacker:
case WorldEvent.EvasionDefender:
case WorldEvent.VictimNotification:
case WorldEvent.KillerNotification:
if (r.String16L(out string en)) Combat?.Invoke(new CombatNotice(msg.EventType, en, 0, 0, 0, false));
break;
case WorldEvent.MagicUpdateSpell:
if (r.U16(out ushort learned)) Player.Spells.Add(learned);
break;
case WorldEvent.MagicRemoveSpell:
if (r.U16(out ushort forgot)) Player.Spells.Remove(forgot);
break;
case WorldEvent.MagicUpdateEnchantment:
if (PlayerDescription.ReadEnchantment(ref r, out Enchantment en1))
{
Player.SetEnchantment(en1);
EnchantmentAdded?.Invoke(en1);
}
break;
case WorldEvent.MagicUpdateMultipleEnchantments:
{
var list = new List<Enchantment>();
if (!PlayerDescription.ReadEnchantmentList(ref r, list)) return;
foreach (Enchantment x in list) { Player.SetEnchantment(x); EnchantmentAdded?.Invoke(x); }
break;
}
case WorldEvent.MagicRemoveEnchantment:
case WorldEvent.MagicDispelEnchantment:
if (WorldMessages.TryLayeredSpell(ref r, out ushort sp, out ushort layer) && Player.RemoveEnchantment(sp, layer))
EnchantmentRemoved?.Invoke(sp);
break;
case WorldEvent.MagicRemoveMultipleEnchantments:
case WorldEvent.MagicDispelMultipleEnchantments:
if (r.ListCount(out int rn, 4))
for (int i = 0; i < rn; i++)
if (WorldMessages.TryLayeredSpell(ref r, out ushort s2, out ushort l2) && Player.RemoveEnchantment(s2, l2))
EnchantmentRemoved?.Invoke(s2);
break;
case WorldEvent.MagicPurgeEnchantments:
foreach (Enchantment x in Player.Enchantments.ToList())
if (x.SpellId != 666) { Player.RemoveEnchantment(x.SpellId, x.Layer); EnchantmentRemoved?.Invoke(x.SpellId); }
break;
case WorldEvent.MagicPurgeBadEnchantments:
// Harmful = not flagged Beneficial (0x2000000).
foreach (Enchantment x in Player.Enchantments.ToList())
if ((x.StatModType & 0x2000000) == 0 && x.SpellId != 666) { Player.RemoveEnchantment(x.SpellId, x.Layer); EnchantmentRemoved?.Invoke(x.SpellId); }
break;
}
}
private void ApplyDescription(PlayerDescriptionData pd)
{
PlayerState p = Player;
p.Description = pd;
foreach (var kv in pd.Attributes) p.Attributes[kv.Key] = kv.Value;
foreach (var kv in pd.Vitals) p.Vitals[kv.Key] = kv.Value;
foreach (var kv in pd.Skills) p.Skills[kv.Key] = kv.Value;
p.Spells.Clear();
p.Spells.UnionWith(pd.Spells);
p.Enchantments.Clear();
p.Enchantments.AddRange(pd.Enchantments);
if (pd.InventoryFound)
{
p.MainPack.Clear();
p.SidePacks.Clear();
foreach (PackEntry it in pd.Inventory)
(it.ContainerType == 0 ? p.MainPack : p.SidePacks).Add(it.Id);
p.Equipped.Clear();
foreach (EquippedEntry eq in pd.Equipped) p.Equipped[eq.Id] = eq.Location;
}
p.DescriptionReceived = true;
// The player's own object gets the property tables (it may not exist yet: PlayerDescription comes first).
if (p.Id != 0) CopyProperties(pd, GetOrStub(p.Id));
else _pendingDescription = pd;
PlayerDescribed?.Invoke();
}
private PlayerDescriptionData? _pendingDescription;
internal void OnPlayerKnown()
{
if (_pendingDescription != null && Player.Id != 0)
{
CopyProperties(_pendingDescription, GetOrStub(Player.Id));
_pendingDescription = null;
}
}
private static void CopyProperties(PlayerDescriptionData pd, WorldObject o)
{
foreach (var kv in pd.Ints) o.Ints[kv.Key] = kv.Value;
foreach (var kv in pd.Int64s) o.Int64s[kv.Key] = kv.Value;
foreach (var kv in pd.Bools) o.Bools[kv.Key] = kv.Value;
foreach (var kv in pd.Floats) o.Floats[kv.Key] = kv.Value;
foreach (var kv in pd.Strings) o.Strings[kv.Key] = kv.Value;
foreach (var kv in pd.DataIds) o.DataIds[kv.Key] = kv.Value;
foreach (var kv in pd.InstanceIds) o.InstanceIds[kv.Key] = kv.Value;
}
/// <summary>
/// On a teleport (portal, recall) the retail client drops everything around it; ACE sends no
/// deletes for what was left behind, only creates for the new surroundings. Keeping them left
/// ghosts: a headless bot on a 4Hives route "used" Hive 3's Brood Matron corpse from Hive 4 for half an
/// hour (2026-10-29). Kept: the player and what it carries (packs, their contents, worn items).
/// </summary>
/// <summary>Drop the surroundings on a teleport, as the retail client does (on unless a test replay needs its ghosts).</summary>
public bool ForgetOnTeleport { get; set; } = true;
private void ForgetSurroundings()
{
uint me = Player.Id;
if (me == 0) return;
var keep = new HashSet<uint>(Inventory().Select(o => o.Id)) { me };
foreach (uint id in _objects.Keys.Where(id => !keep.Contains(id)).ToList())
{
_objects.Remove(id);
ObjectDeleted?.Invoke(id);
}
OpenContainer = 0;
}
/// <summary>
/// Drops an object on the client's own initiative (a ghost the server stopped talking about),
/// as an ObjectDelete would but without raising <see cref="ObjectDeleted"/>: the caller reports
/// it. If the server still has it, its next CreateObject brings it back.
/// </summary>
internal bool ForgetObject(uint id)
{
if (!_objects.Remove(id)) return false;
Player.RemoveFromPack(id);
Player.Equipped.Remove(id);
return true;
}
private WorldObject GetOrStub(uint id)
{
if (!_objects.TryGetValue(id, out WorldObject? o))
{
o = new WorldObject(id);
_objects[id] = o;
}
return o;
}
}
public static class Geometry
{
/// <summary>
/// Metres between two positions. Outdoor cells: landblock x/y are 192 m apart, so positions
/// in neighbouring landblocks compare correctly. Indoor cells use their landblock frame.
/// </summary>
public static float Distance(WorldPosition a, WorldPosition b)
{
float ax = a.X + (a.Cell >> 24) * 192f, ay = a.Y + ((a.Cell >> 16) & 0xFF) * 192f;
float bx = b.X + (b.Cell >> 24) * 192f, by = b.Y + ((b.Cell >> 16) & 0xFF) * 192f;
float dx = ax - bx, dy = ay - by, dz = a.Z - b.Z;
return MathF.Sqrt(dx * dx + dy * dy + dz * dz);
}
/// <summary>Distance on the ground plane (ignores height).</summary>
public static float Distance2D(WorldPosition a, WorldPosition b)
{
float ax = a.X + (a.Cell >> 24) * 192f, ay = a.Y + ((a.Cell >> 16) & 0xFF) * 192f;
float bx = b.X + (b.Cell >> 24) * 192f, by = b.Y + ((b.Cell >> 16) & 0xFF) * 192f;
return MathF.Sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
}

View file

@ -109,6 +109,14 @@ internal static class LaunchCommand
a.InjectionMode = InjMode.DecalBridge;
}
// Headless accounts (rynth-headless.exe instead of acclient) are listed in
// headless-accounts.json the same way. This tool only starts acclient: such an account
// stays RynthCore here (what appsettings.json says) and is launched as one, with a notice.
HashSet<string> headlessIds = RynthCore.App.HeadlessAccountModes.ReadIds(
RynthCore.App.HeadlessAccountModes.PathIn(Path.GetDirectoryName(settingsPath)!), out string? headlessModesError);
if (headlessModesError != null)
Log(headlessModesError);
// ── Resolve account ──────────────────────────────────────────────────
List<AccountDto> accounts = settings.AccountProfiles ?? new();
List<ServerDto> servers = settings.ServerProfiles ?? new();
@ -150,6 +158,9 @@ internal static class LaunchCommand
return 2;
}
if (RynthCore.App.HeadlessAccountModes.IsHeadless(headlessIds, account.Id, (RynthCore.App.InjectionMode)(int)account.InjectionMode))
Log($"Account '{account.AccountName}' is set to Headless in the launcher; --launch starts it in acclient.exe with RynthCore instead " +
"(the launcher starts rynth-headless.exe for it).");
if (account.InjectionMode == InjMode.Decal && !withDecal)
Log($"WARNING: account '{account.AccountName}' is configured for Decal mode; --launch always injects the RynthCore engine (pass --decal for both).");
// "Decal + RynthCore" accounts launch as --decal does. Registration of the Decal
@ -440,6 +451,7 @@ internal static class LaunchCommand
private enum EmulatorKind { Ace = 0, Gdle = 1 }
// No Headless (3): appsettings.json lists Headless accounts as RynthCore (headless-accounts.json above).
private enum InjMode { RynthCore = 0, Decal = 1, DecalBridge = 2 }
private sealed class LaunchContextDto

View file

@ -19,6 +19,8 @@
<!-- "Decal + RynthCore" accounts live in decal-accounts.json beside appsettings.json. -->
<Compile Include="..\RynthCore.App\InjectionMode.cs" Link="Shared\InjectionMode.cs" />
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
<!-- Headless accounts: headless-accounts.json (the injector launch command starts them as RynthCore, with a notice). -->
<Compile Include="..\RynthCore.App\HeadlessAccountModes.cs" Link="Shared\HeadlessAccountModes.cs" />
<!-- Saved account passwords are DPAPI-encrypted (PasswordProtected in appsettings.json). -->
<Compile Include="..\RynthCore.App\AccountPasswordProtection.cs" Link="Shared\AccountPasswordProtection.cs" />
<Compile Include="..\RynthCore.App\AcClientCommandLine.cs" Link="Shared\AcClientCommandLine.cs" />

View file

@ -0,0 +1,37 @@
using System.Diagnostics;
namespace RynthCore.StatusAgent;
/// <summary>
/// Is the client behind a status file still running? A retail client's file is named by its own
/// acclient pid. A headless character's (rynth-headless, several characters per process) is named
/// by a synthetic client id and carries headless / hostPid instead: then the host process must be
/// up and be a rynth-headless. Both checks guard against a recycled pid owned by something else.
/// </summary>
internal static class ClientLiveness
{
public const string HeadlessProcess = "rynth-headless";
public static bool IsAlive(int pid, bool headless, int hostPid, Func<int, string?> processName)
{
if (headless)
{
if (hostPid <= 0) return false;
string? host = processName(hostPid);
return host != null && host.Contains(HeadlessProcess, StringComparison.OrdinalIgnoreCase);
}
string? name = processName(pid);
return name != null && name.Contains("acclient", StringComparison.OrdinalIgnoreCase);
}
/// <summary>The process's name, or null when there is no such process.</summary>
public static string? ProcessName(int pid)
{
try
{
using Process p = Process.GetProcessById(pid);
return p.ProcessName;
}
catch { return null; } // ArgumentException = no such process
}
}

View file

@ -44,6 +44,11 @@ internal sealed class StatusFileModel
// left; the agent adds names/icons from portal.dat) and where the character stands, outdoors too.
[JsonPropertyName("enchantments")] public List<EnchantmentIn>? Enchantments { get; set; }
[JsonPropertyName("opos")] public PositionIn? Opos { get; set; }
// rynth-headless: one process hosts several characters, so "pid" is a per-character client id and
// the host process (hostPid, named hostProcess) is what must be alive (see ClientLiveness).
[JsonPropertyName("headless")] public bool Headless { get; set; }
[JsonPropertyName("hostPid")] public int HostPid { get; set; }
[JsonPropertyName("hostProcess")] public string? HostProcess { get; set; }
// RynthRemote 0.3: the last travel the phone asked RynthNav for (destination, what the plugin did).
[JsonPropertyName("travel")] public TravelIn? Travel { get; set; }
// RynthRemote 0.4: the phone may raise attributes, vitals and skills on this client (engine API v79,

View file

@ -53,7 +53,7 @@ internal static partial class StatusReader
if (model == null) continue;
double ageSec = AgeSeconds(model.Ts, path);
bool alive = IsAcClientAlive(pid);
bool alive = ClientLiveness.IsAlive(pid, model.Headless, model.HostPid, ClientLiveness.ProcessName);
// Dead client: report it once (so the phone shows the stop), then
// retire the stale file so it doesn't linger forever.
@ -188,7 +188,7 @@ internal static partial class StatusReader
if (!m.Success) continue;
if (!int.TryParse(m.Groups[1].Value, out int pid)) continue;
if (seenPids.Contains(pid)) continue; // status file already covered it
if (!IsAcClientAlive(pid)) continue; // only living clients via the log path
if (!ClientLiveness.IsAlive(pid, false, 0, ClientLiveness.ProcessName)) continue; // only living clients via the log path
string? hb = TailFindHeartbeat(path);
if (hb == null) continue;
@ -268,18 +268,6 @@ internal static partial class StatusReader
catch { return double.MaxValue; }
}
private static bool IsAcClientAlive(int pid)
{
try
{
using Process p = Process.GetProcessById(pid);
// Guard against PID reuse: a recycled PID owned by some other process
// must not read as a live AC client.
return p.ProcessName.Contains("acclient", StringComparison.OrdinalIgnoreCase);
}
catch { return false; } // ArgumentException = no such process
}
private static string? TailFindHeartbeat(string path)
{
try