acdream/src/AcDream.App/Rendering/BitmapFont.cs
Erik f6f58a12db feat(render): put the retained UI and debug lines on both backends
Campaign V slice V6d, commit 2 of 3. TextRenderer and DebugLineRenderer were the only two renderers speaking the RHI, and both refused any device that was not a GlGpuDevice. They now refuse nothing: this is the first production rendering acdream can do on Vulkan.

Three things had to go.

The loose uniforms. debug_line declared uView and uProjection separately and DebugLineRenderer set them straight against the compiled GL program, because the pinned push-constant block carries one combined matrix and IGpuPassEncoder has no verb for arbitrary named uniforms. That was never portable — Vulkan has no default uniform block at all — so the shader converged on uViewProjection and Flush multiplies on the CPU. System.Numerics is row-vector convention while GLSL reads the floats column-major, which transposes, so the CPU equivalent of the old per-vertex uProjection * uView is view * projection. The product now rounds once per frame rather than once per vertex; these lines only draw when collision wireframes are switched on, so the offline gate sees nothing of it. ui_text's uScreenSize became the block's two spare scalars, uParamA and uParamB, with the same two divisions and the same NDC mapping around them.

The sampling mode. uUseTexture selected between font coverage, RGBA modulate and flat colour, and no field of the 96-byte block means that. It did not need one: which of the two texture-table slots is assigned IS the mode. uTextureIndexB assigned means a single-channel coverage source, uTextureIndexA assigned means an RGBA colour source, neither assigned means the vertex colour alone. GpuTextureSlot.Unassigned is already a loud sentinel for exactly this kind of question, and both branches guard so it never reaches a sampler. That also retired the 1x1 white fill texture: DrawFill routed solid quads through the sprite bucket relying on white times colour, and the untextured branch produces the same value with no texture at all. Multiplying by 1.0 changes no bits, and the gate agrees.

The texture binding. The classic glActiveTexture/glBindTexture path survived V4a because DrawSprite takes an arbitrary texture from sixty-odd widget call sites. But TextureCache had already registered every one of those into the device's table — the classic path was consuming the raw GL name that registration also produced. The UI's currency is now UiTextureTableHandle, a one-based table index whose zero is the same "no texture" every widget already guards on; a raw slot index would have turned all of those guards into silent false negatives, since slot 0 is perfectly valid. One-based rather than the slot itself because GpuTextureSlot is internal to the pinned contract while UiRenderContext.DrawSprite, TextureCache.GetOrUploadRenderSurface and a dozen widget properties are public, and neither publishing a contract type nor converting the retained UI to internal belongs in this slice.

Two consequences worth stating. The two backends disagree about what a 2-D table entry is — GL reconstructs a sampler2D from the bindless handle, Vulkan reads layer 0 of its sampler2DArray descriptor array — and ACDREAM_SAMPLE_2D is the one place that lives. Keeping GL on sampler2D is what leaves the UI's textures exactly as they are, including the paperdoll/appraisal FBO colour texture, which is an externally-owned GL_TEXTURE_2D from the §7.1 transitional seam and cannot become an array before V4g. On the Vulkan side, sampled views are now always layered, which also removes a latent invalid usage V6c shipped: it registered a Type2D offscreen view into a descriptor array whose element type is sampler2DArray.

And one real fix. Sampling through the table means a bound sampler object overrides the texture's own parameters. Nearest-requested UI art used to get its point filtering from a glTexParameter applied before the bindless handle went resident, so registering it with the stock WorldRepeat sampler would have made every retail icon and dat-font glyph silently bilinear. Those now register with a nearest-and-repeat sampler.

Supporting moves: GlGpuDevice.CreatePipeline splices common.glsl the same way Shader does, since an RHI shader that reads the table needs the table declared; GlGpuPassEncoder binds the device's table with the pipeline, which is the GL analogue of Vulkan binding descriptor set 2 per draw, and has to be per-bind because every raw-GL world renderer puts its own privately-numbered table at that binding; and the encoder derives GL_MULTISAMPLE from the pass's SampleCount, which is where the retained UI's hand-rolled glDisable belonged all along. TextRenderGlStateScope is deleted — the encoder's ambient capture restored a strict superset of it — and its failure-safety test follows the guarantee to GlAmbientCapabilityState, which gains a fakeable seam and, with it, the multisample-dimension coverage #249 recorded as missing.

