Browse Source

Text: new RendererCore class.

A higher-level stateful wrapper around the low-level utilities, capable
of rendering text formed from multiple lines and multiple fonts. Will be
used as a backend for a new Renderer / RendererGL implementation.

No usage docs yet, those will come once the other two classes are made
as well.
pull/674/head
Vladimír Vondruš 2 years ago
parent
commit
84809128b1
  1. 3
      src/Magnum/Text/CMakeLists.txt
  2. 123
      src/Magnum/Text/Implementation/rendererState.h
  3. 723
      src/Magnum/Text/Renderer.cpp
  4. 569
      src/Magnum/Text/Renderer.h
  5. 3320
      src/Magnum/Text/Test/RendererTest.cpp
  6. 2
      src/Magnum/Text/Text.h

3
src/Magnum/Text/CMakeLists.txt

@ -60,7 +60,8 @@ set(MagnumText_HEADERS
visibility.h) visibility.h)
set(MagnumText_PRIVATE_HEADERS set(MagnumText_PRIVATE_HEADERS
Implementation/printFourCC.h) Implementation/printFourCC.h
Implementation/rendererState.h)
if(MAGNUM_TARGET_GL) if(MAGNUM_TARGET_GL)
list(APPEND MagnumText_GracefulAssert_SRCS list(APPEND MagnumText_GracefulAssert_SRCS

123
src/Magnum/Text/Implementation/rendererState.h

@ -0,0 +1,123 @@
#ifndef Magnum_Text_Implementation_rendererState_h
#define Magnum_Text_Implementation_rendererState_h
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022, 2023, 2024, 2025
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "Magnum/Text/Renderer.h"
#include <Corrade/Containers/Array.h>
#include <Corrade/Containers/Optional.h>
#include <Corrade/Containers/StridedArrayView.h>
#include "Magnum/Math/Range.h"
#include "Magnum/Text/Alignment.h"
#include "Magnum/Text/Direction.h"
namespace Magnum { namespace Text {
/* Is inherited by RendererCore::AllocatorState to avoid extra allocations */
struct RendererCore::State {
/* Gets called by RendererCore only if both allocators are specified by the
user. If not, AllocatorState is constructed instead. */
explicit State(const AbstractGlyphCache& glyphCache, void(*glyphAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Vector2>&, Containers::StridedArrayView1D<UnsignedInt>&, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>&), void* glyphAllocatorState, void(*const runAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Float>&, Containers::StridedArrayView1D<UnsignedInt>&), void* runAllocatorState, RendererCoreFlags flags): glyphCache(glyphCache), glyphAllocator{glyphAllocator}, glyphAllocatorState{glyphAllocatorState}, runAllocator{runAllocator}, runAllocatorState{runAllocatorState}, flags{flags} {
CORRADE_INTERNAL_DEBUG_ASSERT(glyphAllocator && runAllocator);
}
/* AllocatorState, Renderer::State etc. inherit from this with the instance
deleted through the base pointer */
virtual ~State() = default;
const AbstractGlyphCache& glyphCache;
void(*const glyphAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Vector2>&, Containers::StridedArrayView1D<UnsignedInt>&, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>&);
void* const glyphAllocatorState;
void(*const runAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Float>&, Containers::StridedArrayView1D<UnsignedInt>&);
void* const runAllocatorState;
const RendererCoreFlags flags;
/* These are controllable by various setters. Keep these values in sync
with code in reset(). */
Alignment alignment = Alignment::MiddleCenter;
LayoutDirection layoutDirection = LayoutDirection::HorizontalTopToBottom;
/* 1 byte free */
Vector2 cursor;
Float lineAdvance = 0.0f;
/* Capacity is the array size. The "rendering" value is glyphs from the
add() calls since the last render() or clear(), i.e. ones that aren't
fully aligned and such yet. */
UnsignedInt glyphCount = 0, renderingGlyphCount = 0;
Containers::StridedArrayView1D<Vector2> glyphPositions;
Containers::StridedArrayView1D<UnsignedInt> glyphIds;
/* Non-empty only if RendererFlag::GlyphClusters is set */
Containers::StridedArrayView1D<UnsignedInt> glyphClusters;
Containers::StridedArrayView1D<Vector2> glyphAdvances;
/* Capacity is the array size. The "rendering" value is again runs from the
add() calls since the last render() or clear(). */
UnsignedInt runCount = 0, renderingRunCount = 0;
Containers::StridedArrayView1D<Float> runScales;
Containers::StridedArrayView1D<UnsignedInt> runEnds;
/* Rendering state */
bool rendering = false;
/* 1 byte free */
Containers::Optional<Alignment> resolvedAlignment;
/* Both are a zero vector initially, the first track the current line start
and the second position within the current line. The actual `cursor` is
added to all glyph positions only at the end. */
Vector2 renderingLineStart, renderingLineCursor;
/* On add(), if zero, is set to lineAdvance (if non-zero) or (scaled) line
advance of the first used font */
/** @todo might want to vary line advance per line based on the actual
metrics of used fonts (it looks uglily uneven though!), would need to
keep track of max descent, max ascent and max line gap of fonts used on
previous and next line and calculate the actual line advance from
prev line max descent + max of prev and current line line gap + max of
current line ascent, and then shift the whole like by that once it's
done instead of advancing directly the cursor before */
Vector2 renderingLineAdvance;
/* Everything until runCount is a block that needs to be aligned */
UnsignedInt blockRunBegin = 0;
Range2D blockRectangle;
/* Everything until runCount is a line that needs to be aligned */
UnsignedInt lineGlyphBegin = 0;
Range2D lineRectangle;
};
/* Instantiated only if the builtin allocators are used. See their contents for
the types being stored here. */
struct RendererCore::AllocatorState: RendererCore::State {
/* Defined in Renderer.cpp because it needs access to default allocator
implementations */
explicit AllocatorState(const AbstractGlyphCache& glyphCache, void(*glyphAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Vector2>&, Containers::StridedArrayView1D<UnsignedInt>&, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>&), void* glyphAllocatorState, void(*const runAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Float>&, Containers::StridedArrayView1D<UnsignedInt>&), void* runAllocatorState, RendererCoreFlags flags);
Containers::Array<char> glyphData;
Containers::Array<char> runData;
};
}}
#endif

723
src/Magnum/Text/Renderer.cpp

@ -26,22 +26,39 @@
#include "Renderer.h" #include "Renderer.h"
#include <Corrade/Containers/StridedArrayView.h> #include <Corrade/Containers/EnumSet.hpp>
#include <Corrade/Containers/GrowableArray.h>
#include <Corrade/Containers/Optional.h> #include <Corrade/Containers/Optional.h>
#include <Corrade/Containers/StridedArrayView.h>
#include <Corrade/Containers/StringView.h>
#include <Corrade/Containers/Triple.h> #include <Corrade/Containers/Triple.h>
#include "Magnum/Math/Functions.h" #include "Magnum/Math/Functions.h"
#include "Magnum/Math/FunctionsBatch.h"
#include "Magnum/Math/Range.h" #include "Magnum/Math/Range.h"
#include "Magnum/Text/AbstractFont.h" #include "Magnum/Text/AbstractFont.h"
#include "Magnum/Text/AbstractGlyphCache.h" #include "Magnum/Text/AbstractGlyphCache.h"
#include "Magnum/Text/AbstractShaper.h"
#include "Magnum/Text/Alignment.h" #include "Magnum/Text/Alignment.h"
#include "Magnum/Text/Direction.h" #include "Magnum/Text/Direction.h"
#include "Magnum/Text/Implementation/rendererState.h"
/* Somehow on GCC 4.8 to 7 the {} passed as a default argument for
ArrayView<const FeatureRange> causes "error: elements of array 'const class
Magnum::Text::FeatureRange [0]' have incomplete type". GCC 9 is fine, no
idea about version 8, but including the definition for it as well to be
safe. Similar problem happens with MSVC STL, where the initializer_list is
implemented as a (begin, end) pair and size() is a difference of those two
pointers. Which needs to know the type size to calculate the actual element
count. */
#if (defined(CORRADE_TARGET_GCC) && __GNUC__ <= 8) || defined(CORRADE_TARGET_DINKUMWARE)
#include "Magnum/Text/Feature.h"
#endif
#ifdef MAGNUM_TARGET_GL #ifdef MAGNUM_TARGET_GL
#include <string> #include <string>
#include <tuple> #include <tuple>
#include <vector> #include <vector>
#include <Corrade/Containers/Array.h>
#include <Corrade/Containers/ArrayViewStl.h> /** @todo remove once Renderer is STL-free */ #include <Corrade/Containers/ArrayViewStl.h> /** @todo remove once Renderer is STL-free */
#include <Corrade/Containers/StringStl.h> /** @todo remove once Renderer is STL-free */ #include <Corrade/Containers/StringStl.h> /** @todo remove once Renderer is STL-free */
@ -50,11 +67,711 @@
#include "Magnum/GL/Extensions.h" #include "Magnum/GL/Extensions.h"
#include "Magnum/GL/Mesh.h" #include "Magnum/GL/Mesh.h"
#include "Magnum/Shaders/GenericGL.h" #include "Magnum/Shaders/GenericGL.h"
#include "Magnum/Text/AbstractShaper.h"
#endif #endif
namespace Magnum { namespace Text { namespace Magnum { namespace Text {
Debug& operator<<(Debug& debug, const RendererCoreFlag value) {
debug << "Text::RendererCoreFlag" << Debug::nospace;
switch(value) {
/* LCOV_EXCL_START */
#define _c(v) case RendererCoreFlag::v: return debug << "::" #v;
_c(GlyphClusters)
#undef _c
/* LCOV_EXCL_STOP */
}
return debug << "(" << Debug::nospace << Debug::hex << UnsignedByte(value) << Debug::nospace << ")";
}
Debug& operator<<(Debug& debug, const RendererCoreFlags value) {
return Containers::enumSetDebugOutput(debug, value, "Text::RendererCoreFlags{}", {
RendererCoreFlag::GlyphClusters
});
}
namespace {
struct Glyph {
Vector2 position;
UnsignedInt id;
};
struct GlyphCluster {
Vector2 position;
UnsignedInt id;
UnsignedInt cluster;
};
auto defaultGlyphAllocatorFor(const RendererCoreFlags flags) -> void(*)(void*, UnsignedInt, Containers::StridedArrayView1D<Vector2>&, Containers::StridedArrayView1D<UnsignedInt>&, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>&) {
if(flags >= RendererCoreFlag::GlyphClusters)
return [](void* const state, const UnsignedInt glyphCount, Containers::StridedArrayView1D<Vector2>& glyphPositions, Containers::StridedArrayView1D<UnsignedInt>& glyphIds, Containers::StridedArrayView1D<UnsignedInt>* const glyphClusters, Containers::StridedArrayView1D<Vector2>& glyphAdvances) {
Containers::Array<char>& data = *static_cast<Containers::Array<char>*>(state);
/* The array may not be fully used yet, or it might have been reset
back to empty. Append only if the desired capacity is more than
what's there. */
const std::size_t existingSize = glyphPositions.size();
const std::size_t desiredByteSize = (existingSize + glyphCount)*sizeof(GlyphCluster);
if(desiredByteSize > data.size()) {
/* Using arrayAppend() as it reallocates with a growth
strategy, arrayResize() would take the size literally */
arrayAppend(data, NoInit, desiredByteSize - data.size());
}
/* The new capacity is the actual array size, not just
`desiredByteSize`. If the array got enlarged by exactly the
requested `size`, it'll be the same as `desiredByteSize`. If the
array was larger, such as after a clear(), the capacity will
again use up all of it. */
const Containers::StridedArrayView1D<GlyphCluster> glyphs = Containers::arrayCast<GlyphCluster>(data);
glyphPositions = glyphs.slice(&GlyphCluster::position);
glyphIds = glyphs.slice(&GlyphCluster::id);
*glyphClusters = glyphs.slice(&GlyphCluster::cluster);
/* As IDs and clusters are right after each other and have the same
size as a Vector2, we can abuse them to store advances. Those
are guaranteed to be always filled only once advances are no
longer needed, so that's fine -- but we need to ensure that we
point to the new memory, not to the existing, where it'd
overwrite existing IDs and clusters. */
glyphAdvances = Containers::arrayCast<Vector2>(glyphs.slice(&GlyphCluster::id).exceptPrefix(existingSize));
};
else
return [](void* const state, const UnsignedInt glyphCount, Containers::StridedArrayView1D<Vector2>& glyphPositions, Containers::StridedArrayView1D<UnsignedInt>& glyphIds, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>& glyphAdvances) {
Containers::Array<char>& data = *static_cast<Containers::Array<char>*>(state);
/* The array may not be fully used yet, or it might have been reset
back to empty. Append only if the desired capacity is more than
what's there. Unlike above we don't have any place to alias
advances with, so append them at the end. */
const std::size_t desiredByteSize = glyphPositions.size()*sizeof(Glyph) + glyphCount*(sizeof(Glyph) + sizeof(Vector2));
if(desiredByteSize > data.size()) {
/* Using arrayAppend() as it reallocates with a growth
strategy, arrayResize() would take the size literally */
arrayAppend(data, NoInit, desiredByteSize - data.size());
}
/* Calculate the new capacity from the actual array size. Compared
to the above, we need to make sure the unused space at the end
is correctly divided between the Glyph and the Vector2 for
advances. */
const std::size_t newCapacity = glyphPositions.size() + (data.size() - glyphPositions.size()*sizeof(Glyph))/(sizeof(Glyph) + sizeof(Vector2));
const std::size_t newSize = newCapacity - glyphPositions.size();
const Containers::StridedArrayView1D<Glyph> glyphs = Containers::arrayCast<Glyph>(data.prefix(newCapacity*sizeof(Glyph)));
glyphPositions = glyphs.slice(&Glyph::position);
glyphIds = glyphs.slice(&Glyph::id);
/* Don't take just the suffix for advances as the size may not be
divisible by sizeof(Vector2), especially after clear() */
glyphAdvances = Containers::arrayCast<Vector2>(data.sliceSize(newCapacity*sizeof(Glyph), newSize*sizeof(Vector2)));
};
}
struct TextRun {
Float scale;
UnsignedInt end;
};
void defaultRunAllocator(void* const state, const UnsignedInt runCount, Containers::StridedArrayView1D<Float>& runScales, Containers::StridedArrayView1D<UnsignedInt>& runEnds) {
Containers::Array<char>& data = *static_cast<Containers::Array<char>*>(state);
const std::size_t newSize = runScales.size() + runCount;
const std::size_t desiredByteSize = newSize*sizeof(TextRun);
if(desiredByteSize > data.size()) {
/* Using arrayAppend() as it reallocates with a growth strategy,
arrayResize() would take the size literally */
arrayAppend(data, NoInit, desiredByteSize - data.size());
}
const Containers::StridedArrayView1D<TextRun> runs = Containers::arrayCast<TextRun>(data);
runScales = runs.slice(&TextRun::scale);
runEnds = runs.slice(&TextRun::end);
}
}
RendererCore::AllocatorState::AllocatorState(const AbstractGlyphCache& glyphCache, void(*glyphAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Vector2>&, Containers::StridedArrayView1D<UnsignedInt>&, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>&), void* glyphAllocatorState, void(*const runAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Float>&, Containers::StridedArrayView1D<UnsignedInt>&), void* runAllocatorState, RendererCoreFlags flags): State{glyphCache,
glyphAllocator ? glyphAllocator : defaultGlyphAllocatorFor(flags),
glyphAllocator ? glyphAllocatorState : &glyphData,
runAllocator ? runAllocator : defaultRunAllocator,
runAllocator ? runAllocatorState : &runData, flags} {}
RendererCore::RendererCore(const AbstractGlyphCache& glyphCache, void(*glyphAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Vector2>&, Containers::StridedArrayView1D<UnsignedInt>&, Containers::StridedArrayView1D<UnsignedInt>*, Containers::StridedArrayView1D<Vector2>&), void* glyphAllocatorState, void(*runAllocator)(void*, UnsignedInt, Containers::StridedArrayView1D<Float>&, Containers::StridedArrayView1D<UnsignedInt>&), void* runAllocatorState, const RendererCoreFlags flags): _state{
/* If either allocator is left at the default, create a state that includes
the data arrays for use by the internal allocators. If both are
user-specified, there's no need to have them as they're unused. */
glyphAllocator && runAllocator ?
Containers::pointer<State>(glyphCache, glyphAllocator, glyphAllocatorState, runAllocator, runAllocatorState, flags) :
Containers::pointer<AllocatorState>(glyphCache, glyphAllocator, glyphAllocatorState, runAllocator, runAllocatorState, flags)} {}
RendererCore::RendererCore(NoCreateT) noexcept {}
RendererCore::RendererCore(RendererCore&&) noexcept = default;
RendererCore::~RendererCore() = default;
RendererCore& RendererCore::operator=(RendererCore&&) noexcept = default;
const AbstractGlyphCache& RendererCore::glyphCache() const {
return _state->glyphCache;
}
RendererCoreFlags RendererCore::flags() const {
return _state->flags;
}
UnsignedInt RendererCore::glyphCount() const {
return _state->glyphCount;
}
UnsignedInt RendererCore::glyphCapacity() const {
return _state->glyphPositions.size();
}
UnsignedInt RendererCore::runCount() const {
return _state->runCount;
}
UnsignedInt RendererCore::runCapacity() const {
return _state->runScales.size();
}
bool RendererCore::isRendering() const {
return _state->rendering;
}
UnsignedInt RendererCore::renderingGlyphCount() const {
return _state->renderingGlyphCount;
}
UnsignedInt RendererCore::renderingRunCount() const {
return _state->renderingRunCount;
}
Vector2 RendererCore::cursor() const {
return _state->cursor;
}
RendererCore& RendererCore::setCursor(const Vector2& cursor) {
State& state = *_state;
CORRADE_ASSERT(!state.rendering,
"Text::RendererCore::setCursor(): rendering in progress", *this);
state.cursor = cursor;
return *this;
}
Alignment RendererCore::alignment() const {
return _state->alignment;
}
RendererCore& RendererCore::setAlignment(const Alignment alignment) {
State& state = *_state;
CORRADE_ASSERT(!state.rendering,
"Text::RendererCore::setAlignment(): rendering in progress", *this);
state.alignment = alignment;
return *this;
}
Float RendererCore::lineAdvance() const {
return _state->lineAdvance;
}
RendererCore& RendererCore::setLineAdvance(const Float advance) {
State& state = *_state;
CORRADE_ASSERT(!state.rendering,
"Text::RendererCore::setLineAdvance(): rendering in progress", *this);
state.lineAdvance = advance;
return *this;
}
LayoutDirection RendererCore::layoutDirection() const {
return _state->layoutDirection;
}
RendererCore& RendererCore::setLayoutDirection(const LayoutDirection direction) {
State& state = *_state;
CORRADE_ASSERT(!state.rendering,
"Text::RendererCore::setLayoutDirection(): rendering in progress", *this);
CORRADE_ASSERT(direction == LayoutDirection::HorizontalTopToBottom,
"Text::RendererCore::setLayoutDirection(): only" << LayoutDirection::HorizontalTopToBottom << "is supported right now, got" << direction, *this);
state.layoutDirection = direction;
return *this;
}
Containers::StridedArrayView1D<const Vector2> RendererCore::glyphPositions() const {
const State& state = *_state;
return state.glyphPositions.prefix(state.glyphCount);
}
Containers::StridedArrayView1D<const UnsignedInt> RendererCore::glyphIds() const {
const State& state = *_state;
return state.glyphIds.prefix(state.glyphCount);
}
Containers::StridedArrayView1D<const UnsignedInt> RendererCore::glyphClusters() const {
const State& state = *_state;
CORRADE_ASSERT(state.flags & RendererCoreFlag::GlyphClusters,
"Text::RendererCore::glyphClusters(): glyph clusters not enabled", {});
return state.glyphClusters.prefix(state.glyphCount);
}
Containers::StridedArrayView1D<const Float> RendererCore::runScales() const {
const State& state = *_state;
return state.runScales.prefix(state.runCount);
}
Containers::StridedArrayView1D<const UnsignedInt> RendererCore::runEnds() const {
const State& state = *_state;
return state.runEnds.prefix(state.runCount);
}
Range1Dui RendererCore::glyphsForRuns(const Range1Dui& runRange) const {
const State& state = *_state;
CORRADE_ASSERT(runRange.min() <= state.renderingRunCount &&
runRange.max() <= state.renderingRunCount,
/* The Vector2ui is to avoid double {}s in the printed value */
/** @todo fix the printer itself, maybe? */
"Text::RendererCore::glyphsForRuns(): runs" << Debug::packed << (Vector2ui{runRange.min(), runRange.max()}) << "out of range for" << state.renderingRunCount << "runs", {});
return {runRange.min() ? state.runEnds[runRange.min() - 1] : 0,
runRange.max() ? state.runEnds[runRange.max() - 1] : 0};
}
void RendererCore::allocateGlyphs(
#ifndef CORRADE_NO_ASSERT
const char* const messagePrefix,
#endif
const UnsignedInt totalGlyphCount)
{
State& state = *_state;
/* This function should only be called if we need more memory or from
clear() with everything empty */
CORRADE_INTERNAL_DEBUG_ASSERT(totalGlyphCount > state.glyphPositions.size() || (state.glyphCount == 0 && state.renderingGlyphCount == 0 && totalGlyphCount == 0));
/* Sliced copies of the views for the allocator to update. As this is
called from add(), all glyph contents until `state.renderingGlyphCount`
should be preserved, not just `state.glyphCount`. */
Containers::StridedArrayView1D<Vector2> glyphPositions =
state.glyphPositions.prefix(state.renderingGlyphCount);
Containers::StridedArrayView1D<UnsignedInt> glyphIds =
state.glyphIds.prefix(state.renderingGlyphCount);
Containers::StridedArrayView1D<UnsignedInt> glyphClusters = state.flags & RendererCoreFlag::GlyphClusters ?
state.glyphClusters.prefix(state.renderingGlyphCount) : nullptr;
/* Advances are just temporary and thus we don't need to preserve existing
contents. But the allocator may still want to know where it's coming
from so give it a non-null empty view if possible */
Containers::StridedArrayView1D<Vector2> glyphAdvances =
state.glyphAdvances.prefix(0);
/* While this function gets total glyph count, the allocator gets glyph
count to grow by instead */
state.glyphAllocator(state.glyphAllocatorState,
totalGlyphCount - state.renderingGlyphCount,
glyphPositions,
glyphIds,
state.flags & RendererCoreFlag::GlyphClusters ? &glyphClusters : nullptr,
glyphAdvances);
/* Take the smallest size of all as the new capacity. Again the advances
don't preserve the previous contents so they're just the new size. Add
the existing glyph count to that instead of subtracting glyph count from
all others to avoid an underflow. */
std::size_t minCapacity = Math::min({
glyphPositions.size(),
glyphIds.size(),
state.renderingGlyphCount + glyphAdvances.size()});
/* These assertions are present even for the builtin allocator but
shouldn't fire. If they do, the whole thing is broken, but it's better
to blow up with a nice message than with some strange OOB error later */
if(state.flags & RendererCoreFlag::GlyphClusters) {
minCapacity = Math::min(minCapacity, glyphClusters.size());
CORRADE_ASSERT(minCapacity >= totalGlyphCount,
messagePrefix << "expected allocated glyph positions, IDs and clusters to have at least" << totalGlyphCount << "elements and advances" << totalGlyphCount - state.renderingGlyphCount << "but got" << glyphPositions.size() << Debug::nospace << "," << glyphIds.size() << Debug::nospace << "," << glyphClusters.size() << "and" << glyphAdvances.size(), );
} else {
CORRADE_ASSERT(minCapacity >= totalGlyphCount,
messagePrefix << "expected allocated glyph positions and IDs to have at least" << totalGlyphCount << "elements and advances" << totalGlyphCount - state.renderingGlyphCount << "but got" << glyphPositions.size() << Debug::nospace << "," << glyphIds.size() << "and" << glyphAdvances.size(), );
}
/* Keep just the minimal size for all, which is the new capacity */
state.glyphPositions = glyphPositions.prefix(minCapacity);
state.glyphIds = glyphIds.prefix(minCapacity);
if(state.flags & RendererCoreFlag::GlyphClusters)
state.glyphClusters = glyphClusters.prefix(minCapacity);
/* Again the advances are just the size alone, not the full capacity */
state.glyphAdvances = glyphAdvances.prefix(minCapacity - state.renderingGlyphCount);
}
void RendererCore::allocateRuns(
#ifndef CORRADE_NO_ASSERT
const char* const messagePrefix,
#endif
const UnsignedInt totalRunCount)
{
State& state = *_state;
/* This function should only be called if we need more memory or from
clear() with everything empty */
CORRADE_INTERNAL_DEBUG_ASSERT(totalRunCount > state.runScales.size() || (state.runCount == 0 && state.renderingRunCount == 0 && totalRunCount == 0));
/* Sliced copies of the views for the allocator to update. As this is
called from add(), all run contents until `state.renderingRunCount`
should be preserved, not just `state.runCount`. */
Containers::StridedArrayView1D<Float> runScales =
state.runScales.prefix(state.renderingRunCount);
Containers::StridedArrayView1D<UnsignedInt> runEnds =
state.runEnds.prefix(state.renderingRunCount);
/* While this function gets total run count, the allocator gets run count
to grow by instead */
state.runAllocator(state.runAllocatorState,
totalRunCount - state.renderingRunCount,
runScales,
runEnds);
/* Take the smallest size of all as the new capacity */
const std::size_t minCapacity = Math::min(
runScales.size(),
runEnds.size());
/* These assertions are present even for the builtin allocator but
shouldn't fire. If they do, the whole thing is broken, but it's better
to blow up with a nice message than with some strange OOB error later */
CORRADE_ASSERT(minCapacity >= totalRunCount,
messagePrefix << "expected allocated run scales and ends to have at least" << totalRunCount << "elements but got" << runScales.size() << "and" << runEnds.size(), );
/* Keep just the minimal size for all, which is the new capacity */
state.runScales = runScales.prefix(minCapacity);
state.runEnds = runEnds.prefix(minCapacity);
}
RendererCore& RendererCore::reserve(const UnsignedInt glyphCapacity, const UnsignedInt runCapacity) {
State& state = *_state;
if(state.glyphPositions.size() < glyphCapacity)
allocateGlyphs(
#ifndef CORRADE_NO_ASSERT
"Text::RendererCore::reserve():",
#endif
glyphCapacity);
if(state.runScales.size() < runCapacity)
allocateRuns(
#ifndef CORRADE_NO_ASSERT
"Text::RendererCore::reserve():",
#endif
runCapacity);
return *this;
}
RendererCore& RendererCore::clear() {
State& state = *_state;
/* Reset the glyph / run count to 0 and call the allocators, requesting 0
glyphs and runs as well. It may make use of that to refresh itself. */
state.glyphCount = 0;
state.renderingGlyphCount = 0;
state.runCount = 0;
state.renderingRunCount = 0;
allocateGlyphs(
#ifndef CORRADE_NO_ASSERT
"", /* Asserts won't happen as returned sizes will be always >= 0 */
#endif
0);
allocateRuns(
#ifndef CORRADE_NO_ASSERT
"", /* Asserts won't happen as returned sizes will be always >= 0 */
#endif
0);
/* All in-progress rendering, both for the block and for the line, should
be cleaned up */
state.rendering = false;
state.resolvedAlignment = {};
state.renderingLineStart = {};
state.renderingLineCursor = {};
state.renderingLineAdvance = {};
state.blockRunBegin = {};
state.blockRectangle = {};
state.lineGlyphBegin = {};
state.lineRectangle = {};
return *this;
}
void RendererCore::resetInternal() {
State& state = *_state;
/* Keep in sync with the initializers in the State struct */
state.alignment = Alignment::MiddleCenter;
state.layoutDirection = LayoutDirection::HorizontalTopToBottom;
state.cursor = {};
state.lineAdvance = {};
}
RendererCore& RendererCore::reset() {
clear();
/* Reset also all other settable state to defaults */
resetInternal();
return *this;
}
void RendererCore::alignAndFinishLine() {
State& state = *_state;
CORRADE_INTERNAL_DEBUG_ASSERT(state.lineGlyphBegin != state.renderingGlyphCount && state.resolvedAlignment);
const Range2D alignedLineRectangle = alignRenderedLine(
state.lineRectangle,
state.layoutDirection,
*state.resolvedAlignment,
state.glyphPositions.slice(state.lineGlyphBegin, state.renderingGlyphCount));
/* Extend the block rectangle with final line bounds */
state.blockRectangle = Math::join(state.blockRectangle, alignedLineRectangle);
/* New line starts after all existing glyphs and is empty */
state.lineGlyphBegin = state.renderingGlyphCount;
state.lineRectangle = {};
}
RendererCore& RendererCore::add(AbstractShaper& shaper, const Float size, const Containers::StringView text, const UnsignedInt begin, const UnsignedInt end, const Containers::ArrayView<const FeatureRange> features) {
State& state = *_state;
/* Mark as rendering in progress if not already */
state.rendering = true;
/* Query ID of shaper font in the cache for performing glyph ID mapping */
const Containers::Optional<UnsignedInt> glyphCacheFontId = state.glyphCache.findFont(shaper.font());
CORRADE_ASSERT(glyphCacheFontId,
"Text::RendererCore::add(): shaper font not found among" << state.glyphCache.fontCount() << "fonts in associated glyph cache", *this);
/* Scaling factor, line advance taken from the font if not specified
externally. Currently assuming just horizontal layout direction, so the
line advance is vertical. */
/** @todo update once allowing other directions */
const AbstractFont& font = shaper.font();
const Float scale = size/font.size();
CORRADE_INTERNAL_DEBUG_ASSERT(state.layoutDirection == LayoutDirection::HorizontalTopToBottom);
if(state.renderingLineAdvance == Vector2{}) {
if(state.lineAdvance != 0.0f)
state.renderingLineAdvance = Vector2::yAxis(-state.lineAdvance);
else
state.renderingLineAdvance = Vector2::yAxis(-font.lineHeight()*scale);
}
Containers::StringView line = text.slice(begin, end);
while(line) {
const Containers::StringView lineEnd = line.findOr('\n', line.end());
/* Comparing like this to avoid an unnecessary memcmp(). If we reach
the end of the input text, it's *not* an end of the line, because
the next add() call may continue with it. */
const bool isEndOfLine = lineEnd.size() == 1 && lineEnd[0] == '\n';
/* If the line is not empty and produced some glyphs, render them */
if(const UnsignedInt glyphCount = lineEnd.begin() != line.begin() ? shaper.shape(text, line.begin() - text.begin(), lineEnd.begin() - text.begin(), features) : 0) {
/* If we need to add more glyphs than what's in the capacity,
allocate more */
if(state.glyphPositions.size() < state.renderingGlyphCount + glyphCount) {
allocateGlyphs(
#ifndef CORRADE_NO_ASSERT
"Text::RendererCore::add():",
#endif
state.renderingGlyphCount + glyphCount);
#ifdef CORRADE_GRACEFUL_ASSERT
/* For testing only -- if allocation failed, bail */
if(state.glyphPositions.size() < state.renderingGlyphCount + glyphCount)
return *this;
#endif
}
const Containers::StridedArrayView1D<Vector2> glyphOffsetsPositions = state.glyphPositions.sliceSize(state.renderingGlyphCount, glyphCount);
/* The glyph advance array may be aliasing IDs and clusters. Pick
only a suffix of the same size as the remaining capacity -- that
memory is guaranteed to be unused yet. */
const std::size_t remainingCapacity = state.glyphPositions.size() - state.renderingGlyphCount;
const Containers::StridedArrayView1D<Vector2> glyphAdvances = state.glyphAdvances.sliceSize(state.glyphAdvances.size() - remainingCapacity, glyphCount);
shaper.glyphOffsetsAdvancesInto(
glyphOffsetsPositions,
glyphAdvances);
/* Render line glyph positions, aliasing the offsets */
const Range2D rectangle = renderLineGlyphPositionsInto(
shaper.font(),
size,
state.layoutDirection,
glyphOffsetsPositions,
glyphAdvances,
state.renderingLineCursor,
glyphOffsetsPositions);
/* Retrieve the glyph IDs and clusters, convert the glyph IDs to
cache-global. Do it only after finalizing the positions so the
glyphAdvances array can alias the IDs. */
const Containers::StridedArrayView1D<UnsignedInt> glyphIds = state.glyphIds.sliceSize(state.renderingGlyphCount, glyphCount);
shaper.glyphIdsInto(glyphIds);
state.glyphCache.glyphIdsInto(*glyphCacheFontId, glyphIds, glyphIds);
if(state.flags & RendererCoreFlag::GlyphClusters)
shaper.glyphClustersInto(state.glyphClusters.sliceSize(state.renderingGlyphCount, glyphCount));
/* If we're aligning based on glyph bounds, calculate a rectangle
from scratch instead of using a rectangle based on advances and
font metrics. Join the resulting rectangle with one that's
maintained for the line so far. */
state.lineRectangle = Math::join(state.lineRectangle,
(UnsignedByte(state.alignment) & Implementation::AlignmentGlyphBounds) ?
glyphQuadBounds(state.glyphCache, scale, glyphOffsetsPositions, glyphIds) :
rectangle);
state.renderingGlyphCount += glyphCount;
}
/* If the alignment isn't resolved yet and the shaper detected any
usable direction (or we're at the end of the line where we need
it), resolve it. If there's no usable direction detected yet, maybe
it will be next time. */
if(!state.resolvedAlignment) {
/* In this case it may happen that we query direction on a shaper
for which shape() wasn't called yet, for example if shaping a
text starting with \n and the previous text shaping gave back
ShapeDirection::Unspecified as well. In such case it likely
returns ShapeDirection::Unspecified too. */
const ShapeDirection shapeDirection = shaper.direction();
if(shapeDirection != ShapeDirection::Unspecified || isEndOfLine)
state.resolvedAlignment = alignmentForDirection(
state.alignment,
state.layoutDirection,
shapeDirection);
}
/* If a newline follows, wrap up the existing line. This can happen
independently of whether any glyphs were processed in this
iteration, as add() can be called with a string that starts with a
\n, for example. */
if(isEndOfLine) {
/* If there are any glyphs on the current line, either added right
above or being there from the previous add() call, align them.
If alignment based on bounds is requested, calculate a special
rectangle for it. */
if(state.lineGlyphBegin != state.renderingGlyphCount)
alignAndFinishLine();
/* Move the cursor for the next line */
state.renderingLineStart += state.renderingLineAdvance;
state.renderingLineCursor = state.renderingLineStart;
}
/* For the next iteration cut away everything that got processed,
including the \n */
line = line.suffix(lineEnd.end());
}
/* Final alignment of the whole block happens in render() below */
/* Save the whole thing as a new run, if any glyphs were added at all.
Right now it's just a single run each time add() is called, but
eventually it might get split by lines or by shaping direction. */
if((state.renderingRunCount ? state.runEnds[state.renderingRunCount - 1] : 0) < state.renderingGlyphCount) {
if(state.runScales.size() <= state.renderingRunCount) {
allocateRuns(
#ifndef CORRADE_NO_ASSERT
"Text::RendererCore::add():",
#endif
state.renderingRunCount + 1);
#ifdef CORRADE_GRACEFUL_ASSERT
/* For testing only -- if allocation failed, bail */
if(state.runScales.size() <= state.renderingRunCount)
return *this;
#endif
}
state.runScales[state.renderingRunCount] = scale;
state.runEnds[state.renderingRunCount] = state.renderingGlyphCount;
++state.renderingRunCount;
}
return *this;
}
RendererCore& RendererCore::add(AbstractShaper& shaper, const Float size, const Containers::StringView text, const UnsignedInt begin, const UnsignedInt end) {
return add(shaper, size, text, begin, end, {});
}
RendererCore& RendererCore::add(AbstractShaper& shaper, const Float size, const Containers::StringView text, const UnsignedInt begin, const UnsignedInt end, const std::initializer_list<FeatureRange> features) {
return add(shaper, size, text, begin, end, Containers::arrayView(features));
}
RendererCore& RendererCore::add(AbstractShaper& shaper, const Float size, const Containers::StringView text, const Containers::ArrayView<const FeatureRange> features) {
return add(shaper, size, text, 0, text.size(), features);
}
RendererCore& RendererCore::add(AbstractShaper& shaper, const Float size, const Containers::StringView text) {
return add(shaper, size, text, {});
}
RendererCore& RendererCore::add(AbstractShaper& shaper, const Float size, const Containers::StringView text, const std::initializer_list<FeatureRange> features) {
return add(shaper, size, text, Containers::arrayView(features));
}
Containers::Pair<Range2D, Range1Dui> RendererCore::render() {
State& state = *_state;
/* If the alignment still isn't resolved at this point, it means it either
stayed at ShapeDirection::Unspecified for all text added so far, or
there wasn't any text actually added. Go with whatever
alignmentForDirection() picks, then. Also, state.resolvedAlignment is
going to get reset right at the end, but let's just write there
temporarily, the logic is easier that way. */
if(!state.resolvedAlignment)
state.resolvedAlignment = alignmentForDirection(
state.alignment,
state.layoutDirection,
ShapeDirection::Unspecified);
/* Align the last unfinished line. In most cases there will be, unless the
last text passed to add() was ending with a \n. */
if(state.lineGlyphBegin != state.renderingGlyphCount)
alignAndFinishLine();
/* Align the block. Now it's respecting the alignment relative to the
origin, move everything relative to the actual desired cursor. Could
probably do that in the alignRendered*() by passing a specially crafted
rect that's shifted by the cursor, but that'd become a testing nightmare
with vertical text or when per-line advance is implemented. So just do
that after. */
const Containers::StridedArrayView1D<Vector2> blockGlyphPositions = state.glyphPositions.slice(state.blockRunBegin ? state.runEnds[state.blockRunBegin - 1] : 0, state.renderingRunCount ? state.runEnds[state.renderingRunCount - 1] : 0);
const Range2D alignedBlockRectangle = alignRenderedBlock(
state.blockRectangle,
state.layoutDirection,
*state.resolvedAlignment,
blockGlyphPositions);
for(Vector2& i: blockGlyphPositions)
i += state.cursor;
/* Reset all block-related state, marking the renderer as not in progress
anymore. Line-related state should be reset after the alignLine() above
already. */
const UnsignedInt blockRunBegin = state.blockRunBegin;
state.rendering = false;
state.resolvedAlignment = {};
state.renderingLineStart = {};
state.renderingLineCursor = {};
state.renderingLineAdvance = {};
CORRADE_INTERNAL_DEBUG_ASSERT(state.lineGlyphBegin == state.renderingGlyphCount &&
state.lineRectangle == Range2D{});
state.glyphCount = state.renderingGlyphCount;
state.runCount = state.renderingRunCount;
state.blockRunBegin = state.runCount;
state.blockRectangle = {};
return {alignedBlockRectangle.translated(state.cursor), {blockRunBegin, state.runCount}};
}
Containers::Pair<Range2D, Range1Dui> RendererCore::render(AbstractShaper& shaper, const Float size, const Containers::StringView text, const Containers::ArrayView<const FeatureRange> features) {
add(shaper, size, text, features);
return render();
}
Containers::Pair<Range2D, Range1Dui> RendererCore::render(AbstractShaper& shaper, const Float size, const Containers::StringView text) {
return render(shaper, size, text, {});
}
Containers::Pair<Range2D, Range1Dui> RendererCore::render(AbstractShaper& shaper, const Float size, const Containers::StringView text, const std::initializer_list<FeatureRange> features) {
return render(shaper, size, text, Containers::arrayView(features));
}
Range2D renderLineGlyphPositionsInto(const AbstractFont& font, const Float size, const LayoutDirection direction, const Containers::StridedArrayView1D<const Vector2>& glyphOffsets, const Containers::StridedArrayView1D<const Vector2>& glyphAdvances, Vector2& cursor, const Containers::StridedArrayView1D<Vector2>& glyphPositions) { Range2D renderLineGlyphPositionsInto(const AbstractFont& font, const Float size, const LayoutDirection direction, const Containers::StridedArrayView1D<const Vector2>& glyphOffsets, const Containers::StridedArrayView1D<const Vector2>& glyphAdvances, Vector2& cursor, const Containers::StridedArrayView1D<Vector2>& glyphPositions) {
CORRADE_ASSERT(glyphAdvances.size() == glyphOffsets.size() && CORRADE_ASSERT(glyphAdvances.size() == glyphOffsets.size() &&
glyphPositions.size() == glyphOffsets.size(), glyphPositions.size() == glyphOffsets.size(),

569
src/Magnum/Text/Renderer.h

@ -27,9 +27,12 @@
*/ */
/** @file /** @file
* @brief Class @ref Magnum::Text::AbstractRenderer, typedef @ref Magnum::Text::Renderer2D, @ref Magnum::Text::Renderer3D, function @ref Magnum::Text::renderLineGlyphPositionsInto(), @ref Magnum::Text::renderGlyphQuadsInto(), @ref Magnum::Text::glyphQuadBounds(), @ref Magnum::Text::alignRenderedLine(), @ref Magnum::Text::alignRenderedBlock(), @ref Magnum::Text::renderGlyphQuadIndicesInto(), @ref Magnum::Text::glyphRangeForBytes() * @brief Class @ref Magnum::Text::RendererCore, @ref Magnum::Text::AbstractRenderer, typedef @ref Magnum::Text::Renderer2D, @ref Magnum::Text::Renderer3D, function @ref Magnum::Text::renderLineGlyphPositionsInto(), @ref Magnum::Text::renderGlyphQuadsInto(), @ref Magnum::Text::glyphQuadBounds(), @ref Magnum::Text::alignRenderedLine(), @ref Magnum::Text::alignRenderedBlock(), @ref Magnum::Text::renderGlyphQuadIndicesInto(), @ref Magnum::Text::glyphRangeForBytes()
*/ */
#include <initializer_list>
#include <Corrade/Containers/Pointer.h>
#include "Magnum/Magnum.h" #include "Magnum/Magnum.h"
#include "Magnum/Text/Text.h" #include "Magnum/Text/Text.h"
#include "Magnum/Text/visibility.h" #include "Magnum/Text/visibility.h"
@ -52,6 +55,570 @@
namespace Magnum { namespace Text { namespace Magnum { namespace Text {
/**
@brief Text renderer core flag
@m_since_latest
@see @ref RendererFlags, @ref Renderer
*/
enum class RendererCoreFlag: UnsignedByte {
/**
* Populate glyph cluster info in @ref RendererCore::glyphClusters() for
* text selection and editing purposes.
*/
GlyphClusters = 1 << 0,
};
/**
* @debugoperatorenum{RendererCoreFlag}
* @m_since_latest
*/
MAGNUM_TEXT_EXPORT Debug& operator<<(Debug& output, RendererCoreFlag value);
/**
@brief Text renderer core flags
@m_since_latest
@see @ref Renderer
*/
typedef Containers::EnumSet<RendererCoreFlag> RendererCoreFlags;
CORRADE_ENUMSET_OPERATORS(RendererCoreFlags)
/**
* @debugoperatorenum{RendererCoreFlags}
* @m_since_latest
*/
MAGNUM_TEXT_EXPORT Debug& operator<<(Debug& output, RendererCoreFlags value);
/**
@brief Text renderer core
@m_since_latest
*/
class MAGNUM_TEXT_EXPORT RendererCore {
public:
/**
* @brief Construct
* @param glyphCache Glyph cache to use for glyph ID mapping
* @param flags Opt-in feature flags
*
* By default, the renderer allocates the memory for glyph and run data
* internally. Use the overload below to supply external allocators.
* @todoc the damn thing can't link to functions taking functions
*/
explicit RendererCore(const AbstractGlyphCache& glyphCache, RendererCoreFlags flags = {}): RendererCore{glyphCache, nullptr, nullptr, nullptr, nullptr, flags} {}
/**
* @brief Construct with external allocators
* @param glyphCache Glyph cache to use for glyph ID mapping
* @param glyphAllocator Glyph allocator function or
* @cpp nullptr @ce
* @param glyphAllocatorState State pointer to pass to
* @p glyphAllocator
* @param runAllocator Run allocator function or @cpp nullptr @ce
* @param runAllocatorState State pointer to pass to @p runAllocator
* @param flags Opt-in feature flags
*
* The @p glyphAllocator gets called with desired @p glyphCount every
* time @ref glyphCount() reaches @ref glyphCapacity(). Size of
* passed-in @p glyphPositions, @p glyphIds and @p glyphClusters views
* matches @ref glyphCount(). The @p glyphAdvances view is a temporary
* storage with contents that don't need to be preserved on
* reallocation and is thus passed in empty. If the renderer wasn't
* constructed with @ref RendererCoreFlag::GlyphClusters, the
* @p glyphClusters is @cpp nullptr @ce to indicate it's not meant to
* be allocated. The allocator is expected to replace all passed views
* with new views that are larger by *at least* @p glyphCount, pointing
* to a reallocated memory with contents from the original view
* preserved. Initially @ref glyphCount() is @cpp 0 @ce and the views
* are all passed in empty, every subsequent time the views match a
* prefix of views previously returned by the allocator. To save
* memory, the renderer guarantees that @p glyphIds and
* @p glyphClusters are only filled once @p glyphAdvances were merged
* into @p glyphPositions. In other words, the @p glyphAdvances can
* alias a suffix of @p glyphIds and @p glyphClusters.
*
* The @p runAllocator gets called with desired @p runCount every time
* @ref runCount() reaches @ref runCapacity(). Size of passed-in
* @p runScales and @p runEnds views matches @ref runCount(). The
* allocator is expected to replace the views with new views that are
* larger by *at least* @p runCount, pointing to a reallocated memory
* with contents from the original views preserved. Initially
* @ref runCount() is @cpp 0 @ce and the views are passed in empty,
* every subsequent time the views match a prefix of views previously
* returned by the allocator.
*
* The renderer always requests only exactly the desired size and the
* growth strategy is up to the allocators themselves --- the returned
* views can be larger than requested and aren't all required to all
* have the same size. The minimum of size increases across all views
* is then treated as the new @ref glyphCapacity() / @ref runCapacity().
*
* As a special case, when @ref clear() or @ref reset() is called, the
* allocators are called with empty views and @p glyphCount /
* @p runCount being @cpp 0 @ce. This is to allow the allocators to
* perform any needed reset as well.
*
* If @p glyphAllocator or @p runAllocator is @cpp nullptr @ce,
* @p glyphAllocatorState or @p runAllocatorState is ignored and
* default builtin allocator get used for either. Passing
* @cpp nullptr @ce for both is equivalent to calling the
* @ref RendererCore(const AbstractGlyphCache&, RendererCoreFlags)
* constructor.
*/
explicit RendererCore(const AbstractGlyphCache& glyphCache, void(*glyphAllocator)(void* state, UnsignedInt glyphCount, Containers::StridedArrayView1D<Vector2>& glyphPositions, Containers::StridedArrayView1D<UnsignedInt>& glyphIds, Containers::StridedArrayView1D<UnsignedInt>* glyphClusters, Containers::StridedArrayView1D<Vector2>& glyphAdvances), void* glyphAllocatorState, void(*runAllocator)(void* state, UnsignedInt runCount, Containers::StridedArrayView1D<Float>& runScales, Containers::StridedArrayView1D<UnsignedInt>& runEnds), void* runAllocatorState, RendererCoreFlags flags = {});
/**
* @brief Construct without creating the internal state
* @m_since_latest
*
* The constructed instance is equivalent to moved-from state, i.e. no
* APIs can be safely called on the object. Useful in cases where you
* will overwrite the instance later anyway. Move another object over
* it to make it useful.
*
* Note that this is a low-level and a potentially dangerous API, see
* the documentation of @ref NoCreate for alternatives.
*/
explicit RendererCore(NoCreateT) noexcept;
/** @brief Copying is not allowed */
RendererCore(RendererCore&) = delete;
/**
* @brief Move constructor
*
* Performs a destructive move, i.e. the original object isn't usable
* afterwards anymore.
*/
RendererCore(RendererCore&&) noexcept;
~RendererCore();
/** @brief Copying is not allowed */
RendererCore& operator=(RendererCore&) = delete;
/** @brief Move assignment */
RendererCore& operator=(RendererCore&&) noexcept;
/** @brief Glyph cache associated with the renderer */
const AbstractGlyphCache& glyphCache() const;
/** @brief Flags */
RendererCoreFlags flags() const;
/**
* @brief Total count of rendered glyphs
*
* Does *not* include glyphs from the current in-progress rendering, if
* any, as their contents are not finalized yet. Use
* @ref renderingGlyphCount() to query the count including the
* in-progress glyphs.
* @see @ref isRendering(), @ref runCount()
*/
UnsignedInt glyphCount() const;
/**
* @brief Glyph capacity
*
* @see @ref glyphCount(), @ref runCapacity(), @ref reserve()
*/
UnsignedInt glyphCapacity() const;
/**
* @brief Total count of rendered runs
*
* Does *not* include runs from the current in-progress rendering, if
* any, as their contents are not finalized yet. Use
* @ref renderingRunCount() to query the count including the
* in-progress runs.
* @see @ref isRendering(), @ref glyphCount()
*/
UnsignedInt runCount() const;
/**
* @brief Run capacity
*
* @see @ref runCount(), @ref glyphCapacity() @ref reserve()
*/
UnsignedInt runCapacity() const;
/**
* @brief Whether text rendering is currently in progress
*
* Returns @cpp true @ce if there are any @ref add() calls not yet
* followed by a @ref render(), @cpp false @ce otherwise. If rendering
* is in progress, @ref setCursor(), @ref setAlignment() and
* @ref setLayoutDirection() cannot be called. The @ref glyphCount(),
* @ref runCount() and all data accessors don't include the
* yet-to-be-finalized contents.
*/
bool isRendering() const;
/**
* @brief Total count of glyphs including current in-progress rendering
*
* Can be used for example to query which glyphs correspond to the last
* @ref add() call. If @ref isRendering() is @cpp false @ce, the
* returned value is the same as @ref glyphCount().
*/
UnsignedInt renderingGlyphCount() const;
/**
* @brief Total count of runs including current in-progress rendering
*
* Can be used for example to query which runs correspond to the last
* @ref add() call. If @ref isRendering() is @cpp false @ce, the
* returned value is the same as @ref runCount().
*/
UnsignedInt renderingRunCount() const;
/**
* @brief Cursor position
*
* Note that this does *not* return the current position at which an
* in-progress rendering is happening --- the way the glyphs get placed
* before they're aligned to their final position is internal to the
* implementation and querying such in-progress state would be of
* little use.
*/
Vector2 cursor() const;
/**
* @brief Set cursor position for the next rendered text
* @return Reference to self (for method chaining)
*
* The next rendered text is placed according to specified @p cursor,
* @ref alignment() and @ref lineAdvance(). Expects that rendering is
* currently not in progress, meaning that the cursor can be only
* specified before rendering a particular piece of text. Initial value
* is @cpp {0.0f, 0.0f} @ce.
* @see @ref isRendering()
*/
RendererCore& setCursor(const Vector2& cursor);
/** @brief Text alignment */
Alignment alignment() const;
/**
* @brief Set alignment for the next rendered text
* @return Reference to self (for method chaining)
*
* The next rendered text is placed according to specified
* @ref cursor(), @p alignment and @ref lineAdvance(). Expects that
* rendering is currently not in progress, meaning that the alignment
* can be only specified before rendering a particular piece of text.
* Initial value is @ref Alignment::MiddleCenter.
* @see @ref isRendering()
*/
RendererCore& setAlignment(Alignment alignment);
/** @brief Line advance */
Float lineAdvance() const;
/**
* @brief Set line advance for the next rendered text
* @return Reference to self (for method chaining)
*
* The next rendered text is placed according to specified
* @ref cursor(), @ref alignment and @p advance. The advance value is
* used according to @ref layoutDirection() and in a coordinate system
* matching @ref AbstractFont::ascent() and
* @relativeref{AbstractFont,descent()}, so for example causes the next
* line to be shifted in a negative Y direction for
* @ref LayoutDirection::HorizontalTopToBottom. Expects that rendering
* is currently not in progress, meaning that the line advance can be
* only specified before rendering a particular piece of text. If set
* to @cpp 0.0f @ce, the line advance is picked metrics of the first
* font a corresponding size passed to @ref add().
* @see @ref isRendering(), @ref AbstractFont::lineHeight()
*/
RendererCore& setLineAdvance(Float advance);
/** @brief Layout direction */
LayoutDirection layoutDirection() const;
/**
* @brief Set layout direction
* @return Reference to self (for method chaining)
*
* Expects that rendering is currently not in progress. Currently
* expected to always be @ref LayoutDirection::HorizontalTopToBottom.
* Initial value is @ref LayoutDirection::HorizontalTopToBottom.
* @see @ref isRendering()
*/
RendererCore& setLayoutDirection(LayoutDirection direction);
/**
* @brief Glyph positions
*
* The returned view has a size of @ref glyphCount(). Note that the
* contents are not guaranteed to be meaningful if custom glyph
* allocator is used, as the user code is free to perform subsequent
* operations on those.
*/
Containers::StridedArrayView1D<const Vector2> glyphPositions() const;
/**
* @brief Glyph IDs
*
* The returned view has a size of @ref glyphCount(). Note that the
* contents are not guaranteed to be meaningful if custom glyph
* allocator is used, as the user code is free to perform subsequent
* operations on those.
*/
Containers::StridedArrayView1D<const UnsignedInt> glyphIds() const;
/**
* @brief Glyph cluster IDs
*
* Expects that the renderer was constructed with
* @ref RendererCoreFlag::GlyphClusters. The returned view has a size
* of @ref glyphCount(). Note that the contents are not guaranteed to
* be meaningful if custom glyph allocator is used, as the user code is
* free to perform subsequent operations on those.
*/
Containers::StridedArrayView1D<const UnsignedInt> glyphClusters() const;
/**
* @brief Text run scales
*
* The returned view has a size of @ref runCount(). Note that the
* contents are not guaranteed to be meaningful if custom run allocator
* is used, as the user code is free to perform subsequent operations
* on those.
*/
Containers::StridedArrayView1D<const Float> runScales() const;
/**
* @brief Text run end glyph offsets
*
* The returned view has a size of @ref runCount(), the last value is
* equal to @ref glyphCount(), and the values index the
* @ref glyphPositions(), @ref glyphIds() and @ref glyphClusters()
* views. The first text run glyphs start at offset @cpp 0 @ce and end
* at @cpp runEnds()[0] @ce, the second text run glyphs start at offset
* @cpp runEnds()[0] @ce and end at @cpp runEnds()[1] @ce, etc. See
* also the @ref glyphsForRuns() function which provides a convenient
* way to get a range of glyphs corresponding to a range of runs
* without having to deal with edge cases.
*
* Note that the contents of the returned view are not guaranteed to be
* meaningful if custom run allocator is used, as the user code is free
* to perform subsequent operations on those.
*/
Containers::StridedArrayView1D<const UnsignedInt> runEnds() const;
/**
* @brief Range of glyphs corresponding to a range of runs
*
* With @p runRange being for example the second value returned by
* @ref render(), returns a begin and end glyph offset for given run
* range, which can then be used to index the @ref glyphPositions(),
* @ref glyphIds() and @ref glyphClusters() views. Expects that both
* the min and max @p runRange value are less than or equal to
* @ref renderingRunCount().
*
* Note that the returned value is not guaranteed to be meaningful if
* custom run allocator is used, as the user code is free to perform
* subsequent operations on the run data.
* @see @ref runEnds()
*/
Range1Dui glyphsForRuns(const Range1Dui& runRange) const;
/**
* @brief Reserve capacity for given glyph and run count
* @return Reference to self (for method chaining)
*
* @see @ref glyphCapacity(), @ref glyphCount(),
* @ref runCapacity(), @ref runCount()
*/
RendererCore& reserve(UnsignedInt glyphCapacity, UnsignedInt runCapacity);
/**
* @brief Clear rendered glyphs and runs
* @return Reference to self (for method chaining)
*
* The @ref glyphCount() and @ref runCount() becomes @cpp 0 @ce after
* this call and any in-progress rendering is discarded, making
* @ref isRendering() return @cpp false @ce. If custom glyph or run
* allocators are used, they get called with empty views and zero
* sizes.
*
* Depending on allocator used, @ref glyphCapacity() and
* @ref runCapacity() may stay non-zero. The @ref cursor(),
* @ref alignment(), @ref lineAdvance() and @ref layoutDirection() are
* left untouched, use @ref reset() to reset those to their default
* values as well.
*/
RendererCore& clear();
/**
* @brief Reset internal renderer state
* @return Reference to self (for method chaining)
*
* Calls @ref clear(), and additionally @ref cursor(),
* @ref alignment(), @ref lineAdvance() and @ref layoutDirection() are
* reset to their default values. Apart from @ref glyphCapacity() and
* @ref runCapacity(), which may stay non-zero depending on allocator
* used, the instance is equivalent to a default-constructed state.
*/
RendererCore& reset();
/**
* @brief Add to the currently rendered text
* @param shaper Shaper instance to render with
* @param size Font size
* @param text Text in UTF-8
* @param begin Beginning byte in the input text
* @param end (One byte after) the end byte in the input text
* @param features Typographic features to apply for the whole text or
* its subranges
* @return Reference to self (for method chaining)
*
* Splits @p text into individual lines and shapes each with given
* @p shaper. Places and aligns the text according to @ref cursor(),
* @ref alignment() and @ref layoutDirection(), continuing from the
* state left after the previous @ref add(), if any.
*
* After calling this function, @ref isRendering() returns
* @cpp true @ce, @ref renderingGlyphCount() and @ref renderingRunCount()
* are updated with the count of newly added glyphs and runs, and
* @ref setCursor(), @ref setAlignment() or @ref setLayoutDirection()
* cannot be called anymore. Call @ref add() more times and wrap up
* with @ref render() to perform the final alignment and other steps
* necessary to finalize the rendering. If you only need to render the
* whole text at once, you can use
* @ref render(AbstractShaper&, Float, Containers::StringView, Containers::ArrayView<const FeatureRange>)
* instead.
*
* The function assumes that the @p shaper has either appropriate
* script, language and shape direction set, or has them left at
* defaults in order let them be autodetected. In order to allow the
* implementation to perform shaping aware of surrounding context, such
* as picking correct glyphs for beginning, middle or end of a word or a
* paragraph, the individual @ref add() calls should ideally be made
* with the same @p text view and the slices defined by @p begin and
* @p end. Use the @ref add(AbstractShaper&, Float, Containers::StringView, Containers::ArrayView<const FeatureRange>)
* overload to pass a string as a whole.
*
* The function uses @ref AbstractShaper::shape(),
* @ref renderLineGlyphPositionsInto(), @ref alignRenderedLine() and
* @ref glyphQuadBounds() internally, see their documentation for more
* information.
*/
#ifdef DOXYGEN_GENERATING_OUTPUT
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, UnsignedInt begin, UnsignedInt end, Containers::ArrayView<const FeatureRange> features = {});
#else
/* To not have to include ArrayView */
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, UnsignedInt begin, UnsignedInt end);
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, UnsignedInt begin, UnsignedInt end, Containers::ArrayView<const FeatureRange> features);
#endif
/** @overload */
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, UnsignedInt begin, UnsignedInt end, std::initializer_list<FeatureRange> features);
/**
* @brief Add a whole string to the currently rendered text
*
* Equivalent to @ref add(AbstractShaper&, Float, Containers::StringView, UnsignedInt, UnsignedInt, Containers::ArrayView<const FeatureRange>)
* with @p begin set to @cpp 0 @ce and @p end to size of @p text.
*/
#ifdef DOXYGEN_GENERATING_OUTPUT
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, Containers::ArrayView<const FeatureRange> features = {});
#else
/* To not have to include ArrayView */
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text);
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, Containers::ArrayView<const FeatureRange> features);
#endif
/** @overload */
RendererCore& add(AbstractShaper& shaper, Float size, Containers::StringView text, std::initializer_list<FeatureRange> features);
/**
* @brief Wrap up rendering of all text added so far
*
* Performs a final alignment of the text block added by preceding
* @ref add() calls and wraps up the rendering. After calling this
* function, @ref isRendering() returns @cpp false @ce,
* @ref glyphCount() and @ref runCount() are updated with the count of
* all rendered glyphs and runs, and @ref setCursor(),
* @ref setAlignment() or @ref setLayoutDirection() can be called again
* for the next text to be rendered.
*
* The function returns a bounding box and a range of runs of the
* currently rendered text, the run range can then be used to index
* the @ref runScales() and @ref runEnds() views. Note that it's
* possible for the render to produce an empty range, such as when an
* empty text was passed or when it was just newlines. You can use
* @ref glyphsForRuns() to convert the returned run range to a begin
* and end glyph offset, which can be then used to index the
* @ref glyphPositions(), @ref glyphIds() and @ref glyphClusters()
* views.
*
* The rendered glyph range is not touched or used by the renderer in
* any way afterwards. If the renderer was created with custom
* allocators, the caller can thus perform further operations on the
* allocated data.
*
* Use @ref clear() or @ref reset() to discard all text rendered so
* far. The function uses @ref alignRenderedBlock() internally, see its
* documentation for more information.
*/
Containers::Pair<Range2D, Range1Dui> render();
/**
* @brief Render a whole text at once
*
* A convenience shortcut for rendering a single piece of text that's
* equivalent to calling @ref add(AbstractShaper&, Float, Containers::StringView, Containers::ArrayView<const FeatureRange>)
* followed by @ref render(). See their documentation for more
* information.
*
* After calling this function, @ref isRendering() returns
* @cpp false @ce. If this function is called while rendering is in
* progress, the glyphs rendered so far are included in the result as
* well.
*/
#ifdef DOXYGEN_GENERATING_OUTPUT
Containers::Pair<Range2D, Range1Dui> render(AbstractShaper& shaper, Float size, Containers::StringView text, Containers::ArrayView<const FeatureRange> features = {});
#else
/* To not have to include ArrayView */
Containers::Pair<Range2D, Range1Dui> render(AbstractShaper& shaper, Float size, Containers::StringView text);
Containers::Pair<Range2D, Range1Dui> render(AbstractShaper& shaper, Float size, Containers::StringView text, Containers::ArrayView<const FeatureRange> features);
#endif
/** @overload */
Containers::Pair<Range2D, Range1Dui> render(AbstractShaper& shaper, Float size, Containers::StringView text, std::initializer_list<FeatureRange> features);
#ifdef DOXYGEN_GENERATING_OUTPUT
private:
#else
protected:
#endif
struct State;
struct AllocatorState;
Containers::Pointer<State> _state;
/* Called by reset() */
MAGNUM_TEXT_LOCAL void resetInternal();
private:
/* While the allocators get just size to grow by, these functions get
the total count */
MAGNUM_TEXT_LOCAL void allocateGlyphs(
#ifndef CORRADE_NO_ASSERT
const char* messagePrefix,
#endif
UnsignedInt totalGlyphCount);
MAGNUM_TEXT_LOCAL void allocateRuns(
#ifndef CORRADE_NO_ASSERT
const char* messagePrefix,
#endif
UnsignedInt totalRunCount);
MAGNUM_TEXT_LOCAL void alignAndFinishLine();
};
/** /**
@brief Render glyph positions for a (part of a) single line @brief Render glyph positions for a (part of a) single line
@param[in] font Font to query metrics from @param[in] font Font to query metrics from

3320
src/Magnum/Text/Test/RendererTest.cpp

File diff suppressed because it is too large Load Diff

2
src/Magnum/Text/Text.h

@ -56,6 +56,8 @@ enum class Script: UnsignedInt;
class FeatureRange; class FeatureRange;
class RendererCore;
#ifdef MAGNUM_TARGET_GL #ifdef MAGNUM_TARGET_GL
class DistanceFieldGlyphCacheGL; class DistanceFieldGlyphCacheGL;
class GlyphCacheGL; class GlyphCacheGL;

Loading…
Cancel
Save