refactor(app): extract LiveSessionController for network-side session lifecycle (Step 2)

Step 2 of the extraction sequence in docs/architecture/code-structure.md
§4. Lifts DNS resolution + WorldSession instantiation + wireEvents
callback + per-frame Tick + Dispose out of GameWindow.TryStartLiveSession
into a dedicated AcDream.App.Net.LiveSessionController.

What moves:
  - DNS resolution (IPAddress.TryParse + Dns.GetHostAddresses fallback,
    IPv4 preferred) → LiveSessionController.ResolveEndpoint
  - WorldSession instantiation → LiveSessionController.CreateAndWire
  - "live: connecting to ..." console line → CreateAndWire
  - Try/catch around the setup phase → CreateAndWire (separate from the
    Connect/EnterWorld try block that stays in GameWindow)
  - Per-frame _liveSession?.Tick() → _liveSessionController?.Tick()
  - OnClosing _liveSession?.Dispose() → _liveSessionController?.Dispose()

What stays in GameWindow:
  - The 25+ event subscriptions (extracted into a new private
    WireLiveSessionEvents method that the controller invokes via callback)
  - The Connect → CharacterList → EnterWorld → post-EnterWorld setup dance
    (touches Chat, _playerServerGuid, _vitalsVm, _worldState, _settingsStore,
    _settingsVm, _playerModeAutoEntry; moving these would balloon Step 2's
    scope and risk surface)
  - All 60+ outbound _liveSession.Send* call sites (touch the field by
    name; LiveSessionController.Session is the controller-side mirror)

The _liveSession field remains as a convenience handle synced with
_liveSessionController.Session; it tracks the same WorldSession instance.

Behavior preservation:
  - Same DNS-resolution sequence, same "live: connecting to ..." line,
    same wiring-vs-Connect ordering as pre-refactor.
  - Same 25+ event subscriptions in the same order, byte-for-byte.
  - Same Connect/EnterWorld error handling (the catch block stays in
    GameWindow because it disposes _combatChatTranslator which is also
    a GameWindow field).

Closes #76.

One subtle nullable-flow fix the compiler required: the chat-bus
lambda's `var liveSession = _liveSession;` capture became
`var liveSession = session;` (the non-null parameter) so the compiler
can prove non-null inside the lambda body. Both pointed to the same
WorldSession instance; only the static analysis changed.

Verification:
  - dotnet build green
  - dotnet test: AcDream.App.Tests 10/10, Core.Net.Tests 294/294,
    UI.Abstractions.Tests 419/419 — all green. Core.Tests 1073/1081
    (same 8 pre-existing physics failures as baseline; unrelated).
  - Live ACE session against +Acdream verified end-to-end:
    * Connection + handshake + EnterWorld
    * Door double-click → OnLiveMotionUpdated round-trip
      (cmd=0x000B open / cmd=0x000C close)
    * NPC double-click → outbound Use
    * Ground item F-key pickup × 4 successful (Amaranth, Comfrey,
      Damiana, Dragonsblood)
    * Spawn stream + chat channels + remote-entity motion all healthy
    * Clean OnClosing → controller.Dispose

