Skip to content

Commit

Permalink
Recycle assorted rendering components to accelerate drawing (#6483)
Browse files Browse the repository at this point in the history
This saves an awful lot of construction/destruction and memory
allocation, especially with text that changes a lot (see: cacafire).

Three things:
1. Recycling the text layouts. This holds onto the `CustomTextLayout` so
   all the things that don't change related to drawing targets and
   whatnot aren't freed and recreated every frame.
2. Reordering the runs in place. This saves a vector
   allocation/copy/delete every time OrderRuns is called. They can be
   rearranged in place.
3. Only clip once per row. This reduces the clip push/pop to only one
   time per row. Since we're always redrawing an entire row at a time,
   this saves a lot of alloc/free of the clip frame, dramatically
   reduces queued commands, and makes less work on the flush since
   clipping requires staging the drawing and then bringing it back to
   the main surface.
  • Loading branch information
miniksa authored Jun 22, 2020
1 parent 26d6a37 commit e7d3dc5
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 99 deletions.
52 changes: 37 additions & 15 deletions src/renderer/dx/CustomTextLayout.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,12 @@ using namespace Microsoft::Console::Render;
// - analyzer - DirectWrite text analyzer from the factory that has been cached at a level above this layout (expensive to create)
// - format - The DirectWrite format object representing the size and other text properties to be applied (by default) to a layout
// - font - The DirectWrite font face to use while calculating layout (by default, will fallback if necessary)
// - clusters - From the backing buffer, the text to be displayed clustered by the columns it should consume.
// - width - The count of pixels available per column (the expected pixel width of every column)
// - boxEffect - Box drawing scaling effects that are cached for the base font across layouts.
CustomTextLayout::CustomTextLayout(gsl::not_null<IDWriteFactory1*> const factory,
gsl::not_null<IDWriteTextAnalyzer1*> const analyzer,
gsl::not_null<IDWriteTextFormat*> const format,
gsl::not_null<IDWriteFontFace1*> const font,
std::basic_string_view<Cluster> const clusters,
size_t const width,
IBoxDrawingEffect* const boxEffect) :
_factory{ factory.get() },
Expand All @@ -47,8 +45,37 @@ CustomTextLayout::CustomTextLayout(gsl::not_null<IDWriteFactory1*> const factory
// Fetch the locale name out once now from the format
_localeName.resize(gsl::narrow_cast<size_t>(format->GetLocaleNameLength()) + 1); // +1 for null
THROW_IF_FAILED(format->GetLocaleName(_localeName.data(), gsl::narrow<UINT32>(_localeName.size())));
}

_textClusterColumns.reserve(clusters.size());
//Routine Description:
// - Resets this custom text layout to the freshly allocated state in terms of text analysis.
// Arguments:
// - <none>, modifies internal state
// Return Value:
// - S_OK or suitable memory management issue
[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::Reset() noexcept
try
{
_runs.clear();
_breakpoints.clear();
_runIndex = 0;
_isEntireTextSimple = false;
_textClusterColumns.clear();
_text.clear();
return S_OK;
}
CATCH_RETURN()

// Routine Description:
// - Appends text to this layout for analysis/processing.
// Arguments:
// - clusters - From the backing buffer, the text to be displayed clustered by the columns it should consume.
// Return Value:
// - S_OK or suitable memory management issue.
[[nodiscard]] HRESULT STDMETHODCALLTYPE CustomTextLayout::AppendClusters(const std::basic_string_view<::Microsoft::Console::Render::Cluster> clusters)
try
{
_textClusterColumns.reserve(_textClusterColumns.size() + clusters.size());

for (const auto& cluster : clusters)
{
Expand All @@ -64,7 +91,10 @@ CustomTextLayout::CustomTextLayout(gsl::not_null<IDWriteFactory1*> const factory

_text += text;
}

return S_OK;
}
CATCH_RETURN()

// Routine Description:
// - Figures out how many columns this layout should take. This will use the analyze step only.
Expand Down Expand Up @@ -1827,21 +1857,13 @@ void CustomTextLayout::_SplitCurrentRun(const UINT32 splitPosition)
// - <none>
void CustomTextLayout::_OrderRuns()
{
const size_t totalRuns = _runs.size();
std::vector<LinkedRun> runs;
runs.resize(totalRuns);

UINT32 nextRunIndex = 0;
for (UINT32 i = 0; i < totalRuns; ++i)
std::sort(_runs.begin(), _runs.end(), [](auto& a, auto& b) { return a.textStart < b.textStart; });
for (UINT32 i = 0; i < _runs.size() - 1; ++i)
{
runs.at(i) = _runs.at(nextRunIndex);
runs.at(i).nextRunIndex = i + 1;
nextRunIndex = _runs.at(nextRunIndex).nextRunIndex;
til::at(_runs, i).nextRunIndex = i + 1;
}

runs.back().nextRunIndex = 0;

_runs.swap(runs);
_runs.back().nextRunIndex = 0;
}

#pragma endregion
5 changes: 4 additions & 1 deletion src/renderer/dx/CustomTextLayout.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,13 @@ namespace Microsoft::Console::Render
gsl::not_null<IDWriteTextAnalyzer1*> const analyzer,
gsl::not_null<IDWriteTextFormat*> const format,
gsl::not_null<IDWriteFontFace1*> const font,
const std::basic_string_view<::Microsoft::Console::Render::Cluster> clusters,
size_t const width,
IBoxDrawingEffect* const boxEffect);

[[nodiscard]] HRESULT STDMETHODCALLTYPE AppendClusters(const std::basic_string_view<::Microsoft::Console::Render::Cluster> clusters);

[[nodiscard]] HRESULT STDMETHODCALLTYPE Reset() noexcept;

[[nodiscard]] HRESULT STDMETHODCALLTYPE GetColumns(_Out_ UINT32* columns);

// IDWriteTextLayout methods (but we don't actually want to implement them all, so just this one matching the existing interface)
Expand Down
62 changes: 50 additions & 12 deletions src/renderer/dx/CustomTextRenderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,40 @@ CATCH_RETURN()
::Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2dContext;
RETURN_IF_FAILED(drawingContext->renderTarget->QueryInterface(d2dContext.GetAddressOf()));

// Determine clip rectangle
D2D1_RECT_F clipRect;
clipRect.top = origin.y;
clipRect.bottom = clipRect.top + drawingContext->cellSize.height;
clipRect.left = 0;
clipRect.right = drawingContext->targetSize.width;

// If we already have a clip rectangle, check if it different than the previous one.
if (_clipRect.has_value())
{
const auto storedVal = _clipRect.value();
// If it is different, pop off the old one and push the new one on.
if (storedVal.top != clipRect.top || storedVal.bottom != clipRect.bottom ||
storedVal.left != clipRect.left || storedVal.right != clipRect.right)
{
d2dContext->PopAxisAlignedClip();

// Clip all drawing in this glyph run to where we expect.
// We need the AntialiasMode here to be Aliased to ensure
// that background boxes line up with each other and don't leave behind
// stray colors.
// See GH#3626 for more details.
d2dContext->PushAxisAlignedClip(clipRect, D2D1_ANTIALIAS_MODE_ALIASED);
_clipRect = clipRect;
}
}
// If we have no clip rectangle, it's easy. Push it on and go.
else
{
// See above for aliased flag explanation.
d2dContext->PushAxisAlignedClip(clipRect, D2D1_ANTIALIAS_MODE_ALIASED);
_clipRect = clipRect;
}

// Draw the background
// The rectangle needs to be deduced based on the origin and the BidiDirection
const auto advancesSpan = gsl::make_span(glyphRun->glyphAdvances, glyphRun->glyphCount);
Expand All @@ -425,18 +459,6 @@ CATCH_RETURN()
}
rect.right = rect.left + totalSpan;

// Clip all drawing in this glyph run to where we expect.
// We need the AntialiasMode here to be Aliased to ensure
// that background boxes line up with each other and don't leave behind
// stray colors.
// See GH#3626 for more details.
d2dContext->PushAxisAlignedClip(rect, D2D1_ANTIALIAS_MODE_ALIASED);

// Ensure we pop it on the way out
auto popclip = wil::scope_exit([&d2dContext]() noexcept {
d2dContext->PopAxisAlignedClip();
});

d2dContext->FillRectangle(rect, drawingContext->backgroundBrush);

RETURN_IF_FAILED(_drawCursor(d2dContext.Get(), rect, *drawingContext, true));
Expand Down Expand Up @@ -635,6 +657,22 @@ CATCH_RETURN()
}
#pragma endregion

