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>
This commit is contained in:
parent
ec414d60cd
commit
ceec3bc440
334 changed files with 3660 additions and 3840 deletions
|
|
@ -1,11 +1,7 @@
|
|||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using AcDream.App.Rendering.Wb;
|
||||
using Silk.NET.OpenGL;
|
||||
|
||||
namespace AcDream.App.Rendering;
|
||||
|
||||
|
|
@ -15,36 +11,39 @@ namespace AcDream.App.Rendering;
|
|||
/// <see cref="Begin"/> at the start of a HUD pass, queue geometry via
|
||||
/// <see cref="DrawString"/> / <see cref="DrawRect"/>, then <see cref="Flush"/>.
|
||||
///
|
||||
/// Uses two internal vertex buffers (text and rect) flushed in two draw calls
|
||||
/// to avoid a per-vertex "use texture" flag. Rects are drawn first so text
|
||||
/// sits on top of background panels.
|
||||
/// Campaign V slice V4a: ported onto <see cref="IGpuDevice"/>. One pipeline
|
||||
/// (blend, depth-disable, and the MSAA/alpha-to-coverage isolation the prior
|
||||
/// <c>TextRenderGlStateScope</c> restored by hand are now baked into the
|
||||
/// pipeline description) and one pass per <see cref="Flush"/>, with each
|
||||
/// bucket/segment getting its own per-frame ring allocation instead of a
|
||||
/// shared, growable VBO. Rects are drawn first so text sits on top of
|
||||
/// background panels — bucket ORDER is unchanged, only how each bucket
|
||||
/// reaches the GPU.
|
||||
/// </summary>
|
||||
public sealed unsafe class TextRenderer : IDisposable
|
||||
internal sealed class TextRenderer : IDisposable
|
||||
{
|
||||
private const int FloatsPerVertex = 8; // pos(2) + uv(2) + color(4)
|
||||
private const int VertexStrideBytes = FloatsPerVertex * sizeof(float);
|
||||
|
||||
private readonly GL _gl;
|
||||
private readonly ITextRenderGlStateApi _glState;
|
||||
private readonly Shader _shader;
|
||||
private readonly ResourceCleanupGroup _resources;
|
||||
private uint _vao;
|
||||
private uint _vbo;
|
||||
private readonly uint _whiteTex; // 1×1 white, for solid fills routed through the sprite bucket
|
||||
private int _vboCapacityBytes;
|
||||
private static readonly GpuVertexLayout VertexLayout = new(
|
||||
StrideBytes: VertexStrideBytes,
|
||||
[
|
||||
new GpuVertexAttribute(0, GpuVertexFormat.Float2, 0),
|
||||
new GpuVertexAttribute(1, GpuVertexFormat.Float2, 8),
|
||||
new GpuVertexAttribute(2, GpuVertexFormat.Float4, 16),
|
||||
]);
|
||||
|
||||
private sealed class FrameBufferSet
|
||||
{
|
||||
public uint Vao;
|
||||
public uint Vbo;
|
||||
public int CapacityBytes;
|
||||
public int UsedBytes;
|
||||
}
|
||||
// uUseTexture values the ui_text.frag shader branches on (reusing the
|
||||
// shared push-constant block's uRenderPass scalar — see the shader's own
|
||||
// comment for why there is no dedicated field).
|
||||
private const int UseTextureNone = 0;
|
||||
private const int UseTextureFont = 1;
|
||||
private const int UseTextureSprite = 2;
|
||||
|
||||
private readonly FrameBufferSet[] _frameBuffers;
|
||||
private FrameBufferSet? _activeFrameBuffer;
|
||||
private readonly IGpuDevice _device;
|
||||
private readonly IGpuPipeline _pipeline;
|
||||
|
||||
internal long DynamicBufferCapacityBytes =>
|
||||
_frameBuffers.Sum(set => (long)set.CapacityBytes);
|
||||
private sealed class SpriteSeg { public GpuTextureSlot TextureSlot; public readonly List<float> Verts = new(256); }
|
||||
|
||||
private readonly List<float> _textBuf = new(8192);
|
||||
private readonly List<float> _rectBuf = new(1024);
|
||||
|
|
@ -53,16 +52,14 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
// Drawing segments in submission order preserves painter z-order for
|
||||
// sprite-on-sprite UI. (The old per-texture dictionary drew a REUSED texture
|
||||
// at its FIRST-insertion point, so later bar sprites covered glyphs emitted
|
||||
// earlier via the shared dat-font atlas — the stamina/mana numbers vanished.)
|
||||
private sealed class SpriteSeg { public uint Texture; public readonly List<float> Verts = new(256); }
|
||||
|
||||
// earlier via the shared dat-font atlas — the stamina/mana numbers vanished.)
|
||||
private readonly List<SpriteSeg> _spriteSegs = new();
|
||||
private int _segUsed;
|
||||
private int _textVerts;
|
||||
private int _rectVerts;
|
||||
private Vector2 _screenSize;
|
||||
|
||||
// Overlay layer — a parallel set of buckets drawn AFTER the normal sprite/rect/text
|
||||
// Overlay layer — a parallel set of buckets drawn AFTER the normal sprite/rect/text
|
||||
// buckets, so open popups/menus composite on top of EVERYTHING, including translucent
|
||||
// rect panel backgrounds (which otherwise always win because rects flush after
|
||||
// sprites). Routed by OverlayMode; the UI root sets it for the popup traversal.
|
||||
|
|
@ -77,142 +74,38 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
/// of all normal-layer geometry). Set by the UI root around the popup/overlay pass.</summary>
|
||||
public bool OverlayMode { get; set; }
|
||||
|
||||
public TextRenderer(GL gl, string shaderDir)
|
||||
{
|
||||
_gl = gl;
|
||||
_glState = new SilkTextRenderGlStateApi(gl);
|
||||
var resources = new ResourceCleanupGroup();
|
||||
Shader? shader = null;
|
||||
var frameBuffers = new FrameBufferSet[3];
|
||||
uint whiteTexture = 0;
|
||||
try
|
||||
{
|
||||
shader = new Shader(gl,
|
||||
Path.Combine(shaderDir, "ui_text.vert"),
|
||||
Path.Combine(shaderDir, "ui_text.frag"));
|
||||
resources.Add("text shader", shader.Dispose);
|
||||
|
||||
for (int i = 0; i < frameBuffers.Length; i++)
|
||||
frameBuffers[i] = CreateFrameBufferSet(resources);
|
||||
|
||||
// 1×1 white texture so DrawFill can route solid-colour quads through the SPRITE
|
||||
// bucket (the shader multiplies texel×color → white×color = color). Lets a panel
|
||||
// background draw UNDER its text in painter order, which DrawRect's separate
|
||||
// bucket cannot (it always composites after all sprites).
|
||||
whiteTexture = GlResourceCommand.CreateTexture(
|
||||
_gl,
|
||||
"TextRenderer white texture");
|
||||
uint ownedWhiteTexture = whiteTexture;
|
||||
resources.Add(
|
||||
"white texture",
|
||||
() => GlResourceCommand.DeleteTexture(
|
||||
_gl,
|
||||
ownedWhiteTexture,
|
||||
$"delete TextRenderer white texture {ownedWhiteTexture}"));
|
||||
GlResourceCommand.Execute(
|
||||
_gl,
|
||||
"initialize TextRenderer white texture",
|
||||
() =>
|
||||
{
|
||||
_gl.BindTexture(TextureTarget.Texture2D, whiteTexture);
|
||||
Span<byte> whitePixel = stackalloc byte[] { 255, 255, 255, 255 };
|
||||
fixed (byte* wp = whitePixel)
|
||||
_gl.TexImage2D(TextureTarget.Texture2D, 0, (int)InternalFormat.Rgba8, 1, 1, 0,
|
||||
PixelFormat.Rgba, PixelType.UnsignedByte, wp);
|
||||
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
|
||||
_gl.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Nearest);
|
||||
_gl.BindTexture(TextureTarget.Texture2D, 0);
|
||||
});
|
||||
}
|
||||
catch (Exception constructionFailure)
|
||||
{
|
||||
try
|
||||
{
|
||||
resources.RetryCleanup();
|
||||
}
|
||||
catch (Exception cleanupFailure)
|
||||
{
|
||||
throw new GlResourceConstructionException(
|
||||
"TextRenderer construction failed and its published GL resources did not cleanly roll back.",
|
||||
resources,
|
||||
[constructionFailure, cleanupFailure]);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
_resources = resources;
|
||||
_shader = shader;
|
||||
_frameBuffers = frameBuffers;
|
||||
_whiteTex = whiteTexture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Selects the GPU-fenced frame slot and resets its append cursor. Every
|
||||
/// UI segment rendered during the frame receives a distinct byte range;
|
||||
/// later text or sprite batches cannot overwrite an earlier in-flight draw.
|
||||
/// No longer meaningful post-V4a: per-frame vertex data comes from the
|
||||
/// device's shared ring rather than a VBO this class owns. Kept (returning
|
||||
/// 0) so <c>RenderFrameDiagnosticSources</c>'s telemetry read still compiles;
|
||||
/// the dynamic-buffer dimension it reported is now a device-wide, not a
|
||||
/// per-renderer, concern.
|
||||
/// </summary>
|
||||
public void BeginFrame(int frameSlot)
|
||||
internal long DynamicBufferCapacityBytes => 0;
|
||||
|
||||
public TextRenderer(IGpuDevice device)
|
||||
{
|
||||
if ((uint)frameSlot >= (uint)_frameBuffers.Length)
|
||||
throw new ArgumentOutOfRangeException(nameof(frameSlot));
|
||||
|
||||
FrameBufferSet set = _frameBuffers[frameSlot];
|
||||
set.UsedBytes = 0;
|
||||
_activeFrameBuffer = set;
|
||||
_vao = set.Vao;
|
||||
_vbo = set.Vbo;
|
||||
_vboCapacityBytes = set.CapacityBytes;
|
||||
}
|
||||
|
||||
private FrameBufferSet CreateFrameBufferSet(ResourceCleanupGroup resources)
|
||||
{
|
||||
uint vao = TrackedGlResource.CreateVertexArray(
|
||||
_gl,
|
||||
"TextRenderer frame VAO creation");
|
||||
RetryableGpuResourceRelease vaoRelease =
|
||||
TrackedGlResource.CreateRetryableVertexArrayDeletion(
|
||||
_gl,
|
||||
vao,
|
||||
"TextRenderer frame VAO disposal");
|
||||
resources.Add("frame VAO", vaoRelease.Run);
|
||||
var set = new FrameBufferSet { Vao = vao };
|
||||
|
||||
uint vbo = TrackedGlResource.CreateBuffer(
|
||||
_gl,
|
||||
"TextRenderer frame VBO creation");
|
||||
set.Vbo = vbo;
|
||||
RetryableGpuResourceRelease? vboRelease = null;
|
||||
resources.Add(
|
||||
"frame VBO",
|
||||
() =>
|
||||
{
|
||||
vboRelease ??= TrackedGlResource.CreateRetryableBufferDeletion(
|
||||
_gl,
|
||||
vbo,
|
||||
set.CapacityBytes,
|
||||
"TextRenderer frame VBO disposal");
|
||||
vboRelease.Run();
|
||||
});
|
||||
|
||||
GlResourceCommand.Execute(
|
||||
_gl,
|
||||
"initialize TextRenderer frame VAO and VBO",
|
||||
() =>
|
||||
{
|
||||
_gl.BindVertexArray(set.Vao);
|
||||
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, set.Vbo);
|
||||
uint stride = FloatsPerVertex * sizeof(float);
|
||||
_gl.EnableVertexAttribArray(0);
|
||||
_gl.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, stride, (void*)0);
|
||||
_gl.EnableVertexAttribArray(1);
|
||||
_gl.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, stride, (void*)(2 * sizeof(float)));
|
||||
_gl.EnableVertexAttribArray(2);
|
||||
_gl.VertexAttribPointer(2, 4, VertexAttribPointerType.Float, false, stride, (void*)(4 * sizeof(float)));
|
||||
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, 0);
|
||||
_gl.BindVertexArray(0);
|
||||
});
|
||||
return set;
|
||||
_device = device ?? throw new ArgumentNullException(nameof(device));
|
||||
_pipeline = _device.CreatePipeline(new GpuPipelineDescription
|
||||
{
|
||||
Name = "ui-text",
|
||||
Shaders = new GpuShaderSet("ui_text"),
|
||||
VertexLayout = VertexLayout,
|
||||
Topology = GpuPrimitiveTopology.TriangleList,
|
||||
Blend = GpuBlendMode.StraightAlpha,
|
||||
// The retained UI is a self-contained 2-D pass: depth is
|
||||
// irrelevant (feedback_render_self_contained_gl_state) and the
|
||||
// world pass's alpha-to-coverage/multisample state must not leak
|
||||
// in — SampleCount=1 drives the GL backend's GL_MULTISAMPLE
|
||||
// toggle off when this pipeline binds (GlGpuDevice.ApplyRenderState),
|
||||
// which is what the deleted TextRenderGlStateScope used to restore
|
||||
// by hand around every Flush.
|
||||
Depth = GpuDepthState.Disabled,
|
||||
Cull = GpuCullMode.None,
|
||||
AlphaToCoverage = false,
|
||||
ColorWrite = true,
|
||||
SampleCount = 1,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Begin a HUD pass. Call once per frame before any Draw* calls.</summary>
|
||||
|
|
@ -241,11 +134,11 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
|
||||
/// <summary>Draw a solid-colour quad through the SPRITE bucket (and the overlay layer
|
||||
/// when active), so it composites in painter order with sprites + dat-font text. Use
|
||||
/// this — not <see cref="DrawRect"/> — for a panel BACKGROUND that text draws on top of:
|
||||
/// this — not <see cref="DrawRect"/> — for a panel BACKGROUND that text draws on top of:
|
||||
/// DrawRect's bucket always flushes after all sprites, so a rect background would cover
|
||||
/// the text instead.</summary>
|
||||
public void DrawFill(float x, float y, float w, float h, Vector4 color)
|
||||
=> DrawSprite(_whiteTex, x, y, w, h, 0f, 0f, 1f, 1f, color);
|
||||
=> DrawSprite(_device.DefaultTextureSlot, x, y, w, h, 0f, 0f, 1f, 1f, color);
|
||||
|
||||
/// <summary>Draw a 1-pixel-thick outline rect.</summary>
|
||||
public void DrawRectOutline(float x, float y, float w, float h, Vector4 color, float thickness = 1f)
|
||||
|
|
@ -313,7 +206,7 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
}
|
||||
if (!font.TryGetGlyph(c, out var g))
|
||||
{
|
||||
// Unknown glyph — skip its advance width if '?' exists.
|
||||
// Unknown glyph — skip its advance width if '?' exists.
|
||||
if (font.TryGetGlyph('?', out var q))
|
||||
cursorX += q.Advance;
|
||||
continue;
|
||||
|
|
@ -344,9 +237,9 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
/// <summary>
|
||||
/// Draw a textured sprite quad in screen pixel space with an explicit
|
||||
/// source-UV rectangle (for 9-slice / atlas sub-regions). Batched per
|
||||
/// GL texture handle; flushed with uUseTexture=2 (RGBA modulate).
|
||||
/// texture-table slot, flushed with uUseTexture=2 (RGBA modulate).
|
||||
/// </summary>
|
||||
public void DrawSprite(uint texture, float x, float y, float w, float h,
|
||||
public void DrawSprite(GpuTextureSlot texture, float x, float y, float w, float h,
|
||||
float u0, float v0, float u1, float v1, Vector4 tint)
|
||||
{
|
||||
SpriteSeg seg = OverlayMode
|
||||
|
|
@ -358,18 +251,18 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
/// <summary>Pick the sprite segment for <paramref name="texture"/>: extend the current
|
||||
/// same-texture run, else reuse a pooled segment, else allocate. Submission order is
|
||||
/// preserved (painter z-order for sprite-on-sprite UI).</summary>
|
||||
private static SpriteSeg NextSpriteSeg(List<SpriteSeg> segs, ref int used, uint texture)
|
||||
private static SpriteSeg NextSpriteSeg(List<SpriteSeg> segs, ref int used, GpuTextureSlot texture)
|
||||
{
|
||||
if (used > 0 && segs[used - 1].Texture == texture)
|
||||
if (used > 0 && segs[used - 1].TextureSlot == texture)
|
||||
return segs[used - 1];
|
||||
if (used < segs.Count)
|
||||
{
|
||||
var s = segs[used++];
|
||||
s.Texture = texture;
|
||||
s.TextureSlot = texture;
|
||||
s.Verts.Clear();
|
||||
return s;
|
||||
}
|
||||
var ns = new SpriteSeg { Texture = texture };
|
||||
var ns = new SpriteSeg { TextureSlot = texture };
|
||||
segs.Add(ns);
|
||||
used++;
|
||||
return ns;
|
||||
|
|
@ -381,10 +274,10 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
{
|
||||
// Two triangles (6 verts). CCW in pixel space is clockwise in NDC
|
||||
// because the vertex shader flips Y, so OpenGL's default front-face
|
||||
// is GL_CCW — we rely on cull-face being disabled during HUD pass.
|
||||
// (x, y) ─ (x+w, y)
|
||||
// │ │
|
||||
// (x, y+h) ─ (x+w, y+h)
|
||||
// is GL_CCW — we rely on cull-face being disabled during HUD pass.
|
||||
// (x, y) ─ (x+w, y)
|
||||
// │ │
|
||||
// (x, y+h) ─ (x+w, y+h)
|
||||
//
|
||||
// Triangle 1: (x,y) (x+w,y+h) (x+w,y)
|
||||
// Triangle 2: (x,y) (x,y+h) (x+w,y+h)
|
||||
|
|
@ -402,131 +295,105 @@ public sealed unsafe class TextRenderer : IDisposable
|
|||
V(x + w, y + h, u1, v1);
|
||||
}
|
||||
|
||||
/// <summary>Upload + draw accumulated rects + text. font may be null if only DrawRect was used.</summary>
|
||||
public void Flush(BitmapFont? font)
|
||||
/// <summary>Upload + draw accumulated rects + text against the current frame. font may
|
||||
/// be null if only DrawRect was used.</summary>
|
||||
public void Flush(BitmapFont? font, IGpuFrame frame)
|
||||
{
|
||||
bool anyNormal = _segUsed > 0 || _textVerts > 0 || _rectVerts > 0;
|
||||
bool anyOverlay = _overlaySegUsed > 0 || _overlayTextVerts > 0 || _overlayRectVerts > 0;
|
||||
if (!anyNormal && !anyOverlay) return;
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
|
||||
// Retained UI is a private render pass: an upload or draw failure must
|
||||
// not leak its depth/cull/blend/MSAA state into a later recoverable
|
||||
// frame. The focused scope restores from Flush's generated finally,
|
||||
// including when either DrawLayer call throws.
|
||||
using var stateScope = new TextRenderGlStateScope(_glState);
|
||||
using IGpuPassEncoder pass = frame.BeginPass(new GpuPassDescription
|
||||
{
|
||||
Name = "ui-text",
|
||||
// GL's BeginPass deliberately does not touch viewport/scissor for
|
||||
// a Target:null pass, and Load/Store against the backbuffer
|
||||
// reproduces exactly what this pass did before the RHI existed —
|
||||
// the frame spine still owns clears until slice V4h.
|
||||
Color = new GpuColorAttachment(
|
||||
Target: null,
|
||||
Load: GpuLoadOp.Load,
|
||||
Store: GpuStoreOp.Store,
|
||||
ClearColor: default),
|
||||
Depth = null,
|
||||
SampleCount = 1,
|
||||
});
|
||||
pass.BindPipeline(_pipeline);
|
||||
|
||||
_shader.Use();
|
||||
_shader.SetVec2("uScreenSize", _screenSize);
|
||||
GpuPushConstants baseConstants = GpuPushConstants.Default;
|
||||
baseConstants.ParamA = _screenSize.X;
|
||||
baseConstants.ParamB = _screenSize.Y;
|
||||
|
||||
_gl.BindVertexArray(_vao);
|
||||
_gl.BindBuffer(BufferTargetARB.ArrayBuffer, _vbo);
|
||||
|
||||
// Establish the self-contained UI pass state.
|
||||
// The world pass leaves alpha-to-coverage + multisample enabled (WbDrawDispatcher,
|
||||
// QualitySettings MSAA). If they bleed into the UI pass, each glyph's soft alpha
|
||||
// EDGE is converted to dithered MSAA coverage instead of a clean alpha blend —
|
||||
// the "text not sharp / fuzzy" artifact. The UI composites with straight alpha
|
||||
// blending and must own this state (feedback_render_self_contained_gl_state).
|
||||
_gl.Disable(EnableCap.SampleAlphaToCoverage);
|
||||
_gl.Disable(EnableCap.Multisample);
|
||||
_gl.Disable(EnableCap.DepthTest);
|
||||
_gl.Disable(EnableCap.CullFace);
|
||||
_gl.DepthMask(false);
|
||||
_gl.Enable(EnableCap.Blend);
|
||||
_gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
|
||||
|
||||
// LAYERED compositing for the UI (background → fill → text):
|
||||
// 1. RGBA dat sprites — window chrome / panel backgrounds (behind)
|
||||
// 2. Untextured rects — widget fills (e.g. vital bars) on the chrome
|
||||
// 3. Text glyphs — on top
|
||||
// LAYERED compositing for the UI (background → fill → text):
|
||||
// 1. RGBA dat sprites — window chrome / panel backgrounds (behind)
|
||||
// 2. Untextured rects — widget fills (e.g. vital bars) on the chrome
|
||||
// 3. Text glyphs — on top
|
||||
// Bucket 1 (sprites) draws in SUBMISSION (painter) order via _spriteSegs,
|
||||
// so sprite-on-sprite z is preserved. Buckets 2 (rects) + 3 (debug text)
|
||||
// composite on top, in that order. The OVERLAY layer repeats all three
|
||||
// AFTER the normal layer, so open popups beat even the rect backgrounds.
|
||||
DrawLayer(_spriteSegs, _segUsed, _rectBuf, _rectVerts, _textBuf, _textVerts, font);
|
||||
DrawLayer(_overlaySpriteSegs, _overlaySegUsed, _overlayRectBuf, _overlayRectVerts, _overlayTextBuf, _overlayTextVerts, font);
|
||||
|
||||
DrawLayer(pass, frame, in baseConstants, _spriteSegs, _segUsed, _rectBuf, _rectVerts, _textBuf, _textVerts, font);
|
||||
DrawLayer(pass, frame, in baseConstants, _overlaySpriteSegs, _overlaySegUsed, _overlayRectBuf, _overlayRectVerts, _overlayTextBuf, _overlayTextVerts, font);
|
||||
}
|
||||
|
||||
/// <summary>Draw one compositing layer: sprites (submission order, one call per
|
||||
/// texture) → untextured rects → debug-font text. Shared by the normal and overlay
|
||||
/// layers; GL state + shader are set up by <see cref="Flush"/>.</summary>
|
||||
/// <summary>Draw one compositing layer: sprites (submission order, one draw per
|
||||
/// segment) → untextured rects → debug-font text. Shared by the normal and overlay
|
||||
/// layers; pipeline + pass are already bound by <see cref="Flush"/>.</summary>
|
||||
private void DrawLayer(
|
||||
IGpuPassEncoder pass,
|
||||
IGpuFrame frame,
|
||||
in GpuPushConstants baseConstants,
|
||||
List<SpriteSeg> spriteSegs, int segUsed,
|
||||
List<float> rectBuf, int rectVerts,
|
||||
List<float> textBuf, int textVerts, BitmapFont? font)
|
||||
{
|
||||
// 1. RGBA dat sprites — one draw call per distinct GL texture.
|
||||
if (segUsed > 0)
|
||||
// 1. RGBA dat sprites — one draw per distinct texture-table slot.
|
||||
for (int i = 0; i < segUsed; i++)
|
||||
{
|
||||
_shader.SetInt("uUseTexture", 2);
|
||||
_gl.ActiveTexture(TextureUnit.Texture0);
|
||||
_shader.SetInt("uTex", 0);
|
||||
for (int i = 0; i < segUsed; i++)
|
||||
{
|
||||
var seg = spriteSegs[i];
|
||||
if (seg.Verts.Count == 0) continue;
|
||||
_gl.BindTexture(TextureTarget.Texture2D, seg.Texture);
|
||||
int firstVertex = UploadBuffer(seg.Verts);
|
||||
_gl.DrawArrays(PrimitiveType.Triangles, firstVertex, (uint)(seg.Verts.Count / FloatsPerVertex));
|
||||
}
|
||||
SpriteSeg seg = spriteSegs[i];
|
||||
if (seg.Verts.Count == 0) continue;
|
||||
DrawBucket(pass, frame, in baseConstants, seg.Verts, UseTextureSprite, seg.TextureSlot);
|
||||
}
|
||||
|
||||
// 2. Untextured rects — widget fills on top of the chrome.
|
||||
// 2. Untextured rects — widget fills on top of the chrome.
|
||||
if (rectVerts > 0)
|
||||
{
|
||||
_shader.SetInt("uUseTexture", 0);
|
||||
int firstVertex = UploadBuffer(rectBuf);
|
||||
_gl.DrawArrays(PrimitiveType.Triangles, firstVertex, (uint)rectVerts);
|
||||
}
|
||||
DrawBucket(pass, frame, in baseConstants, rectBuf, UseTextureNone, GpuTextureSlot.Unassigned);
|
||||
|
||||
// 3. Textured debug-font text glyphs on top.
|
||||
if (textVerts > 0 && font is not null)
|
||||
{
|
||||
_shader.SetInt("uUseTexture", 1);
|
||||
_gl.ActiveTexture(TextureUnit.Texture0);
|
||||
_gl.BindTexture(TextureTarget.Texture2D, font.TextureId);
|
||||
_shader.SetInt("uTex", 0);
|
||||
int firstVertex = UploadBuffer(textBuf);
|
||||
_gl.DrawArrays(PrimitiveType.Triangles, firstVertex, (uint)textVerts);
|
||||
}
|
||||
DrawBucket(pass, frame, in baseConstants, textBuf, UseTextureFont, font.TextureId);
|
||||
}
|
||||
|
||||
private int UploadBuffer(List<float> buf)
|
||||
private static void DrawBucket(
|
||||
IGpuPassEncoder pass,
|
||||
IGpuFrame frame,
|
||||
in GpuPushConstants baseConstants,
|
||||
List<float> verts,
|
||||
int useTexture,
|
||||
GpuTextureSlot textureSlot)
|
||||
{
|
||||
int bytes = buf.Count * sizeof(float);
|
||||
if (bytes == 0) return 0;
|
||||
FrameBufferSet set = _activeFrameBuffer
|
||||
?? throw new InvalidOperationException("BeginFrame must be called before rendering text.");
|
||||
int byteOffset = set.UsedBytes;
|
||||
int requiredBytes = checked(byteOffset + bytes);
|
||||
int byteCount = verts.Count * sizeof(float);
|
||||
if (byteCount == 0) return;
|
||||
|
||||
if (requiredBytes > _vboCapacityBytes)
|
||||
{
|
||||
int newCapacity = DynamicBufferCapacity.Grow(
|
||||
_vboCapacityBytes,
|
||||
requiredBytes);
|
||||
TrackedGlResource.AllocateBufferStorage(
|
||||
_gl,
|
||||
GLEnum.ArrayBuffer,
|
||||
_vbo,
|
||||
_vboCapacityBytes,
|
||||
newCapacity,
|
||||
GLEnum.DynamicDraw,
|
||||
"TextRenderer frame VBO growth");
|
||||
_vboCapacityBytes = newCapacity;
|
||||
}
|
||||
GpuRingAllocation allocation = frame.AllocateRing(byteCount, GpuRingUsage.Vertex);
|
||||
CollectionsMarshal.AsSpan(verts).CopyTo(allocation.AsSpan<float>());
|
||||
|
||||
fixed (float* p = CollectionsMarshal.AsSpan(buf))
|
||||
_gl.BufferSubData(BufferTargetARB.ArrayBuffer, (nint)byteOffset, (nuint)bytes, p);
|
||||
GpuPushConstants constants = baseConstants;
|
||||
constants.RenderPass = useTexture;
|
||||
// Unassigned (the untextured-rect bucket) never reaches the shader as
|
||||
// a slot index — uUseTexture==0 skips the sample entirely — but a
|
||||
// defined value is still written so no stale slot lingers in the
|
||||
// uniform between draws.
|
||||
constants.TextureIndexA = textureSlot.IsAssigned ? textureSlot.Index : 0u;
|
||||
|
||||
set.UsedBytes = requiredBytes;
|
||||
set.CapacityBytes = _vboCapacityBytes;
|
||||
return byteOffset / (FloatsPerVertex * sizeof(float));
|
||||
pass.BindVertexBuffer(allocation.Buffer, allocation.OffsetBytes);
|
||||
pass.SetPushConstants(in constants);
|
||||
pass.Draw((uint)(verts.Count / FloatsPerVertex), instanceCount: 1, firstVertex: 0, firstInstance: 0);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_resources.RetryCleanup();
|
||||
_pipeline.Dispose();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue