/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Vladimír Vondruš 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 #include #include #include #include #include #include #include #include "Magnum/ImageView.h" #include "Magnum/Math/ConfigurationValue.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 image; Containers::Optional filePath; std::unordered_map glyphId; Containers::Array glyphAdvance; }; namespace { class MagnumFontLayouter: public AbstractLayouter { public: explicit MagnumFontLayouter(Containers::ArrayView glyphAdvance, const AbstractGlyphCache& cache, Float fontSize, Float textSize, Containers::Array&& glyphs); private: Containers::Triple doRenderGlyph(UnsignedInt i) override; const Containers::ArrayView glyphAdvance; const AbstractGlyphCache& cache; const Float fontSize, textSize; const Containers::Array 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 data, const Float) -> Metrics { 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("version") != 1) { Error() << "Text::MagnumFont::openData(): unsupported file version, expected 1 but got" << conf.value("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 glyphs = _opened->conf.groups("glyph"); arrayReserve(_opened->glyphAdvance, glyphs.size()); for(const Utility::ConfigurationGroup* const g: glyphs) arrayAppend(_opened->glyphAdvance, g->value("advance")); /* Fill character->glyph map */ const std::vector chars = _opened->conf.groups("char"); for(const Utility::ConfigurationGroup* const c: chars) { const UnsignedInt glyphId = c->value("glyph"); CORRADE_INTERNAL_ASSERT(glyphId < _opened->glyphAdvance.size()); _opened->glyphId.emplace(c->value("unicode"), glyphId); } return {_opened->conf.value("fontSize"), _opened->conf.value("ascent"), _opened->conf.value("descent"), _opened->conf.value("lineHeight")}; } auto MagnumFont::doOpenFile(const Containers::StringView filename, const Float size) -> Metrics { _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::doGlyphAdvance(const UnsignedInt glyph) { return glyph < _opened->glyphAdvance.size() ? _opened->glyphAdvance[glyph] : Vector2(); } Containers::Pointer MagnumFont::doCreateGlyphCache() { /* Set cache image */ Containers::Pointer cache{InPlaceInit, _opened->conf.value("originalImageSize"), _opened->image->size(), _opened->conf.value("padding")}; cache->setImage({}, *_opened->image); /* Fill glyph map */ const std::vector glyphs = _opened->conf.groups("glyph"); for(std::size_t i = 0; i != glyphs.size(); ++i) cache->insert(i, glyphs[i]->value("position"), glyphs[i]->value("rectangle")); /* GCC 4.8 needs extra help here */ return Containers::Pointer{Utility::move(cache)}; } Containers::Pointer MagnumFont::doLayout(const AbstractGlyphCache& cache, const Float size, const Containers::StringView text) { /* Get glyph codes from characters */ Containers::Array glyphs{NoInit, text.size()}; for(std::size_t i = 0; i != text.size(); ) { const Containers::Pair codepointNext = Utility::Unicode::nextChar(text, i); const auto it = _opened->glyphId.find(codepointNext.first()); glyphs[i] = it == _opened->glyphId.end() ? 0 : it->second; i = codepointNext.second(); } return Containers::pointer(_opened->glyphAdvance, cache, this->size(), size, Utility::move(glyphs)); } namespace { MagnumFontLayouter::MagnumFontLayouter(Containers::ArrayView glyphAdvance, const AbstractGlyphCache& cache, const Float fontSize, const Float textSize, Containers::Array&& glyphs): AbstractLayouter{UnsignedInt(glyphs.size())}, glyphAdvance{glyphAdvance}, cache(cache), fontSize{fontSize}, textSize{textSize}, glyphs{Utility::move(glyphs)} {} Containers::Triple MagnumFontLayouter::doRenderGlyph(const UnsignedInt i) { /* Position of the texture in the resulting glyph, texture coordinates */ Vector2i position; Range2Di rectangle; std::tie(position, rectangle) = cache[glyphs[i]]; /* Normalized texture coordinates */ const auto textureCoordinates = Range2D(rectangle).scaled(1.0f/Vector2(cache.textureSize())); /* Quad rectangle, computed from texture rectangle, denormalized to requested text size */ const auto quadRectangle = Range2D(Range2Di::fromSize(position, rectangle.size())).scaled(Vector2(textSize/fontSize)); /* Advance for given glyph, denormalized to requested text size */ const Vector2 advance = glyphAdvance[glyphs[i]]*(textSize/fontSize); return {quadRectangle, textureCoordinates, advance}; } } }} CORRADE_PLUGIN_REGISTER(MagnumFont, Magnum::Text::MagnumFont, MAGNUM_TEXT_ABSTRACTFONT_PLUGIN_INTERFACE)