[[nodiscard]] HRESULT CustomTextRenderer::EndClip(void* clientDrawingContext) noexcept
try
{
DrawingContext* drawingContext = static_cast<DrawingContext*>(clientDrawingContext);
RETURN_HR_IF(E_INVALIDARG, !drawingContext);

if (_clipRect.has_value())
{
drawingContext->renderTarget->PopAxisAlignedClip();
_clipRect = std::nullopt;
}

return S_OK;
}
CATCH_RETURN()

[[nodiscard]] HRESULT CustomTextRenderer::_DrawBasicGlyphRun(DrawingContext* clientDrawingContext,
D2D1_POINT_2F baselineOrigin,
DWRITE_MEASURING_MODE measuringMode,
Expand Down
27 changes: 17 additions & 10 deletions src/renderer/dx/CustomTextRenderer.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,20 @@ namespace Microsoft::Console::Render
IDWriteFactory* dwriteFactory,
const DWRITE_LINE_SPACING spacing,
const D2D_SIZE_F cellSize,
const D2D_SIZE_F targetSize,
const std::optional<CursorOptions>& cursorInfo,
const D2D1_DRAW_TEXT_OPTIONS options = D2D1_DRAW_TEXT_OPTIONS_NONE) noexcept
const D2D1_DRAW_TEXT_OPTIONS options = D2D1_DRAW_TEXT_OPTIONS_NONE) noexcept :
renderTarget(renderTarget),
foregroundBrush(foregroundBrush),
backgroundBrush(backgroundBrush),
forceGrayscaleAA(forceGrayscaleAA),
dwriteFactory(dwriteFactory),
spacing(spacing),
cellSize(cellSize),
targetSize(targetSize),
cursorInfo(cursorInfo),
options(options)
{
this->renderTarget = renderTarget;
this->foregroundBrush = foregroundBrush;
this->backgroundBrush = backgroundBrush;
this->forceGrayscaleAA = forceGrayscaleAA;
this->dwriteFactory = dwriteFactory;
this->spacing = spacing;
this->cellSize = cellSize;
this->cursorInfo = cursorInfo;
this->options = options;
}

ID2D1RenderTarget* renderTarget;
Expand All @@ -39,6 +41,7 @@ namespace Microsoft::Console::Render
IDWriteFactory* dwriteFactory;
DWRITE_LINE_SPACING spacing;
D2D_SIZE_F cellSize;
D2D_SIZE_F targetSize;
std::optional<CursorOptions> cursorInfo;
D2D1_DRAW_TEXT_OPTIONS options;
};
Expand Down Expand Up @@ -98,6 +101,8 @@ namespace Microsoft::Console::Render
BOOL isRightToLeft,
IUnknown* clientDrawingEffect) noexcept override;

[[nodiscard]] HRESULT STDMETHODCALLTYPE EndClip(void* clientDrawingContext) noexcept;

private:
[[nodiscard]] HRESULT _FillRectangle(void* clientDrawingContext,
IUnknown* clientDrawingEffect,
Expand Down Expand Up @@ -128,5 +133,7 @@ namespace Microsoft::Console::Render
DWRITE_MEASURING_MODE measuringMode,
_In_ const DWRITE_GLYPH_RUN* glyphRun,
_In_opt_ const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription) noexcept;

std::optional<D2D1_RECT_F> _clipRect;
};
}
Loading

0 comments on commit e7d3dc5

Please sign in to comment.