Skip to content

Commit 91e887c

Browse files
committed
Introduce the concept of a shared glyph cache
1 parent 0019fdb commit 91e887c

4 files changed

Lines changed: 198 additions & 11 deletions

File tree

‎src/ImageSharp.Drawing/Processing/DrawingCanvas{TPixel}.cs‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,18 @@ public sealed class DrawingCanvas<TPixel> : DrawingCanvas
5959
/// </summary>
6060
private readonly Stack<DrawingCanvasState> savedStates = new();
6161

62+
// Per-canvas glyph-outline cache: when enabled, hoists RichTextGlyphRenderer's per-glyph
63+
// outline cache from per-DrawText-call scope up to the whole canvas, so a glyph outline
64+
// built once is reused by every DrawText call on this canvas (across a frame's many text
65+
// runs) instead of being rebuilt for every run on a text-heavy page. Lazily created and only
66+
// used when sharing is opted in via Configuration.SetSharedGlyphCache; see shareGlyphCache.
67+
private Dictionary<RichTextGlyphRenderer.CacheKey, List<RichTextGlyphRenderer.GlyphRenderData>>? sharedGlyphCacheStore;
68+
69+
// Whether this canvas shares its glyph-outline cache across DrawText calls. Resolved once at
70+
// construction from the configuration (Configuration.SetSharedGlyphCache); defaults to false,
71+
// in which case each DrawText uses RichTextGlyphRenderer's private per-call cache.
72+
private readonly bool shareGlyphCache;
73+
6274
/// <summary>
6375
/// Initializes a new instance of the <see cref="DrawingCanvas{TPixel}"/> class.
6476
/// </summary>
@@ -149,6 +161,7 @@ private DrawingCanvas(
149161
this.targetFrame = targetFrame;
150162
this.batcher = batcher;
151163
this.ownsBatcher = ownsBatcher;
164+
this.shareGlyphCache = configuration.GetSharedGlyphCache();
152165

153166
// Canvas coordinates are local to the current frame; origin stays at (0,0).
154167
this.Bounds = new Rectangle(0, 0, targetFrame.Bounds.Width, targetFrame.Bounds.Height);
@@ -437,6 +450,11 @@ public override void DrawText(
437450
this.DrawTextCore(textOptions, text, path, brush, pen);
438451
}
439452

453+
// Returns the per-canvas shared glyph-outline cache (lazily created) when sharing is enabled,
454+
// or null so the renderer falls back to its private per-call cache (the historical default).
455+
private Dictionary<RichTextGlyphRenderer.CacheKey, List<RichTextGlyphRenderer.GlyphRenderData>>? ResolveGlyphCache()
456+
=> this.shareGlyphCache ? this.sharedGlyphCacheStore ??= [] : null;
457+
440458
private void DrawTextCore(
441459
RichTextOptions textOptions,
442460
ReadOnlySpan<char> text,
@@ -457,7 +475,7 @@ private void DrawTextCore(
457475
EnsureTextPaint(brush, pen);
458476

459477
RichTextOptions configuredOptions = ConfigureTextOptions(textOptions, path, out IPath? configuredPath);
460-
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, configuredPath, pen, brush);
478+
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, configuredPath, pen, brush, this.ResolveGlyphCache());
461479
TextRenderer renderer = new(glyphRenderer);
462480
renderer.RenderText(text, configuredOptions);
463481

@@ -487,7 +505,7 @@ public override void DrawText(
487505
effectiveOptions.ShapeOptions,
488506
Matrix4x4.CreateTranslation(location.X, location.Y, 0) * effectiveOptions.Transform);
489507

490-
using RichTextGlyphRenderer glyphRenderer = new(placedOptions, path: null, pen, brush);
508+
using RichTextGlyphRenderer glyphRenderer = new(placedOptions, path: null, pen, brush, this.ResolveGlyphCache());
491509
textBlock.RenderTo(glyphRenderer, wrappingLength);
492510

493511
this.DrawTextOperations(glyphRenderer.DrawingOperations, placedOptions, state.ClipPaths);
@@ -509,7 +527,7 @@ public override void DrawText(
509527
DrawingCanvasState state = this.ResolveState();
510528
DrawingOptions effectiveOptions = state.Options;
511529

512-
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, path, pen, brush);
530+
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, path, pen, brush, this.ResolveGlyphCache());
513531
textBlock.RenderTo(glyphRenderer, wrappingLength);
514532

