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>
290 lines
13 KiB
C#
290 lines
13 KiB
C#
using System.Collections.Concurrent;
|
|
using AcDream.Content;
|
|
using DatReaderWriter;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Silk.NET.OpenGL;
|
|
|
|
namespace AcDream.App.Rendering;
|
|
|
|
/// <summary>
|
|
/// The subset of the production render stack that the UI Studio needs:
|
|
/// GL + dats + UiHost + the WB mesh pipeline. Constructed from the same
|
|
/// classes and the same order as <see cref="GameWindow.OnLoad"/>, minus
|
|
/// terrain / sky / physics / streaming.
|
|
/// </summary>
|
|
internal sealed record RenderStack(
|
|
GL Gl,
|
|
IDatReaderWriter Dats,
|
|
string ShaderDir,
|
|
Wb.BindlessSupport Bindless,
|
|
TextureCache TextureCache,
|
|
Shader MeshShader,
|
|
Wb.WbMeshAdapter MeshAdapter,
|
|
Wb.EntitySpawnAdapter EntitySpawnAdapter,
|
|
Wb.WbDrawDispatcher DrawDispatcher,
|
|
SceneLightingUboBinding LightingUbo,
|
|
AcDream.App.UI.UiHost UiHost,
|
|
AcDream.App.UI.UiDatFont? VitalsDatFont,
|
|
AcDream.App.UI.UiDatFont? LargeDatFont) : System.IDisposable
|
|
{
|
|
internal GpuFrameFlightController FrameFlights { get; init; } = null!;
|
|
internal IGpuDevice GpuDevice { get; init; } = null!;
|
|
internal GpuDeviceFrameLifetime FrameLifetime { get; init; } = null!;
|
|
private ResourceShutdownTransaction? _shutdown;
|
|
|
|
internal void BeginFrame() => FrameLifetime.BeginFrame();
|
|
|
|
internal void EndFrame() => FrameLifetime.EndFrame();
|
|
|
|
/// <summary>Dispose the GL pieces this stack OWNS (everything created in
|
|
/// <see cref="RenderBootstrap.Create"/>). <see cref="Dats"/> + <see cref="Gl"/> are caller-owned
|
|
/// and NOT disposed here. Called once at studio teardown.</summary>
|
|
public void Dispose()
|
|
{
|
|
_shutdown ??= new ResourceShutdownTransaction(
|
|
new ResourceShutdownStage("submitted GPU work",
|
|
[
|
|
new("frame flight drain", FrameFlights.WaitForSubmittedWork),
|
|
]),
|
|
new ResourceShutdownStage("draw frontend",
|
|
[
|
|
new("draw dispatcher", DrawDispatcher.Dispose),
|
|
]),
|
|
new ResourceShutdownStage("mesh adapter",
|
|
[
|
|
new("mesh adapter", MeshAdapter.Dispose),
|
|
]),
|
|
new ResourceShutdownStage("remaining render stack",
|
|
[
|
|
new("texture cache", TextureCache.Dispose),
|
|
new("mesh shader", MeshShader.Dispose),
|
|
new("lighting UBO", LightingUbo.Dispose),
|
|
new("UI host", UiHost.Dispose),
|
|
]),
|
|
new ResourceShutdownStage("GPU device (RHI)",
|
|
[
|
|
new("GPU device", GpuDevice.Dispose),
|
|
]),
|
|
new ResourceShutdownStage("frame flight owner",
|
|
[
|
|
new("frame flights", FrameFlights.Dispose),
|
|
]));
|
|
_shutdown.CompleteOrThrow();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Resolves a sprite id (0x06xxxxxx) to a (texture-table slot, width, height) triple.
|
|
/// Copied verbatim from GameWindow's ResolveChrome closure — it calls
|
|
/// TextureCache.GetOrUploadRenderSurface(id, out w, out h).
|
|
/// </summary>
|
|
public (GpuTextureSlot handle, int width, int height) ResolveChrome(uint spriteId)
|
|
{
|
|
GpuTextureSlot t = TextureCache.GetOrUploadRenderSurface(spriteId, out int w, out int h);
|
|
return (t, w, h);
|
|
}
|
|
|
|
// ── Font cache (per-stack, keyed by FontDid) ─────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Cache of loaded dat fonts keyed by FontDid (0x40000000-range).
|
|
/// Populated lazily by <see cref="ResolveDatFont"/>. Thread-safe for
|
|
/// concurrent reads from the studio render loop; writes happen only
|
|
/// during the first load of each distinct FontDid.
|
|
/// </summary>
|
|
private readonly ConcurrentDictionary<uint, AcDream.App.UI.UiDatFont?> _fontCache = new();
|
|
|
|
/// <summary>
|
|
/// Lazily load and cache a dat font by its FontDid. Returns null (and
|
|
/// caches null) when the Font DBObj is absent or has no foreground surface —
|
|
/// callers fall back to the global font in that case.
|
|
///
|
|
/// <para>Pre-seeds <see cref="VitalsDatFont"/> (0x40000000) and
|
|
/// <see cref="LargeDatFont"/> (0x40000001) from the already-loaded instances
|
|
/// to avoid a redundant upload on those two ids.</para>
|
|
/// </summary>
|
|
public AcDream.App.UI.UiDatFont? ResolveDatFont(uint fontDid)
|
|
{
|
|
return _fontCache.GetOrAdd(fontDid, id =>
|
|
AcDream.App.UI.UiDatFont.Load(Dats, TextureCache, id));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pre-seeds the font cache from the two already-loaded font instances
|
|
/// (VitalsDatFont = 0x40000000, LargeDatFont = 0x40000001) so that
|
|
/// <see cref="ResolveDatFont"/> returns them without a redundant GL upload.
|
|
/// Called once by <see cref="RenderBootstrap.Create"/> after the stack is
|
|
/// fully constructed.
|
|
/// </summary>
|
|
internal void SeedFontCache()
|
|
{
|
|
if (VitalsDatFont is not null)
|
|
_fontCache.TryAdd(AcDream.App.UI.UiDatFont.DefaultFontId, VitalsDatFont);
|
|
if (LargeDatFont is not null)
|
|
_fontCache.TryAdd(0x40000001u, LargeDatFont);
|
|
}
|
|
}
|
|
|
|
/// <summary>Options for <see cref="RenderBootstrap.Create"/>.</summary>
|
|
internal sealed record RenderBootstrapOptions(
|
|
AcDream.UI.Abstractions.Settings.QualitySettings Quality,
|
|
string DiagnosticsDirectory);
|
|
|
|
/// <summary>
|
|
/// Constructs the UI Studio's render stack from the production classes,
|
|
/// in the same order as <see cref="GameWindow.OnLoad"/>.
|
|
/// </summary>
|
|
internal static class RenderBootstrap
|
|
{
|
|
/// <summary>
|
|
/// Build the studio's render stack. Throws <see cref="NotSupportedException"/>
|
|
/// (same message as GameWindow) if GL_ARB_bindless_texture or
|
|
/// GL_ARB_shader_draw_parameters are absent — the modern path is mandatory.
|
|
/// </summary>
|
|
public static RenderStack Create(
|
|
GL gl,
|
|
IDatReaderWriter dats,
|
|
RenderBootstrapOptions opts)
|
|
{
|
|
// --- Bindless detection (GameWindow ~1701-1723) ---
|
|
if (!Wb.BindlessSupport.TryCreate(gl, out var bindless)
|
|
|| bindless is null
|
|
|| !bindless.HasShaderDrawParameters(gl))
|
|
{
|
|
throw new NotSupportedException(
|
|
"acdream requires GL_ARB_bindless_texture + GL_ARB_shader_draw_parameters " +
|
|
"(GL 4.3+ with bindless support). Your GPU/driver does not expose these extensions. " +
|
|
"If this is unexpected, please file a bug report with your GPU vendor + driver version.");
|
|
}
|
|
|
|
// --- Shared infra (GameWindow ~1198, ~1211) ---
|
|
string shaderDir = Path.Combine(AppContext.BaseDirectory, "Rendering", "Shaders");
|
|
var lightingUbo = new SceneLightingUboBinding(gl);
|
|
|
|
// --- Mesh shader (GameWindow ~1769-1771) ---
|
|
var meshShader = new Shader(gl,
|
|
Path.Combine(shaderDir, "mesh_modern.vert"),
|
|
Path.Combine(shaderDir, "mesh_modern.frag"));
|
|
|
|
// --- TextureCache (GameWindow ~1774) ---
|
|
var frameFlights = new GpuFrameFlightController(gl);
|
|
// Campaign V slice V4a: the RHI device UI Studio's TextureCache/UiHost
|
|
// now need for their retained-UI texture/pipeline path, constructed
|
|
// the same way HostInputCameraCompositionPhase does for the main
|
|
// GameWindow (V1).
|
|
var gpuDevice = new AcDream.App.Rendering.Gpu.Gl.GlGpuDevice(gl, frameFlights, shaderDir);
|
|
var frameLifetime = new GpuDeviceFrameLifetime(gpuDevice);
|
|
var textureCache = new TextureCache(
|
|
gl,
|
|
gpuDevice,
|
|
dats,
|
|
bindless,
|
|
frameFlights,
|
|
opts.DiagnosticsDirectory);
|
|
|
|
// --- AnimLoader (GameWindow ~1240) ---
|
|
var animLoader = new AcDream.Content.Vfx.RetailAnimationLoader(dats);
|
|
|
|
// --- WbMeshAdapter (GameWindow ~2286-2287) ---
|
|
var wbLogger = NullLogger<Wb.WbMeshAdapter>.Instance;
|
|
var meshAdapter = Wb.WbMeshAdapter.CreateWithLiveDatPreparedAssets(
|
|
gl,
|
|
dats,
|
|
wbLogger,
|
|
frameFlights);
|
|
|
|
// --- SequencerFactory (GameWindow ~2306-2334) ---
|
|
var capturedDats = dats;
|
|
var capturedAnimLoader = animLoader;
|
|
AcDream.Core.Physics.AnimationSequencer SequencerFactory(AcDream.Core.World.WorldEntity e)
|
|
{
|
|
if (capturedDats is not null && capturedAnimLoader is not null)
|
|
{
|
|
var setup = capturedDats.Get<DatReaderWriter.DBObjs.Setup>(e.SourceGfxObjOrSetupId);
|
|
if (setup is not null)
|
|
{
|
|
uint mtableId = (uint)setup.DefaultMotionTable;
|
|
if (mtableId != 0)
|
|
{
|
|
var mtable = capturedDats.Get<DatReaderWriter.DBObjs.MotionTable>(mtableId);
|
|
if (mtable is not null)
|
|
return new AcDream.Core.Physics.AnimationSequencer(
|
|
setup, mtable, capturedAnimLoader);
|
|
}
|
|
// Setup exists but no motion table — no-op sequencer.
|
|
return new AcDream.Core.Physics.AnimationSequencer(
|
|
setup,
|
|
new DatReaderWriter.DBObjs.MotionTable(),
|
|
capturedAnimLoader);
|
|
}
|
|
}
|
|
// Complete fallback: empty setup + empty motion table + null loader.
|
|
return new AcDream.Core.Physics.AnimationSequencer(
|
|
new DatReaderWriter.DBObjs.Setup(),
|
|
new DatReaderWriter.DBObjs.MotionTable(),
|
|
new NullAnimLoader());
|
|
}
|
|
|
|
// --- EntitySpawnAdapter (GameWindow ~2335-2336) ---
|
|
var entitySpawnAdapter = new Wb.EntitySpawnAdapter(
|
|
textureCache, SequencerFactory, meshAdapter);
|
|
|
|
// --- EntityClassificationCache (GameWindow ~217 — field initializer, new()) ---
|
|
var classificationCache = new Wb.EntityClassificationCache();
|
|
|
|
// --- TranslucencyFadeManager (GameWindow — field initializer, new()) ---
|
|
var translucencyFades = new AcDream.Core.Rendering.TranslucencyFadeManager();
|
|
|
|
// --- WbDrawDispatcher (GameWindow ~2377-2381) ---
|
|
var drawDispatcher = new Wb.WbDrawDispatcher(
|
|
gl, meshShader, textureCache, meshAdapter, entitySpawnAdapter,
|
|
bindless, classificationCache, translucencyFades);
|
|
drawDispatcher.AlphaToCoverage = opts.Quality.AlphaToCoverage;
|
|
|
|
// --- Vitals dat font (GameWindow ~1820-1822) ---
|
|
var vitalsDatFont = AcDream.App.UI.UiDatFont.Load(dats, textureCache);
|
|
|
|
// --- Larger retail font (0x40000001, MaxCharHeight=18) for attribute row text.
|
|
// The default font (0x40000000, 16px) renders the row names too small; the 18px
|
|
// variant (confirmed in client_portal.dat 2026-06-26) matches the retail character
|
|
// window list more closely (≈ icon height ≈ 24px target, 18px is best available).
|
|
var largeDatFont = AcDream.App.UI.UiDatFont.Load(dats, textureCache, 0x40000001u);
|
|
|
|
// --- UiHost (GameWindow ~1790); pass null for debugFont (only used as
|
|
// a fallback BitmapFont for the world-space HUD — not needed for the
|
|
// UI Studio, and BitmapFont requires a system font byte array) ---
|
|
var uiHost = new AcDream.App.UI.UiHost(gpuDevice, () => frameLifetime.Current, defaultFont: null);
|
|
|
|
var stack = new RenderStack(
|
|
Gl: gl,
|
|
Dats: dats,
|
|
ShaderDir: shaderDir,
|
|
Bindless: bindless,
|
|
TextureCache: textureCache,
|
|
MeshShader: meshShader,
|
|
MeshAdapter: meshAdapter,
|
|
EntitySpawnAdapter: entitySpawnAdapter,
|
|
DrawDispatcher: drawDispatcher,
|
|
LightingUbo: lightingUbo,
|
|
UiHost: uiHost,
|
|
VitalsDatFont: vitalsDatFont,
|
|
LargeDatFont: largeDatFont)
|
|
{
|
|
FrameFlights = frameFlights,
|
|
GpuDevice = gpuDevice,
|
|
FrameLifetime = frameLifetime,
|
|
};
|
|
|
|
// Pre-seed the font cache with the two already-uploaded atlas instances
|
|
// so ResolveDatFont(0x40000000) and ResolveDatFont(0x40000001) hit the cache
|
|
// rather than re-uploading the same GL texture a second time.
|
|
stack.SeedFontCache();
|
|
|
|
return stack;
|
|
}
|
|
|
|
// NullAnimLoader mirrors GameWindow's private NullAnimLoader (GameWindow ~13327-13330).
|
|
private sealed class NullAnimLoader : AcDream.Core.Physics.IAnimationLoader
|
|
{
|
|
public DatReaderWriter.DBObjs.Animation? LoadAnimation(uint id) => null;
|
|
}
|
|
}
|