Walking-range auto-walk + pickup-overshoot bugs observed during
verification are pre-existing (filed as #77); they live in
PlayerMovementController.DriveServerAutoWalk / threshold logic
which this refactor did not touch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Erik 2026-05-17 16:15:57 +02:00
parent 4f3b8a6824
commit 0b25df53df
2 changed files with 194 additions and 79 deletions

View file

@ -738,6 +738,11 @@ public sealed class GameWindow : IDisposable
// Phase 4.7: optional live connection to an ACE server. Enabled only when
// ACDREAM_LIVE=1 is in the environment — fully backward compatible with
// the offline rendering pipeline.
// Step 2 re-attempt (2026-05-16, debug pass): the network-side lifecycle
// (DNS, endpoint, WorldSession construction, Tick, Dispose) lives in
// LiveSessionController. _liveSession remains as a convenience handle
// for the ~60 outbound SendXxx call sites; it tracks Controller.Session.
private AcDream.App.Net.LiveSessionController? _liveSessionController;
private AcDream.Core.Net.WorldSession? _liveSession;
private int _liveCenterX;
private int _liveCenterY;
@ -1819,38 +1824,80 @@ public sealed class GameWindow : IDisposable
private void TryStartLiveSession()
{
if (!_options.LiveMode) return;
var host = _options.LiveHost;
var port = _options.LivePort;
var user = _options.LiveUser;
var pass = _options.LivePass;
if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pass))
// Step 2 (2026-05-16): delegate pre-Connect setup to LiveSessionController.
// The controller owns DNS resolution + WorldSession instantiation + the
// wireEvents callback; this method keeps the Connect → CharacterList →
// EnterWorld → post-setup dance because those touch GameWindow state.
_liveSessionController = new AcDream.App.Net.LiveSessionController();
_liveSession = _liveSessionController.CreateAndWire(_options, WireLiveSessionEvents);
if (_liveSession is null)
{
Console.WriteLine("live: ACDREAM_LIVE set but TEST_USER/TEST_PASS missing; skipping");
_combatChatTranslator?.Dispose();
_combatChatTranslator = null;
_liveSessionController = null;
return;
}
var user = _options.LiveUser!;
var pass = _options.LivePass!;
var host = _options.LiveHost;
var port = _options.LivePort;
try
{
// Resolve DNS names (e.g. play.coldeve.ac) as well as literal
// IP addresses. `IPAddress.Parse` throws on hostnames; fall
// back to `Dns.GetHostAddresses` and prefer IPv4 (ACE + retail
// use IPv4 UDP exclusively).
System.Net.IPAddress ip;
if (!System.Net.IPAddress.TryParse(host, out ip!))
Chat.OnSystemMessage($"connecting to {host}:{port} as {user}", chatType: 1);
_liveSession.Connect(user, pass);
Chat.OnSystemMessage("connected — character list received", chatType: 1);
if (_liveSession.Characters is null || _liveSession.Characters.Characters.Count == 0)
{
var addrs = System.Net.Dns.GetHostAddresses(host);
ip = System.Array.Find(addrs,
a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
?? (addrs.Length > 0 ? addrs[0] : throw new System.Exception(
$"DNS resolved no addresses for '{host}'"));
Console.WriteLine($"live: resolved {host} → {ip}");
Console.WriteLine("live: no characters on account; disconnecting");
_liveSessionController.Dispose();
_liveSessionController = null;
_liveSession = null;
return;
}
var endpoint = new System.Net.IPEndPoint(ip, port);
Console.WriteLine($"live: connecting to {endpoint} as {user}");
_liveSession = new AcDream.Core.Net.WorldSession(endpoint);
_liveSession.EntitySpawned += OnLiveEntitySpawned;
var chosen = _liveSession.Characters.Characters[0];
_playerServerGuid = chosen.Id;
_vitalsVm?.SetLocalPlayerGuid(chosen.Id);
Chat.SetLocalPlayerGuid(chosen.Id);
_worldState.MarkPersistent(chosen.Id);
Console.WriteLine($"live: entering world as 0x{chosen.Id:X8} {chosen.Name}");
_liveSession.EnterWorld(user, characterIndex: 0);
_activeToonKey = chosen.Name;
if (_settingsStore is not null && _settingsVm is not null)
{
var toonBag = _settingsStore.LoadCharacter(_activeToonKey);
_settingsVm.LoadCharacterContext(toonBag);
Console.WriteLine($"settings: loaded character[{_activeToonKey}] preferences");
}
_playerModeAutoEntry?.Arm();
Console.WriteLine($"live: in world — CreateObject stream active " +
$"(so far: {_liveSpawnReceived} received, {_liveSpawnHydrated} hydrated)");
}
catch (Exception ex)
{
Console.WriteLine($"live: session failed: {ex.Message}");
_combatChatTranslator?.Dispose();
_combatChatTranslator = null;
_liveSessionController?.Dispose();
_liveSessionController = null;
_liveSession = null;
}
}
/// <summary>
/// Step 2 helper: subscribes the live <paramref name="session"/> to all
/// the parsers / handlers / translators that <c>GameWindow</c> needs.
/// Called once by <see cref="LiveSessionController.CreateAndWire"/>
/// immediately after the <see cref="AcDream.Core.Net.WorldSession"/>
/// is constructed and BEFORE any network I/O.
/// </summary>
private void WireLiveSessionEvents(AcDream.Core.Net.WorldSession session)
{
_liveSession = session;
_liveSession.EntitySpawned += OnLiveEntitySpawned;
_liveSession.EntityDeleted += OnLiveEntityDeleted;
_liveSession.MotionUpdated += OnLiveMotionUpdated;
_liveSession.PositionUpdated += OnLivePositionUpdated;
@ -2011,7 +2058,11 @@ public sealed class GameWindow : IDisposable
// plus a local echo into ChatLog so the player sees their own
// message immediately. Closes over _liveSession + Chat so this
// wiring only exists for the lifetime of the live session.
var liveSession = _liveSession;
// Step 2: capture the non-null `session` parameter rather than
// the nullable _liveSession field. Semantically identical (the
// field WAS set to `session` at the top of WireLiveSessionEvents)
// but the compiler can prove non-null for the lambda body.
var liveSession = session;
var chat = Chat;
_commandBus = new AcDream.UI.Abstractions.LiveCommandBus();
var turbineChat = TurbineChat;
@ -2119,58 +2170,6 @@ public sealed class GameWindow : IDisposable
LocalPlayer.OnVitalUpdate(v.VitalId, v.Ranks, v.Start, v.Xp, v.Current);
_liveSession.VitalCurrentUpdated += v =>
LocalPlayer.OnVitalCurrent(v.VitalId, v.Current);
Chat.OnSystemMessage($"connecting to {host}:{port} as {user}", chatType: 1);
_liveSession.Connect(user, pass);
Chat.OnSystemMessage("connected — character list received", chatType: 1);
if (_liveSession.Characters is null || _liveSession.Characters.Characters.Count == 0)
{
Console.WriteLine("live: no characters on account; disconnecting");
_liveSession.Dispose();
_liveSession = null;
return;
}
var chosen = _liveSession.Characters.Characters[0];
_playerServerGuid = chosen.Id; // Phase B.2: store for Tab-key player-mode entry
_vitalsVm?.SetLocalPlayerGuid(chosen.Id); // Phase D.2a — devtools HP bar tracks this guid
Chat.SetLocalPlayerGuid(chosen.Id); // Phase J — recognize own /say echo from ACE's HearSpeech broadcast
_worldState.MarkPersistent(chosen.Id); // player entity survives landblock unloads
Console.WriteLine($"live: entering world as 0x{chosen.Id:X8} {chosen.Name}");
_liveSession.EnterWorld(user, characterIndex: 0);
// L.0 Character tab: swap the SettingsVM's character bag
// from the "default" pre-login bag to the actual chosen
// toon's bag. Every Save from now on writes under the
// chosen toon's name. LoadCharacterContext rebinds BOTH
// persisted + draft so HasUnsavedChanges doesn't flag the
// swap as a pending edit.
_activeToonKey = chosen.Name;
if (_settingsStore is not null && _settingsVm is not null)
{
var toonBag = _settingsStore.LoadCharacter(_activeToonKey);
_settingsVm.LoadCharacterContext(toonBag);
Console.WriteLine($"settings: loaded character[{_activeToonKey}] preferences");
}
// Phase K.2: arm auto-entry. The guard's predicates won't
// pass yet — the entity stream hasn't started — but the
// OnUpdate tick re-checks every frame and fires once
// everything converges (typically 100-300 ms after EnterWorld
// returns). User can pre-empt via DebugPanel "Toggle
// Free-Fly Mode" or Tab; both call Cancel() first.
_playerModeAutoEntry?.Arm();
Console.WriteLine($"live: in world — CreateObject stream active " +
$"(so far: {_liveSpawnReceived} received, {_liveSpawnHydrated} hydrated)");
}
catch (Exception ex)
{
Console.WriteLine($"live: session failed: {ex.Message}");
_combatChatTranslator?.Dispose();
_combatChatTranslator = null;
_liveSession?.Dispose();
_liveSession = null;
}
}
/// <summary>
@ -6248,7 +6247,8 @@ public sealed class GameWindow : IDisposable
// CreateObject events find their landblock already loaded in
// GpuWorldState. Non-blocking — returns immediately if no datagrams
// are in the kernel buffer. Fires EntitySpawned events synchronously.
_liveSession?.Tick();
// Step 2: routed through the controller; functionally identical.
_liveSessionController?.Tick();
// Phase K.1a — tick the input dispatcher so Hold-type bindings
// re-fire while their chord is held. K.1b adds the subscribers
@ -10194,7 +10194,8 @@ public sealed class GameWindow : IDisposable
// Phase I.7: unsubscribe combat → chat translator before the
// session it depends on goes away.
_combatChatTranslator?.Dispose();
_liveSession?.Dispose();
_liveSessionController?.Dispose();
_liveSession = null;
_audioEngine?.Dispose(); // Phase E.2: stop all voices, close AL context
_wbDrawDispatcher?.Dispose();
_skyRenderer?.Dispose(); // depends on sampler cache; dispose first