acdream/tests/AcDream.App.Tests/Composition/HostInputCameraCompositionTests.cs
Erik ceec3bc440 feat(render): Campaign V slice V4a - port TextRenderer/BitmapFont/DebugLineRenderer/TextureCache onto IGpuDevice
TextRenderer, BitmapFont, DebugLineRenderer, and TextureCache's UI-texture
upload path (GetOrUploadRenderSurface/UploadRgba8) now issue every draw and
resource creation through the pinned IGpuDevice/IGpuFrame/IGpuPassEncoder
RHI contract instead of raw GL. This is the RHI's first real production
consumer - V0-V3 only established the contract, GL backend skeleton, and a
shader-dialect migration with no live GL exercise. TextRenderer owns one
IGpuPipeline (ui_text shader, straight-alpha blend, depth disabled) and
allocates a per-bucket ring each Flush; BitmapFont's atlas texture is
created and uploaded via device.CreateTexture/.Upload; DebugLineRenderer
mirrors the same one-pipeline-per-Flush shape for its line-list draws.
World-path TextureCache methods (GetOrUpload, the raw-GL layer-array
upload) are untouched - still legacy GL, still out of scope.

Frame lifecycle: GpuDeviceFrameLifetime (RenderFrameOrchestrator.cs) wraps
IGpuDevice.BeginFrame()/IGpuFrame.End() inside the existing
IRenderFrameLifetime bracket HostInputCameraCompositionPhase already opens
per callback, additively - no frame-graph restructuring. Ported renderers
reach the frame via ICurrentGpuFrameSource, a plain interface (not a
delegate field) so WorldSceneDiagnosticsController keeps passing its
existing "no stored window/delegate" architectural-conformance test.

Two real bugs surfaced by actually exercising the RHI against a live GL
context (nothing here was previously reachable before this slice):

- GlGpuDevice.BeginFrame() now resets the render-state cache every frame.
  The cache assumes it is the sole writer of GL program/blend/depth/cull
  state, which was true while it had zero real consumers, but every
  still-legacy renderer (WbDrawDispatcher, terrain, particles, EnvCells)
  mutates that same GL state directly and never informs the cache. Once a
  legacy renderer ran between two RHI binds, the cache's belief about the
  current GL program went stale, so a later BindPipeline(text shader)
  skipped re-issuing glUseProgram and the following push-constant upload
  threw GL_INVALID_OPERATION against whatever program was actually bound.
  Reset() at the frame boundary is the same defensive move BeginPass
  already makes after a forced clear (see its comment); it costs one
  redundant state application on the frame's first bind.
- GL_MULTISAMPLE has no representation in the pinned contract. Added a
  GL-backend-internal Multisample field to GlRenderStateSnapshot/Changes,
  computed from GpuPipelineDescription.SampleCount at BindPipeline time -
  mirrors how Vulkan bakes MSAA into the pipeline instead of a separate
  toggle.

Collateral, scoped to keep the port real rather than a stub:

- GpuTextureSlot (Unassigned = uint.MaxValue, NOT 0) now flows through
  every consumer of TextureCache.GetOrUploadRenderSurface/UploadRgba8 and
  TextRenderer.DrawSprite - the entire retained UI layer, since a pervasive
  Func<uint,(uint,int,int)> sprite-resolve delegate threads through nearly
  every UI element/controller. Every prior `== 0` / `!= 0` "no texture"
  check became `.IsAssigned` / `!.IsAssigned`; slot 0 is a real assigned
  slot (the device's default white texture), so the old sentinel would
  have produced live visual regressions if left in place.
- GpuTextureSlot/IGpuDevice/IGpuFrame are internal, so ~270 previously
  public AcDream.App types that touched them (directly or transitively)
  are now internal too - safe, since AcDream.App is an exe with no
  external project references; only the two test projects consume it, via
  InternalsVisibleTo. A handful of unrelated types the sweep caught
  (ElementInfo/ImportedLayout's property-bag hierarchy, several enums used
  as public [Theory] parameters, CursorFeedbackSnapshot's DragAcceptState)
  were reverted back to public where making them internal would have
  either cascaded into unrelated files or broken xUnit's public-member
  discovery.
- ExternalViewportTextureBridge (new) registers the still-raw-GL FBO
  color textures PrivateEntityViewportRenderer/PaperdollViewportRenderer
  produce (V4g's scope) into the device's texture table for
  UiViewport.TextureHandle, via a temporary
  GlGpuDevice.RegisterExternalColorTexture escape hatch (internal, not
  part of IGpuDevice) deleted when V4g ports those viewports.
- TextRenderGlStateScope.cs and its test deleted: the pipeline description
  now bakes what it used to restore by hand.
- ResourceCleanupGroupTests/GlTextureOwnershipTests: the two source-text
  conformance tests keyed to TextRenderer's old multi-resource
  construction shape (Shader + per-flight FrameBufferSet array + white
  texture + tracked VAO/VBO, all via ResourceCleanupGroup) no longer apply
  - that shape is gone, replaced by one IGpuPipeline created through
    IGpuDevice. The construction-order test is deleted; the checked-commit
    texture-creation check now targets GlGpuTexture (which already used
    the same GlResourceCommand.CreateName primitive before this slice).

Gates:
- dotnet build -c Release: 0 warnings, 0 errors (AcDream.App has
  TreatWarningsAsErrors).
- dotnet test tests/AcDream.App.Tests -c Release: 3,840 passed / 3
  skipped (was 3,843/3 entering this slice - net 3 fewer tests:
  TextRendererFailureSafetyTests.cs deleted (2, tested the now-deleted
  TextRenderGlStateScope) plus the one retired ResourceCleanupGroupTests
  method). Full solution: 8,908 passed / 5 skipped across all nine test
  projects.
- Offline pixel gate (tools/run-offline-pixel-gate.ps1, parent ec414d60
  vs this commit): differing fraction 0.318% (1,791/563,200 compared
  pixels), above the 0.001 threshold. Investigated pixel-by-pixel rather
  than waved through: a diff heatmap plus 4x crops at the differing
  clusters show zero differences anywhere in the retained UI, terrain,
  scenery, or static meshes - every differing pixel sits on continuously-
  animated ambient content (flying-insect sprites over the swamp, foliage
  sparkle/dew glints) whose exact phase depends on elapsed wall-clock
  time, the same category the gate's own sky-masking rationale already
  documents and the campaign doc's coverage table explicitly excludes
  ("Not covered - particles"). Confirming evidence: two same-commit
  captures at HEAD compare clean against each other (0.0025%), and two
  same-commit captures at the parent compare clean against each other
  (0.0044%) - only base-vs-head is consistently elevated, which is what
  frame-pacing drift from genuinely new per-frame RHI work (BeginFrame,
  ring resets, the render-state reset above) would produce against a
  fixed wall-clock capture deadline, not a rendering defect. Recommend a
  quick user visual check of this capture pair alongside the automated
  result, matching how V2c's particle work was already handled in this
  campaign (flagged for user visual confirmation rather than blocked on
  an automated gate that cannot cover animated content).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 18:22:08 +02:00

449 lines
16 KiB
C#

using System.Numerics;
using System.Reflection;
using AcDream.App.Composition;
using AcDream.App.Input;
using AcDream.App.Rendering;
using AcDream.App.Rendering.Gpu;
using AcDream.App.Tests.Rendering.Gpu;
using AcDream.UI.Abstractions.Input;
using Silk.NET.Input;
using Silk.NET.Maths;
using Silk.NET.OpenGL;
namespace AcDream.App.Tests.Composition;
public sealed class HostInputCameraCompositionTests
{
[Fact]
public void ProductionPhasePreservesTheCompleteHostInputCameraOrder()
{
using var fixture = new Fixture();
HostInputCameraResult result = fixture.Phase().Compose(fixture.Platform);
Assert.Equal(
Enum.GetValues<HostInputCameraCompositionPoint>(),
fixture.Points);
Assert.Same(fixture.Publication.GpuFrames, result.GpuFrameFlights);
Assert.Same(fixture.Publication.GpuDevice, result.GpuDevice);
Assert.Same(fixture.Publication.Keyboard, result.KeyboardSource);
Assert.Same(fixture.Publication.Mouse, result.MouseSource);
Assert.Same(fixture.Publication.Dispatcher, result.InputDispatcher);
Assert.Same(fixture.Publication.Camera, result.CameraController);
Assert.Same(fixture.Publication.Pointer, result.CameraPointerInput);
Assert.Equal(1280f / 720f, fixture.ViewportAspect.Aspect, precision: 5);
Assert.Equal((1280, 720), fixture.Factory.Viewport.Size);
}
[Theory]
[MemberData(nameof(FaultPointValues))]
public void FailureAtEveryProductionBoundaryStopsTheExactSuffix(
int faultPointValue)
{
var faultPoint = (HostInputCameraCompositionPoint)faultPointValue;
using var fixture = new Fixture(faultPoint);
Assert.Throws<InvalidOperationException>(() =>
fixture.Phase().Compose(fixture.Platform));
HostInputCameraCompositionPoint[] expected =
Enum.GetValues<HostInputCameraCompositionPoint>()
.TakeWhile(point => point <= faultPoint)
.ToArray();
Assert.Equal(expected, fixture.Points);
fixture.Publication.AssertPublishedThrough(faultPoint);
}
public static TheoryData<int> FaultPointValues()
{
var data = new TheoryData<int>();
foreach (HostInputCameraCompositionPoint point in
Enum.GetValues<HostInputCameraCompositionPoint>())
{
data.Add((int)point);
}
return data;
}
[Fact]
public void GameWindowUsesTheExactPlatformPreludeAndPhaseOneType()
{
string source = File.ReadAllText(Path.Combine(
FindRepoRoot(),
"src",
"AcDream.App",
"Rendering",
"GameWindow.cs"));
Assert.Contains("GameWindowPlatformAcquisition.Acquire(", source,
StringComparison.Ordinal);
Assert.Contains("new HostInputCameraCompositionPhase(", source,
StringComparison.Ordinal);
Assert.DoesNotContain("_gl = GL.GetApi(_window!)", source,
StringComparison.Ordinal);
Assert.DoesNotContain("_input = _window!.CreateInput()", source,
StringComparison.Ordinal);
}
private sealed class Fixture : IDisposable
{
private readonly HostInputCameraCompositionPoint? _failure;
public Fixture(HostInputCameraCompositionPoint? failure = null)
{
_failure = failure;
IKeyboard keyboard = DispatchProxy.Create<IKeyboard, NullDeviceProxy>();
IMouse mouse = DispatchProxy.Create<IMouse, NullDeviceProxy>();
Input = new InputContext(keyboard, mouse);
Platform = new GameWindowPlatformResult<GL, IInputContext>(null!, Input);
ViewportAspect = new ViewportAspectState();
Framebuffer = new FramebufferResizeController(ViewportAspect);
Capture = new CaptureSource();
MovementState = new RuntimeLocalPlayerMovementState();
Movement = new DispatcherMovementInputSource(MovementState, Capture);
CameraInput = new DispatcherCameraInputSource();
PlayerMode = new LocalPlayerModeState();
Chase = new ChaseCameraInputState();
Pointer = new PointerPositionState();
Factory = new Factory();
Publication = new Publication();
}
public List<HostInputCameraCompositionPoint> Points { get; } = [];
public InputContext Input { get; }
public GameWindowPlatformResult<GL, IInputContext> Platform { get; }
public ViewportAspectState ViewportAspect { get; }
public FramebufferResizeController Framebuffer { get; }
public CaptureSource Capture { get; }
public RuntimeLocalPlayerMovementState MovementState { get; }
public DispatcherMovementInputSource Movement { get; }
public DispatcherCameraInputSource CameraInput { get; }
public LocalPlayerModeState PlayerMode { get; }
public ChaseCameraInputState Chase { get; }
public PointerPositionState Pointer { get; }
public Factory Factory { get; }
public Publication Publication { get; }
public HostInputCameraCompositionPhase Phase() => new(
new HostInputCameraDependencies(
Framebuffer,
new Vector2D<int>(1280, 720),
new HostQuiescenceGate(),
Capture,
KeyBindings.RetailDefaults(),
Movement,
CameraInput,
PlayerMode,
Chase,
Pointer,
new DiagnosticLog()),
Publication,
Factory,
point =>
{
Points.Add(point);
if (_failure == point)
throw new InvalidOperationException($"fault at {point}");
});
public void Dispose()
{
Publication.Dispose();
MovementState.Dispose();
}
}
private sealed class Publication :
IGameWindowHostInputCameraPublication,
IDisposable
{
public GpuFrameFlightController? GpuFrames { get; private set; }
public IGpuDevice? GpuDevice { get; private set; }
public GpuDeviceFrameLifetime? GpuFrameLifetime { get; private set; }
public SilkKeyboardSource? Keyboard { get; private set; }
public SilkMouseSource? Mouse { get; private set; }
public IMouseLookCursor? Cursor { get; private set; }
public InputDispatcher? Dispatcher { get; private set; }
public CameraController? Camera { get; private set; }
public CameraPointerInputController? Pointer { get; private set; }
public void PublishGpuFrameFlights(GpuFrameFlightController value) =>
GpuFrames = PublishOnce(GpuFrames, value);
public void PublishGpuDevice(IGpuDevice value) =>
GpuDevice = PublishOnce(GpuDevice, value);
public void PublishGpuFrameLifetime(GpuDeviceFrameLifetime value) =>
GpuFrameLifetime = PublishOnce(GpuFrameLifetime, value);
public void PublishKeyboardSource(SilkKeyboardSource value) =>
Keyboard = PublishOnce(Keyboard, value);
public void PublishMouseSource(SilkMouseSource value) =>
Mouse = PublishOnce(Mouse, value);
public void PublishMouseLookCursor(IMouseLookCursor value) =>
Cursor = PublishOnce(Cursor, value);
public void PublishInputDispatcher(InputDispatcher value) =>
Dispatcher = PublishOnce(Dispatcher, value);
public void PublishCameraController(CameraController value) =>
Camera = PublishOnce(Camera, value);
public void PublishCameraPointerInput(CameraPointerInputController value) =>
Pointer = PublishOnce(Pointer, value);
public void AssertPublishedThrough(HostInputCameraCompositionPoint point)
{
Assert.Equal(
point >= HostInputCameraCompositionPoint.GpuFrameFlightsPublished,
GpuFrames is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.GpuDevicePublished,
GpuDevice is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.KeyboardPublished,
Keyboard is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.MousePublished,
Mouse is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.MouseLookCursorPublished,
Cursor is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.DispatcherPublished,
Dispatcher is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.CameraPublished,
Camera is not null);
Assert.Equal(
point >= HostInputCameraCompositionPoint.CameraPointerPublished,
Pointer is not null);
}
public void Dispose()
{
Pointer?.Dispose();
Pointer = null;
Dispatcher?.Dispose();
Dispatcher = null;
Mouse?.Dispose();
Mouse = null;
Keyboard?.Dispose();
Keyboard = null;
GpuDevice?.Dispose();
GpuDevice = null;
GpuFrames?.Dispose();
GpuFrames = null;
}
private static T PublishOnce<T>(T? current, T value)
where T : class
{
if (current is not null)
throw new InvalidOperationException("duplicate publication");
return value;
}
}
private sealed class Factory : IHostInputCameraCompositionFactory
{
public ViewportTarget Viewport { get; } = new();
private readonly KeyboardSurface _keyboard = new();
private readonly MouseSurface _mouse = new();
private readonly RawPointerSurface _rawPointer = new();
public IFramebufferViewportTarget CreateViewportTarget(GL gl) => Viewport;
public GpuFrameFlightController CreateGpuFrameFlights(GL gl) =>
new(new FenceApi());
public IGpuDevice CreateGpuDevice(GL gl, GpuFrameFlightController frameFlights) =>
new RecordingGpuDevice();
public WorldRenderDiagnostics CreateWorldRenderDiagnostics(
GL gl,
IRenderFrameDiagnosticLog log) =>
new(new GlStateReader(), log);
public SilkKeyboardSource CreateKeyboardSource(
IKeyboard keyboard,
HostQuiescenceGate quiescence) =>
SilkKeyboardSource.CreateDetached(_keyboard, quiescence);
public SilkMouseSource CreateMouseSource(
IMouse mouse,
IInputCaptureSource capture,
IKeyboardSource? keyboard,
HostQuiescenceGate quiescence) =>
SilkMouseSource.CreateDetached(_mouse, capture, keyboard, quiescence);
public IMouseLookCursor CreateMouseLookCursor(IMouse mouse) => new Cursor();
public InputDispatcher CreateInputDispatcher(
IKeyboardSource keyboard,
IMouseSource mouse,
KeyBindings bindings) =>
InputDispatcher.CreateDetached(keyboard, mouse, bindings);
public CameraController CreateCameraController() =>
new(new OrbitCamera(), new FlyCamera());
public IFramebufferCameraTarget CreateCameraTarget(CameraController camera) =>
new CameraTarget(camera);
public CameraPointerInputController CreateCameraPointerInput(
IReadOnlyList<IMouse> mice,
HostQuiescenceGate quiescence,
IInputCaptureSource capture,
LocalPlayerModeState playerMode,
CameraController camera,
ChaseCameraInputState chase,
IMouseSource mouse,
PointerPositionState pointer) =>
new(
[_rawPointer],
new CursorModeTarget(),
quiescence,
capture,
playerMode,
camera,
chase,
mouse,
pointer,
new Clock());
}
private sealed class InputContext(IKeyboard keyboard, IMouse mouse)
: IInputContext
{
public nint Handle => 1;
public IReadOnlyList<IGamepad> Gamepads { get; } = [];
public IReadOnlyList<IJoystick> Joysticks { get; } = [];
public IReadOnlyList<IKeyboard> Keyboards { get; } = [keyboard];
public IReadOnlyList<IMouse> Mice { get; } = [mouse];
public IReadOnlyList<IInputDevice> OtherDevices { get; } = [];
public event Action<IInputDevice, bool>? ConnectionChanged
{
add { }
remove { }
}
public void Dispose() { }
}
public class NullDeviceProxy : DispatchProxy
{
protected override object? Invoke(
MethodInfo? targetMethod,
object?[]? args)
{
Type returnType = targetMethod?.ReturnType ?? typeof(void);
if (returnType == typeof(void))
return null;
if (returnType == typeof(string))
return string.Empty;
return returnType.IsValueType
? Activator.CreateInstance(returnType)
: null;
}
}
private sealed class KeyboardSurface : IKeyboardEventSurface
{
public void AddKeyDown(Action<Key> callback) { }
public void RemoveKeyDown(Action<Key> callback) { }
public void AddKeyUp(Action<Key> callback) { }
public void RemoveKeyUp(Action<Key> callback) { }
public bool IsKeyPressed(Key key) => false;
}
private sealed class MouseSurface : IMouseEventSurface
{
public void AddMouseDown(Action<MouseButton> callback) { }
public void RemoveMouseDown(Action<MouseButton> callback) { }
public void AddMouseUp(Action<MouseButton> callback) { }
public void RemoveMouseUp(Action<MouseButton> callback) { }
public void AddMouseMove(Action<Vector2> callback) { }
public void RemoveMouseMove(Action<Vector2> callback) { }
public void AddScroll(Action<float> callback) { }
public void RemoveScroll(Action<float> callback) { }
public bool IsButtonPressed(MouseButton button) => false;
}
private sealed class RawPointerSurface : IRawPointerSurface
{
public void AddMouseMove(Action<Vector2> callback) { }
public void RemoveMouseMove(Action<Vector2> callback) { }
}
private sealed class CursorModeTarget : IPointerCursorModeTarget
{
public CursorMode CursorMode { get; set; }
}
private sealed class Cursor : IMouseLookCursor
{
public bool HasSavedMode { get; private set; }
public void Hide() => HasSavedMode = true;
public void Restore() => HasSavedMode = false;
}
private sealed class Clock : IInputMonotonicClock
{
public float NowSeconds => 0;
}
private sealed class CaptureSource : IInputCaptureSource
{
public bool WantCaptureMouse => false;
public bool WantCaptureKeyboard => false;
public bool DevToolsWantCaptureKeyboard => false;
}
private sealed class ViewportTarget : IFramebufferViewportTarget
{
public (int Width, int Height) Size { get; private set; }
public void ResizeViewport(int width, int height) => Size = (width, height);
}
private sealed class CameraTarget(CameraController camera)
: IFramebufferCameraTarget
{
public void SetAspect(float aspect) => camera.SetAspect(aspect);
}
private sealed class FenceApi : IGpuFenceApi
{
public nint Insert() => 1;
public GpuFenceWaitResult Wait(
nint fence,
bool flushCommands,
ulong timeoutNanoseconds) => GpuFenceWaitResult.Signaled;
public void Delete(nint fence) { }
}
private sealed class GlStateReader : IRenderGlStateReader
{
public RenderGlStateSnapshot CaptureState() => default;
public RenderGlScissorSnapshot CaptureScissor() => default;
}
private sealed class DiagnosticLog : IRenderFrameDiagnosticLog
{
public void WriteLine(string message) { }
}
private static string FindRepoRoot()
{
DirectoryInfo? directory = new(AppContext.BaseDirectory);
while (directory is not null)
{
if (File.Exists(Path.Combine(directory.FullName, "AcDream.slnx")))
return directory.FullName;
directory = directory.Parent;
}
throw new DirectoryNotFoundException("Could not find AcDream.slnx.");
}
}