App tests 4,057 passed / 3 skipped, unchanged from commit 1. Offline pixel gate against 871c406b: differing fraction 2.31e-05, 13 pixels of 563,200 compared — below the documented 15-23 pixel same-commit noise band, on a change that redraws every pixel of the retained UI through a different sampling path. The capture was inspected: vitals, spell bar, radar, toolbar icons and slot digits, chat window and Send button all present and correctly placed. Both new .spv pairs compile; the manifest records ui_text and debug_line as Vulkan-ready, leaving six pairs blocked on the world-renderer slices.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 08:51:32 +02:00

213 lines
7.7 KiB
C#

using System;
using System.IO;
using AcDream.App.Rendering.Gpu;
using StbTrueTypeSharp;
namespace AcDream.App.Rendering;
/// <summary>
/// A pixel-font atlas rasterized from a TTF at load time using stb_truetype.
/// Glyphs are packed into a single-channel (R8) atlas. Call
/// <see cref="TryGetGlyph"/> to resolve an ASCII codepoint to UV + metrics.
///
/// Campaign V slice V4a: the atlas is created and uploaded through
/// <see cref="IGpuDevice.CreateTexture"/> instead of raw GL, and registered
/// into the device's texture table.
///
/// Campaign V slice V6d: <see cref="TextureId"/> is that registration's
/// <see cref="UiTextureTableHandle"/> rather than the raw GL name it used to
/// be. Its only consumer is <see cref="TextRenderer"/>, which now samples the
/// table instead of binding a texture unit, so the GL name has no remaining
/// reader — and on Vulkan there is no GL name to have.
///
/// Only printable ASCII (32..127) is supported for the debug overlay.
/// </summary>
public sealed unsafe class BitmapFont : IDisposable
{
public readonly struct Glyph
{
public readonly float UvMinX;
public readonly float UvMinY;
public readonly float UvMaxX;
public readonly float UvMaxY;
public readonly float OffsetX; // from cursor to glyph quad top-left
public readonly float OffsetY;
public readonly float Width; // pixels
public readonly float Height;
public readonly float Advance;
public Glyph(float umn, float vmn, float umx, float vmx,
float ox, float oy, float w, float h, float adv)
{
UvMinX = umn; UvMinY = vmn; UvMaxX = umx; UvMaxY = vmx;
OffsetX = ox; OffsetY = oy; Width = w; Height = h; Advance = adv;
}
}
private readonly Glyph[] _glyphs;
private readonly int _firstChar;
private readonly int _numChars;
private readonly IGpuTexture _texture;
/// <summary>
/// The atlas's <see cref="UiTextureTableHandle"/> — a one-based index into
/// the device's global texture table, not a GL texture name. The name is
/// unchanged so that the public shape of this class did not move for a
/// change of currency its only consumer makes invisible.
/// </summary>
public uint TextureId { get; }
public float PixelHeight { get; }
public float LineHeight { get; }
public float Ascent { get; }
public int AtlasWidth { get; }
public int AtlasHeight { get; }
// internal, not public: IGpuDevice is an internal type (the pinned RHI
// contract). BitmapFont stays public — only construction is restricted —
// so existing public members that hold or return a BitmapFont need no
// visibility change of their own.
internal BitmapFont(IGpuDevice device, byte[] ttfBytes, float pixelHeight,
int atlasSize = 512, int firstChar = 32, int numChars = 96)
{
ArgumentNullException.ThrowIfNull(device);
PixelHeight = pixelHeight;
AtlasWidth = atlasSize;
AtlasHeight = atlasSize;
_firstChar = firstChar;
_numChars = numChars;
// Bake the glyph bitmap via stbtt_BakeFontBitmap.
var bakedChars = new StbTrueType.stbtt_bakedchar[numChars];
var pixels = new byte[AtlasWidth * AtlasHeight];
bool ok = StbTrueType.stbtt_BakeFontBitmap(
ttfBytes, 0, pixelHeight,
pixels, AtlasWidth, AtlasHeight,
firstChar, numChars, bakedChars);
if (!ok)
throw new InvalidOperationException(
$"stbtt_BakeFontBitmap failed: atlas {atlasSize}x{atlasSize} " +
$"too small for pixelHeight={pixelHeight}");
// Extract vertical metrics for line spacing.
using var info = StbTrueType.CreateFont(ttfBytes, 0)
?? throw new InvalidOperationException("stbtt_InitFont failed");
float scale = StbTrueType.stbtt_ScaleForPixelHeight(info, pixelHeight);
int ascent, descent, lineGap;
StbTrueType.stbtt_GetFontVMetrics(info, &ascent, &descent, &lineGap);
Ascent = ascent * scale;
LineHeight = (ascent - descent + lineGap) * scale;
// Convert baked-char records to our Glyph struct.
_glyphs = new Glyph[numChars];
for (int i = 0; i < numChars; i++)
{
var bc = bakedChars[i];
float w = bc.x1 - bc.x0;
float h = bc.y1 - bc.y0;
_glyphs[i] = new Glyph(
umn: bc.x0 / (float)AtlasWidth,
vmn: bc.y0 / (float)AtlasHeight,
umx: bc.x1 / (float)AtlasWidth,
vmx: bc.y1 / (float)AtlasHeight,
ox: bc.xoff,
oy: bc.yoff,
w: w, h: h,
adv: bc.xadvance);
}
// Upload atlas as a single-channel texture (R8) through the device.
IGpuTexture texture = device.CreateTexture(new GpuTextureDescription(
"bitmap-font-atlas",
GpuTextureKind.Texture2D,
GpuTextureFormat.R8Unorm,
Width: AtlasWidth,
Height: AtlasHeight,
LayerCount: 1,
MipLevelCount: 1));
GpuTextureSlot slot;
try
{
fixed (byte* ptr = pixels)
texture.Upload(0, 0, new ReadOnlySpan<byte>(ptr, AtlasWidth * AtlasHeight));
// Clamped, so a glyph's edge texel cannot bleed in from the opposite
// side of the atlas. Retail's dat font glyph UVs never leave their
// own tight sub-rect, but the sampler states it rather than relying
// on that. Slice V6d: this sampler is now the only thing that
// decides how the atlas is filtered — the raw glTexParameter pass
// that used to sit here existed solely because the classic
// texture-unit path sampled the texture object directly, and it is
// gone with that path.
IGpuSampler sampler = device.CreateSampler(GpuSamplerDescription.WorldClamp);
slot = device.RegisterTexture(texture, sampler);
}
catch
{
texture.Dispose();
throw;
}
_texture = texture;
TextureId = UiTextureTableHandle.FromSlot(slot);
}
public bool TryGetGlyph(char c, out Glyph g)
{
int idx = c - _firstChar;
if ((uint)idx >= (uint)_numChars)
{
g = default;
return false;
}
g = _glyphs[idx];
return true;
}
/// <summary>Measure the pixel width of a single-line string in this font.</summary>
public float MeasureWidth(string s)
{
float w = 0;
for (int i = 0; i < s.Length; i++)
{
if (TryGetGlyph(s[i], out var g))
w += g.Advance;
}
return w;
}
public void Dispose()
{
_texture.Dispose();
}
/// <summary>
/// Try to load a monospaced system font from well-known paths on the host OS.
/// Returns null if no candidate was found.
/// </summary>
public static byte[]? TryLoadSystemMonospaceFont()
{
string[] candidates =
{
@"C:\Windows\Fonts\consola.ttf",
@"C:\Windows\Fonts\cour.ttf",
@"C:\Windows\Fonts\arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
"/usr/share/fonts/TTF/DejaVuSansMono.ttf",
"/Library/Fonts/Menlo.ttc",
"/System/Library/Fonts/Menlo.ttc",
};
foreach (var path in candidates)
{
try
{
if (File.Exists(path))
return File.ReadAllBytes(path);
}
catch
{
// try next candidate
}
}
return null;
}
}