515533
this.DrawTextOperations(glyphRenderer.DrawingOperations, effectiveOptions, state.ClipPaths);
@@ -537,7 +555,7 @@ public override void DrawText(
537555
effectiveOptions.ShapeOptions,
538556
Matrix4x4.CreateTranslation(location.X, location.Y, 0) * effectiveOptions.Transform);
539557

540-
using RichTextGlyphRenderer glyphRenderer = new(placedOptions, path: null, pen, brush);
558+
using RichTextGlyphRenderer glyphRenderer = new(placedOptions, path: null, pen, brush, this.ResolveGlyphCache());
541559
lineLayout.RenderTo(glyphRenderer);
542560

543561
this.DrawTextOperations(glyphRenderer.DrawingOperations, placedOptions, state.ClipPaths);
@@ -558,7 +576,7 @@ public override void DrawText(
558576
DrawingCanvasState state = this.ResolveState();
559577
DrawingOptions effectiveOptions = state.Options;
560578

561-
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, path, pen, brush);
579+
using RichTextGlyphRenderer glyphRenderer = new(effectiveOptions, path, pen, brush, this.ResolveGlyphCache());
562580
lineLayout.RenderTo(glyphRenderer);
563581

564582
this.DrawTextOperations(glyphRenderer.DrawingOperations, effectiveOptions, state.ClipPaths);
@@ -1144,6 +1162,9 @@ public override void Dispose()
11441162
this.DisposePendingImageResources();
11451163
}
11461164

1165+
// Release the per-canvas shared glyph-outline cache.
1166+
this.sharedGlyphCacheStore = null;
1167+
11471168
this.isDisposed = true;
11481169
}
11491170
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright (c) Six Labors.
2+
// Licensed under the Six Labors Split License.
3+
4+
namespace SixLabors.ImageSharp.Drawing.Processing;
5+
6+
/// <summary>
7+
/// Adds extensions that control whether glyph-outline caching is shared across all
8+
/// <c>DrawText</c> calls on a canvas (per-canvas) rather than rebuilt per call.
9+
/// </summary>
10+
public static class GlyphCacheDefaultsExtensions
11+
{
12+
/// <summary>
13+
/// Sets whether canvases created from this configuration share a single glyph-outline cache
14+
/// across every <c>DrawText</c> call (per-canvas), instead of using a private cache per call.
15+
/// </summary>
16+
/// <remarks>
17+
/// Sharing lets a glyph outline built once be reused by later text runs on the same canvas,
18+
/// which can help text-heavy output, at the cost of sub-pixel-quantized reuse across calls.
19+
/// Disabled by default.
20+
/// </remarks>
21+
/// <param name="configuration">The configuration to store the setting against.</param>
22+
/// <param name="enabled"><see langword="true"/> to share the glyph cache per canvas.</param>
23+
public static void SetSharedGlyphCache(this Configuration configuration, bool enabled)
24+
{
25+
Guard.NotNull(configuration, nameof(configuration));
26+
configuration.Properties[typeof(SharedGlyphCacheKey)] = enabled;
27+
}
28+
29+
/// <summary>
30+
/// Gets whether canvases created from this configuration share a glyph-outline cache per canvas.
31+
/// </summary>
32+
/// <param name="configuration">The configuration to read the setting from.</param>
33+
/// <returns><see langword="true"/> if sharing is enabled; otherwise <see langword="false"/> (the default).</returns>
34+
internal static bool GetSharedGlyphCache(this Configuration configuration)
35+
=> configuration.Properties.TryGetValue(typeof(SharedGlyphCacheKey), out object? value) && value is true;
36+
37+
// Dedicated marker type used as the Configuration.Properties key, mirroring how the
38+
// pluggable drawing backend keys its entry on typeof(IDrawingBackend).
39+
private sealed class SharedGlyphCacheKey
40+
{
41+
}
42+
}

‎src/ImageSharp.Drawing/Processing/RichTextGlyphRenderer.cs‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,14 @@ internal sealed partial class RichTextGlyphRenderer : BaseGlyphBuilder, IDisposa
7272
// Benchmarked to give <0.2% image difference vs. uncached, with >60% cache hit ratio.
7373
private const float AccuracyMultiple = 8;
7474

75-
/// <summary>Maps cache keys to their list of <see cref="GlyphRenderData"/> entries (one per layer).</summary>
76-
private readonly Dictionary<CacheKey, List<GlyphRenderData>> glyphCache = [];
75+
/// <summary>Maps cache keys to their list of <see cref="GlyphRenderData"/> entries (one per layer).
76+
/// May be a per-canvas shared cache injected via the constructor so glyph outlines persist across
77+
/// every DrawText call in a frame; otherwise a private per-renderer cache (the historical behavior).</summary>
78+
private readonly Dictionary<CacheKey, List<GlyphRenderData>> glyphCache;
79+
80+
/// <summary><see langword="true"/> when <see cref="glyphCache"/> is owned by this renderer and
81+
/// cleared on dispose; <see langword="false"/> for an injected shared (per-canvas) cache.</summary>
82+
private readonly bool ownsCache;
7783

7884
/// <summary>Read cursor into the cached layer list for layered cache hits.</summary>
7985
private int cacheReadIndex;
@@ -107,16 +113,22 @@ internal sealed partial class RichTextGlyphRenderer : BaseGlyphBuilder, IDisposa
107113
/// <param name="path">Optional path to draw the text along.</param>
108114
/// <param name="pen">Default pen for outlined text, or <see langword="null"/> for fill-only.</param>
109115
/// <param name="brush">Default brush for filled text, or <see langword="null"/> for outline-only.</param>
116+
/// <param name="sharedGlyphCache">Optional caller-owned glyph cache shared across renderer
117+
/// instances (e.g. per-canvas) so glyph outlines persist beyond a single text draw; when
118+
/// <see langword="null"/> the renderer uses a private cache cleared on dispose.</param>
110119
public RichTextGlyphRenderer(
111120
DrawingOptions drawingOptions,
112121
IPath? path,
113122
Pen? pen,
114-
Brush? brush)
123+
Brush? brush,
124+
Dictionary<CacheKey, List<GlyphRenderData>>? sharedGlyphCache = null)
115125
: base(drawingOptions.Transform)
116126
{
117127
this.drawingOptions = drawingOptions;
118128
this.defaultPen = pen;
119129
this.defaultBrush = brush;
130+
this.glyphCache = sharedGlyphCache ?? [];
131+
this.ownsCache = sharedGlyphCache is null;
120132
this.DrawingOperations = [];
121133
this.currentCompositionMode = drawingOptions.GraphicsOptions.AlphaCompositionMode;
122134
this.currentBlendingMode = drawingOptions.GraphicsOptions.ColorBlendingMode;
@@ -782,7 +794,12 @@ private void Dispose(bool disposing)
782794
{
783795
if (disposing)
784796
{
785-
this.glyphCache.Clear();
797+
// A shared (per-canvas) cache outlives this renderer; only clear a private one.
798+
if (this.ownsCache)
799+
{
800+
this.glyphCache.Clear();
801+
}
802+
786803
this.DrawingOperations.Clear();
787804
}
788805

@@ -795,7 +812,7 @@ private void Dispose(bool disposing)
795812
/// path and the sub-pixel deltas needed to reposition the path at a different
796813
/// screen location on a cache hit.
797814
/// </summary>
798-
private struct GlyphRenderData
815+
internal struct GlyphRenderData
799816
{
800817
/// <summary>
801818
/// The fractional-pixel offset between the path's bounding-box origin
@@ -834,7 +851,7 @@ private struct GlyphRenderData
834851
/// sub-pixel position (quantized to <see cref="AccuracyMultiple"/>), and the pen reference
835852
/// (since stroke width affects the outline path).
836853
/// </summary>
837-
private readonly struct CacheKey : IEquatable<CacheKey>
854+
internal readonly struct CacheKey : IEquatable<CacheKey>
838855
{
839856
/// <summary>Gets the font family name.</summary>
840857
public string Font { get; init; }
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Copyright (c) Six Labors.
2+
// Licensed under the Six Labors Split License.
3+
4+
using BenchmarkDotNet.Attributes;
5+
using SixLabors.Fonts;
6+
using SixLabors.ImageSharp.Drawing.Processing;
7+
using SixLabors.ImageSharp.PixelFormats;
8+
using SixLabors.ImageSharp.Processing;
9+
10+
namespace SixLabors.ImageSharp.Drawing.Benchmarks.Drawing;
11+
12+
/// <summary>
13+
/// Measures the per-canvas shared glyph-outline cache (opt-in via
14+
/// <see cref="GlyphCacheDefaultsExtensions.SetSharedGlyphCache"/>) against the default
15+
/// per-call cache.
16+
/// <para>
17+
/// Unlike <see cref="DrawTextRepeatedGlyphs"/> (a single <c>DrawText</c> call, where the
18+
/// per-call cache already captures repeats), this draws <see cref="RunCount"/> separate
19+
/// <c>DrawText</c> calls that reuse a common alphabet across runs - the cross-call reuse the
20+
/// shared cache is designed to exploit. The baseline rebuilds each run's glyph outlines from
21+
/// scratch; the shared variant reuses outlines built by earlier runs on the same canvas.
22+
/// </para>
23+
/// </summary>
24+
[MemoryDiagnoser]
25+
public class DrawTextSharedGlyphCache
26+
{
27+
public const int Width = 700;
28+
29+
// Vertical advance between runs. The canvas height is sized in Setup to fit every run so all
30+
// text is actually rasterized (not culled off-canvas), keeping the on/off comparison fair.
31+
private const float LineHeight = 20F;
32+
33+
private readonly Brush brush = Brushes.Solid(Color.Black);
34+
35+
private readonly DrawingOptions drawingOptions = new()
36+
{
37+
GraphicsOptions = new GraphicsOptions { Antialias = true }
38+
};
39+
40+
private Image<Rgba32> privateCacheImage;
41+
private Image<Rgba32> sharedCacheImage;
42+
private Font font;
43+
private string[] runs;
44+
45+
[Params(50, 250, 1000)]
46+
public int RunCount { get; set; }
47+
48+
[GlobalSetup]
49+
public void Setup()
50+
{
51+
this.font = SystemFonts.CreateFont("Arial", 16);
52+
53+
// Short runs drawn as separate DrawText calls. They share a common word pool so glyph
54+
// outlines overlap heavily across runs, which is exactly what a per-canvas cache can reuse.
55+
string[] words = ["The", "quick", "brown", "fox", "jumps", "over", "lazy", "dog", "Sphinx", "black", "quartz", "judge", "vow"];
56+
this.runs = new string[this.RunCount];
57+
for (int i = 0; i < this.RunCount; i++)
58+
{
59+
this.runs[i] = string.Join(
60+
' ',
61+
words[i % words.Length],
62+
words[(i + 3) % words.Length],
63+
words[(i + 7) % words.Length],
64+
words[(i + 11) % words.Length]);
65+
}
66+
67+
// Two isolated configurations differing only in the opt-in flag. Cloning Configuration.Default
68+
// gives an independent Properties bag (the same pattern used to scope SetDrawingBackend), so
69+
// setting the flag on one clone does not affect the other or the global default.
70+
Configuration privateConfig = Configuration.Default.Clone();
71+
privateConfig.SetSharedGlyphCache(false);
72+
73+
Configuration sharedConfig = Configuration.Default.Clone();
74+
sharedConfig.SetSharedGlyphCache(true);
75+
76+
// Tall enough to lay every run on its own line within the canvas bounds.
77+
int height = 16 + (int)(this.RunCount * LineHeight);
78+
this.privateCacheImage = new Image<Rgba32>(privateConfig, Width, height);
79+
this.sharedCacheImage = new Image<Rgba32>(sharedConfig, Width, height);
80+
}
81+
82+
[GlobalCleanup]
83+
public void Cleanup()
84+
{
85+
this.privateCacheImage.Dispose();
86+
this.sharedCacheImage.Dispose();
87+
}
88+
89+
[Benchmark(Baseline = true, Description = "Per-call glyph cache (default)")]
90+
public void PrivateGlyphCache()
91+
=> this.privateCacheImage.Mutate(c => c.Paint(this.drawingOptions, this.DrawRuns));
92+
93+
[Benchmark(Description = "Shared per-canvas glyph cache")]
94+
public void SharedGlyphCache()
95+
=> this.sharedCacheImage.Mutate(c => c.Paint(this.drawingOptions, this.DrawRuns));
96+
97+
private void DrawRuns(DrawingCanvas canvas)
98+
{
99+
float y = 8;
100+
foreach (string run in this.runs)
101+
{
102+
RichTextOptions options = new(this.font) { Origin = new PointF(8, y) };
103+
canvas.DrawText(options, run, this.brush, null);
104+
y += LineHeight;
105+
}
106+
}
107+
}

0 commit comments

Comments
 (0)