You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

234 lines
9.8 KiB

/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022, 2023 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 "MagnumFont.h"
#include <sstream>
#include <unordered_map>
#include <Corrade/Containers/Array.h>
#include <Corrade/Containers/GrowableArray.h>
#include <Corrade/Containers/Optional.h>
#include <Corrade/Containers/Pair.h>
#include <Corrade/Containers/StridedArrayView.h>
#include <Corrade/Containers/Triple.h>
Text: new AbstractShaper interface for shaping. Replaces the previous, grossly inefficient AbstractLayouter which was performing one virtual call per glyph (!). It's now also reusable, meaning it doesn't need to be allocated anew for every new shaped text, and it no longer requires each and every font plugin to implement the same redundant glyph data fetching from the glyph cache, scaling etc. -- all that is meant to be done by the users of AbstractShaper, i.e. Renderer. The independency on a glyph cache theorerically also means it can be used for a completely different, non-texture-based way to render text (such as direct path drawing directly on the GPU), although I won't be exploring that path now. It also exposes an interface for specifying script, language, direction and typographic features. Such interface will be currently only implemented in HarfBuzz, but that's the intent -- to provide a flexible enough interface to support all possible use cases that a font or a font plugin may support, instead of exposing a least common denominator and then having no easy way to shape a text in a non-Latin script or use a fancy OpenType feature the chosen font has. The old public interface is preserved for backwards compatibility, marked as deprecated, however the virtual APIs are not, as supporting that would be too nasty. I don't think any user code ever implemented a font plugin so this should be okay. To ensure smooth transition with no regressions, the Renderer class and MagnumFont tests still use the old API in this commit, and their test pass the same way as they did before (except for two removed MagnumFont test cases which tested errors that are now an assertion in the deprecated layout() API and thus cannot be tested from the plugin anymore). Porting them away from the deprecated API will be done in separate commits.
3 years ago
#include <Corrade/Utility/Algorithms.h>
#include <Corrade/Utility/Configuration.h>
#include <Corrade/Utility/Path.h>
#include <Corrade/Utility/Unicode.h>
#include "Magnum/ImageView.h"
#include "Magnum/Math/ConfigurationValue.h"
Text: new AbstractShaper interface for shaping. Replaces the previous, grossly inefficient AbstractLayouter which was performing one virtual call per glyph (!). It's now also reusable, meaning it doesn't need to be allocated anew for every new shaped text, and it no longer requires each and every font plugin to implement the same redundant glyph data fetching from the glyph cache, scaling etc. -- all that is meant to be done by the users of AbstractShaper, i.e. Renderer. The independency on a glyph cache theorerically also means it can be used for a completely different, non-texture-based way to render text (such as direct path drawing directly on the GPU), although I won't be exploring that path now. It also exposes an interface for specifying script, language, direction and typographic features. Such interface will be currently only implemented in HarfBuzz, but that's the intent -- to provide a flexible enough interface to support all possible use cases that a font or a font plugin may support, instead of exposing a least common denominator and then having no easy way to shape a text in a non-Latin script or use a fancy OpenType feature the chosen font has. The old public interface is preserved for backwards compatibility, marked as deprecated, however the virtual APIs are not, as supporting that would be too nasty. I don't think any user code ever implemented a font plugin so this should be okay. To ensure smooth transition with no regressions, the Renderer class and MagnumFont tests still use the old API in this commit, and their test pass the same way as they did before (except for two removed MagnumFont test cases which tested errors that are now an assertion in the deprecated layout() API and thus cannot be tested from the plugin anymore). Porting them away from the deprecated API will be done in separate commits.
3 years ago
#include "Magnum/Text/AbstractShaper.h"
#include "Magnum/Text/GlyphCache.h"
#include "Magnum/Trade/ImageData.h"
#include "MagnumPlugins/TgaImporter/TgaImporter.h"
namespace Magnum { namespace Text {
struct MagnumFont::Data {
/* Otherwise Clang complains about Utility::Configuration having explicit
constructor when emplace()ing the Pointer. Using = default works on
newer Clang but not older versions. */
explicit Data() {}
Utility::Configuration conf;
Containers::Optional<Trade::ImageData2D> image;
Containers::Optional<Containers::String> filePath;
std::unordered_map<char32_t, UnsignedInt> glyphId;
struct Glyph {
Vector2i size;
Vector2 advance;
};
Containers::Array<Glyph> glyphs;
};
MagnumFont::MagnumFont(): _opened(nullptr) {}
MagnumFont::MagnumFont(PluginManager::AbstractManager& manager, const Containers::StringView& plugin): AbstractFont{manager, plugin}, _opened(nullptr) {}
MagnumFont::~MagnumFont() { close(); }
FontFeatures MagnumFont::doFeatures() const { return FontFeature::OpenData|FontFeature::FileCallback|FontFeature::PreparedGlyphCache; }
bool MagnumFont::doIsOpened() const { return _opened && _opened->image; }
void MagnumFont::doClose() { _opened = nullptr; }
auto MagnumFont::doOpenData(const Containers::ArrayView<const char> data, const Float) -> Properties {
if(!_opened) _opened.emplace();
if(!_opened->filePath && !fileCallback()) {
Error{} << "Text::MagnumFont::openData(): the font can be opened only from the filesystem or if a file callback is present";
return {};
}
/* Open the configuration file */
/* MSVC 2017 requires explicit std::string constructor. MSVC 2015 doesn't. */
std::istringstream in(std::string{data.begin(), data.size()});
Utility::Configuration conf(in, Utility::Configuration::Flag::SkipComments);
if(!conf.isValid() || conf.isEmpty()) {
Error{} << "Text::MagnumFont::openData(): font file is not valid";
return {};
}
/* Check version */
if(conf.value<UnsignedInt>("version") != 1) {
Error() << "Text::MagnumFont::openData(): unsupported file version, expected 1 but got"
<< conf.value<UnsignedInt>("version");
return {};
}
/* Open and load image file. Error messages should be printed by the
TgaImporter already, no need to repeat them again. */
Trade::TgaImporter importer;
importer.setFileCallback(fileCallback(), fileCallbackUserData());
if(!importer.openFile(Utility::Path::join(_opened->filePath ? *_opened->filePath : "", conf.value("image")))) return {};
_opened->image = importer.image2D(0);
if(!_opened->image) return {};
/* Everything okay, save the data internally */
_opened->conf = Utility::move(conf);
/* Glyph advances */
const std::vector<Utility::ConfigurationGroup*> glyphs = _opened->conf.groups("glyph");
_opened->glyphs = Containers::Array<Data::Glyph>{NoInit, glyphs.size()};
for(std::size_t i = 0; i != glyphs.size(); ++i)
_opened->glyphs[i] = {
glyphs[i]->value<Range2Di>("rectangle").size(),
glyphs[i]->value<Vector2>("advance")
};
/* Fill character->glyph map */
const std::vector<Utility::ConfigurationGroup*> chars = _opened->conf.groups("char");
for(const Utility::ConfigurationGroup* const c: chars) {
const UnsignedInt glyphId = c->value<UnsignedInt>("glyph");
CORRADE_INTERNAL_ASSERT(glyphId < _opened->glyphs.size());
_opened->glyphId.emplace(c->value<char32_t>("unicode"), glyphId);
}
return {_opened->conf.value<Float>("fontSize"),
_opened->conf.value<Float>("ascent"),
_opened->conf.value<Float>("descent"),
_opened->conf.value<Float>("lineHeight"),
UnsignedInt(glyphs.size())};
}
auto MagnumFont::doOpenFile(const Containers::StringView filename, const Float size) -> Properties {
_opened.emplace();
_opened->filePath.emplace(Utility::Path::split(filename).first());
return AbstractFont::doOpenFile(filename, size);
}
UnsignedInt MagnumFont::doGlyphId(const char32_t character) {
auto it = _opened->glyphId.find(character);
return it != _opened->glyphId.end() ? it->second : 0;
}
Vector2 MagnumFont::doGlyphSize(const UnsignedInt glyph) {
return Vector2{_opened->glyphs[glyph].size};
}
Vector2 MagnumFont::doGlyphAdvance(const UnsignedInt glyph) {
return _opened->glyphs[glyph].advance;
}
Containers::Pointer<AbstractGlyphCache> MagnumFont::doCreateGlyphCache() {
/* Set cache image */
Containers::Pointer<GlyphCache> cache{InPlaceInit,
_opened->conf.value<Vector2i>("originalImageSize"),
_opened->image->size(),
_opened->conf.value<Vector2i>("padding")};
/* Copy the opened image data directly to the GL texture because (unlike
image()) it matches the actual image size if it differs from
originalImageSize. A potential other way would be to create a
DistanceFieldGlyphCache instead, and call setDistanceFieldImage() on it,
but the font file itself doesn't contain any info about whether it
actually is a distance field, so that would be not really any better. */
/** @todo clean this up once there's a way to upload the processed image
directly from the base class */
cache->texture().setSubImage(0, {}, *_opened->image);
const std::vector<Utility::ConfigurationGroup*> glyphs = _opened->conf.groups("glyph");
/* Set the global invalid glyph to the same as the per-font invalid
glyph. */
if(!glyphs.empty())
cache->setInvalidGlyph(glyphs[0]->value<Vector2i>("position"), glyphs[0]->value<Range2Di>("rectangle"));
/* Add a font, fill the glyph map */
const UnsignedInt fontId = cache->addFont(glyphs.size(), this);
for(std::size_t i = 0; i < glyphs.size(); ++i)
cache->addGlyph(fontId, i, glyphs[i]->value<Vector2i>("position"), glyphs[i]->value<Range2Di>("rectangle"));
/* GCC 4.8 needs extra help here */
return Containers::Pointer<AbstractGlyphCache>{Utility::move(cache)};
}
Text: new AbstractShaper interface for shaping. Replaces the previous, grossly inefficient AbstractLayouter which was performing one virtual call per glyph (!). It's now also reusable, meaning it doesn't need to be allocated anew for every new shaped text, and it no longer requires each and every font plugin to implement the same redundant glyph data fetching from the glyph cache, scaling etc. -- all that is meant to be done by the users of AbstractShaper, i.e. Renderer. The independency on a glyph cache theorerically also means it can be used for a completely different, non-texture-based way to render text (such as direct path drawing directly on the GPU), although I won't be exploring that path now. It also exposes an interface for specifying script, language, direction and typographic features. Such interface will be currently only implemented in HarfBuzz, but that's the intent -- to provide a flexible enough interface to support all possible use cases that a font or a font plugin may support, instead of exposing a least common denominator and then having no easy way to shape a text in a non-Latin script or use a fancy OpenType feature the chosen font has. The old public interface is preserved for backwards compatibility, marked as deprecated, however the virtual APIs are not, as supporting that would be too nasty. I don't think any user code ever implemented a font plugin so this should be okay. To ensure smooth transition with no regressions, the Renderer class and MagnumFont tests still use the old API in this commit, and their test pass the same way as they did before (except for two removed MagnumFont test cases which tested errors that are now an assertion in the deprecated layout() API and thus cannot be tested from the plugin anymore). Porting them away from the deprecated API will be done in separate commits.
3 years ago
Containers::Pointer<AbstractShaper> MagnumFont::doCreateShaper() {
struct Shaper: AbstractShaper {
using AbstractShaper::AbstractShaper;
UnsignedInt doShape(const Containers::StringView textFull, const UnsignedInt begin, const UnsignedInt end, Containers::ArrayView<const FeatureRange>) override {
const Data& fontData = *static_cast<const MagnumFont&>(font())._opened;
const Containers::StringView text = textFull.slice(begin, end == ~UnsignedInt{} ? textFull.size() : end);
/* Get glyph codes from characters */
arrayResize(_glyphs, 0);
arrayReserve(_glyphs, text.size());
for(std::size_t i = 0; i != text.size(); ) {
const Containers::Pair<char32_t, std::size_t> codepointNext = Utility::Unicode::nextChar(text, i);
const auto it = fontData.glyphId.find(codepointNext.first());
arrayAppend(_glyphs, it == fontData.glyphId.end() ? 0 : it->second);
i = codepointNext.second();
}
return _glyphs.size();
}
void doGlyphIdsInto(const Containers::StridedArrayView1D<UnsignedInt>& ids) const override {
Text: new AbstractShaper interface for shaping. Replaces the previous, grossly inefficient AbstractLayouter which was performing one virtual call per glyph (!). It's now also reusable, meaning it doesn't need to be allocated anew for every new shaped text, and it no longer requires each and every font plugin to implement the same redundant glyph data fetching from the glyph cache, scaling etc. -- all that is meant to be done by the users of AbstractShaper, i.e. Renderer. The independency on a glyph cache theorerically also means it can be used for a completely different, non-texture-based way to render text (such as direct path drawing directly on the GPU), although I won't be exploring that path now. It also exposes an interface for specifying script, language, direction and typographic features. Such interface will be currently only implemented in HarfBuzz, but that's the intent -- to provide a flexible enough interface to support all possible use cases that a font or a font plugin may support, instead of exposing a least common denominator and then having no easy way to shape a text in a non-Latin script or use a fancy OpenType feature the chosen font has. The old public interface is preserved for backwards compatibility, marked as deprecated, however the virtual APIs are not, as supporting that would be too nasty. I don't think any user code ever implemented a font plugin so this should be okay. To ensure smooth transition with no regressions, the Renderer class and MagnumFont tests still use the old API in this commit, and their test pass the same way as they did before (except for two removed MagnumFont test cases which tested errors that are now an assertion in the deprecated layout() API and thus cannot be tested from the plugin anymore). Porting them away from the deprecated API will be done in separate commits.
3 years ago
Utility::copy(_glyphs, ids);
}
void doGlyphOffsetsAdvancesInto(const Containers::StridedArrayView1D<Vector2>& offsets, const Containers::StridedArrayView1D<Vector2>& advances) const override {
const Data& fontData = *static_cast<const MagnumFont&>(font())._opened;
Text: new AbstractShaper interface for shaping. Replaces the previous, grossly inefficient AbstractLayouter which was performing one virtual call per glyph (!). It's now also reusable, meaning it doesn't need to be allocated anew for every new shaped text, and it no longer requires each and every font plugin to implement the same redundant glyph data fetching from the glyph cache, scaling etc. -- all that is meant to be done by the users of AbstractShaper, i.e. Renderer. The independency on a glyph cache theorerically also means it can be used for a completely different, non-texture-based way to render text (such as direct path drawing directly on the GPU), although I won't be exploring that path now. It also exposes an interface for specifying script, language, direction and typographic features. Such interface will be currently only implemented in HarfBuzz, but that's the intent -- to provide a flexible enough interface to support all possible use cases that a font or a font plugin may support, instead of exposing a least common denominator and then having no easy way to shape a text in a non-Latin script or use a fancy OpenType feature the chosen font has. The old public interface is preserved for backwards compatibility, marked as deprecated, however the virtual APIs are not, as supporting that would be too nasty. I don't think any user code ever implemented a font plugin so this should be okay. To ensure smooth transition with no regressions, the Renderer class and MagnumFont tests still use the old API in this commit, and their test pass the same way as they did before (except for two removed MagnumFont test cases which tested errors that are now an assertion in the deprecated layout() API and thus cannot be tested from the plugin anymore). Porting them away from the deprecated API will be done in separate commits.
3 years ago
for(std::size_t i = 0; i != _glyphs.size(); ++i) {
/* There's no glyph offsets in addition to advances */
offsets[i] = {};
advances[i] = fontData.glyphs[_glyphs[i]].advance;
}
}
Containers::StridedArrayView1D<const Vector2> _glyphAdvance;
Containers::Array<UnsignedInt> _glyphs;
};
Text: new AbstractShaper interface for shaping. Replaces the previous, grossly inefficient AbstractLayouter which was performing one virtual call per glyph (!). It's now also reusable, meaning it doesn't need to be allocated anew for every new shaped text, and it no longer requires each and every font plugin to implement the same redundant glyph data fetching from the glyph cache, scaling etc. -- all that is meant to be done by the users of AbstractShaper, i.e. Renderer. The independency on a glyph cache theorerically also means it can be used for a completely different, non-texture-based way to render text (such as direct path drawing directly on the GPU), although I won't be exploring that path now. It also exposes an interface for specifying script, language, direction and typographic features. Such interface will be currently only implemented in HarfBuzz, but that's the intent -- to provide a flexible enough interface to support all possible use cases that a font or a font plugin may support, instead of exposing a least common denominator and then having no easy way to shape a text in a non-Latin script or use a fancy OpenType feature the chosen font has. The old public interface is preserved for backwards compatibility, marked as deprecated, however the virtual APIs are not, as supporting that would be too nasty. I don't think any user code ever implemented a font plugin so this should be okay. To ensure smooth transition with no regressions, the Renderer class and MagnumFont tests still use the old API in this commit, and their test pass the same way as they did before (except for two removed MagnumFont test cases which tested errors that are now an assertion in the deprecated layout() API and thus cannot be tested from the plugin anymore). Porting them away from the deprecated API will be done in separate commits.
3 years ago
return Containers::pointer<Shaper>(*this);
}
}}
plugins: new testing workflow. The current testing workflow had quite a few major flaws and it was no longer possible after the move of Any* plugins to core. Among the flaws is: * Every plugin was basically built twice, once as the real plugin and once as a static testing library. Most of the build shared common object files, but nevertheless it inflated build times and made the buildsystem extremely complex. * Because the actual plugin binary was never actually loaded during the test, it couldn't spot problems like: - undefined references - errors in metadata files - mismatched plugin interface/version, missing entry points - broken static plugin import files * Tests that made use of independent plugins (such as TgaImageConverter test using TgaImporter to verify the output) had a hardcoded dependency on such plugins, making a minimal setup very hard. * Dynamic loading of plugins from the Any* proxies was always directed to the install location on the filesystem with no possibility to load these directly from the build tree. That caused random ABI mismatch crashes, or, on the other hand, if no plugins were installed, particular portions of the codebase weren't tested at all. Now the workflow is the following: * Every plugin is built exactly once, either as dynamic or as static. * The test always loads it via the plugin manager. If it's dynamic, it's loaded straight from the build directory; if it's static, it gets linked to the test executable directly. * Plugins used indirectly are always served from the build directory (if enabled) to ensure reproducibility and independence on what's installed on the filesystem. Missing presence of these plugins causes particular tests to be simply skipped. * Plugins that have extensive tests for internal functionality that's not exposed through the plugin interface are still built in two parts, but the internal tests are simply consuming the OBJECT files directly instead of linking to a static library.
8 years ago
CORRADE_PLUGIN_REGISTER(MagnumFont, Magnum::Text::MagnumFont,
MAGNUM_TEXT_ABSTRACTFONT_PLUGIN_INTERFACE)