axmol/core/2d/FontAtlas.cpp

558 lines
18 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2013 Zynga Inc.
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2019-present Axmol Engine contributors (see AUTHORS.md).
2021-11-11 17:20:21 +08:00
https://axmol.dev/
2019-11-23 20:27:39 +08:00
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 "2d/FontAtlas.h"
2022-07-16 10:43:05 +08:00
#if AX_TARGET_PLATFORM != AX_PLATFORM_WIN32 && AX_TARGET_PLATFORM != AX_PLATFORM_ANDROID
#elif AX_TARGET_PLATFORM == AX_PLATFORM_ANDROID
2022-10-01 16:24:52 +08:00
# include "platform/android/jni/Java_org_axmol_lib_AxmolEngine.h"
2019-11-23 20:27:39 +08:00
#endif
#include <algorithm>
#include "2d/FontFreeType.h"
#include "base/UTF8.h"
#include "base/Director.h"
#include "base/EventListenerCustom.h"
#include "base/EventDispatcher.h"
#include "base/EventType.h"
2019-11-23 20:27:39 +08:00
#include "simdjson/simdjson.h"
#include "zlib.h"
#include "fmt/format.h"
#include "base/ZipUtils.h"
#include "base/PaddedString.h"
namespace ax
{
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
const int FontAtlas::CacheTextureWidth = 512;
const int FontAtlas::CacheTextureHeight = 512;
Release 2.1.5 (#2076) * Fix unexpected libpng used * Fix string format incorrect for tests * Fix #1751, use coroutine control AutoTest flow * Update CHANGELOG.md * Added OpenType font (.otf) to the noCompress list. (#2077) * Update 1k & copyright notice in some sources * Move doctest to axmol 3rdparty * Fix ci * Update 1kdist to v90 * Update 1kiss.ps1 * DrawNodeV2 0.95.1 (#2079) * Rename remaining legacy engine related spells and improve code style * Update 3rdparty README.md * Fix checkReallySupportsASTC does not work on ios device reported by @BIGCATDOG in https://github.com/axmolengine/axmol/issues/2078 * Fix ci * FastRNG: add missing include for AXASSERT (#2081) * Delete unused files * Improve FileUtils - Rename FileUtils::createDirectory to FileUtils::createDirectories - Use splitpath_cb to optimize FileUtils::createDirectories - Rename FileUtils::getFileShortName to FileUtils::getPathBaseName - Rename FileUtils::getFileExtension to FileUtils::getPathExtension - Add FileUtils::getPathDirName - Add FileUtils::getPathBaseNameNoExtension - Mark all renamed FileUtils stubs old name deprecated - Mark all FileUtils offthread APIs deprecated * Update box2d to v2.4.2 * Disable /sdl checks explicitly for winuwp For axmol deprecated policy, we need disable /sdl checks explicitly to avoid compiler traits invoking deprecated functions as error * Update cppwinrt to 2.0.240405.15 * Update simdjson to 3.10.0 * Fix box2d testbed compile error * Improve file path to url * Fix FileUtils::createDirectories unix logic * axmol-cmdline: remove arch suffix for host build output directory * Update CHANGELOG.md * Update lua bindings --------- Co-authored-by: Dani Alias <danielgutierrezalias@gmail.com> Co-authored-by: aismann <icesoft@freenet.de> Co-authored-by: smilediver <smilediver@outlook.com>
2024-08-11 21:11:35 +08:00
const char* FontAtlas::CMD_PURGE_FONTATLAS = "__ax_PURGE_FONTATLAS";
const char* FontAtlas::CMD_RESET_FONTATLAS = "__ax_RESET_FONTATLAS";
2019-11-23 20:27:39 +08:00
void FontAtlas::loadFontAtlas(std::string_view fontatlasFile, hlookup::string_map<FontAtlas*>& outAtlasMap)
{
using namespace simdjson;
try
{
auto strJson = PaddedString::load(fontatlasFile);
ondemand::parser parser;
ondemand::document settings = parser.iterate(strJson);
std::string_view type = settings["type"];
if (type != "fontatlas")
{
AXLOGE("Load fontatlas {} fail, invalid asset type: {}", fontatlasFile, type);
return;
}
// std::string_view version = settings["version"];
std::string_view atlasName = settings["atlasName"];
auto it = outAtlasMap.find(atlasName);
if (it != outAtlasMap.end())
{
if (it->second->getReferenceCount() != 1)
{
AXLOGE("Load fontatlas {} fail, due to exist fontatlas with same key {} and in used", fontatlasFile,
atlasName);
return;
}
else
it->second->release();
outAtlasMap.erase(it);
}
std::string_view sourceFont = settings["sourceFont"];
int faceSize = static_cast<int>(static_cast<int64_t>(settings["faceSize"]));
auto font = FontFreeType::create(sourceFont, faceSize, GlyphCollection::DYNAMIC, ""sv, true, 0.0f);
if (!font)
{
AXLOGE("Load fontatils {} fail due to create source font {} fail", fontatlasFile, sourceFont);
return;
}
int atlasDim[2];
auto atliasDim = settings["atlasDim"].get_array();
int index = 0;
for (auto value : atliasDim)
{
atlasDim[index++] = static_cast<int>(value.get_int64());
if (index >= 2)
break;
}
auto fontAtlas = new FontAtlas(font, atlasDim[0], atlasDim[1], AX_CONTENT_SCALE_FACTOR());
try
{
fontAtlas->initWithSettings(&settings);
outAtlasMap.emplace(atlasName, fontAtlas);
}
catch (std::exception& ex)
{
fontAtlas->release();
throw ex; // rethrow
}
}
catch (std::exception& ex)
{
AXLOGE("Load fontatils {} fail due to exception occured: {}", fontatlasFile, ex.what());
}
}
FontAtlas::FontAtlas(Font* theFont)
: FontAtlas(theFont, CacheTextureWidth, CacheTextureHeight, AX_CONTENT_SCALE_FACTOR())
{}
FontAtlas::FontAtlas(Font* theFont, int atlasWidth, int atlasHeight, float scaleFactor)
: _font(theFont), _width(atlasWidth), _height(atlasHeight), _scaleFactor(scaleFactor)
2019-11-23 20:27:39 +08:00
{
_font->retain();
_fontFreeType = dynamic_cast<FontFreeType*>(_font);
if (_fontFreeType)
{
2021-12-25 10:04:45 +08:00
_lineHeight = (float)_font->getFontMaxHeight();
_fontAscender = _fontFreeType->getFontAscender();
2019-11-23 20:27:39 +08:00
_letterEdgeExtend = 2;
auto outlineSize = _fontFreeType->getOutlineSize();
if (outlineSize > 0)
{
_strideShift = 1;
_pixelFormat = backend::PixelFormat::RG8;
_currentPageDataSize = _width * _height << _strideShift;
2019-11-23 20:27:39 +08:00
_lineHeight += 2 * outlineSize;
}
else
{
_strideShift = 0;
_pixelFormat = backend::PixelFormat::R8;
_currentPageDataSize = _width * _height;
}
if (_fontFreeType->isDistanceFieldEnabled())
{
_letterPadding += 2 * FontFreeType::DistanceMapSpread;
}
2019-11-23 20:27:39 +08:00
2022-07-16 10:43:05 +08:00
#if AX_ENABLE_CACHE_TEXTURE_DATA
2019-11-23 20:27:39 +08:00
auto eventDispatcher = Director::getInstance()->getEventDispatcher();
2021-12-25 10:04:45 +08:00
_rendererRecreatedListener = EventListenerCustom::create(
2022-07-16 10:43:05 +08:00
EVENT_RENDERER_RECREATED, AX_CALLBACK_1(FontAtlas::listenRendererRecreated, this));
2019-11-23 20:27:39 +08:00
eventDispatcher->addEventListenerWithFixedPriority(_rendererRecreatedListener, 1);
#endif
}
}
void FontAtlas::reinit()
{
if (!_currentPageData)
_currentPageData = new uint8_t[_currentPageDataSize];
_currentPage = -1;
2021-12-25 10:04:45 +08:00
addNewPage();
2019-11-23 20:27:39 +08:00
}
2019-11-23 20:27:39 +08:00
FontAtlas::~FontAtlas()
{
2022-07-16 10:43:05 +08:00
#if AX_ENABLE_CACHE_TEXTURE_DATA
2019-11-23 20:27:39 +08:00
if (_fontFreeType && _rendererRecreatedListener)
{
auto eventDispatcher = Director::getInstance()->getEventDispatcher();
eventDispatcher->removeEventListener(_rendererRecreatedListener);
_rendererRecreatedListener = nullptr;
}
#endif
_font->release();
releaseTextures();
2022-07-16 10:43:05 +08:00
AX_SAFE_DELETE_ARRAY(_currentPageData);
2019-11-23 20:27:39 +08:00
}
void FontAtlas::initWithSettings(void* opaque /*simdjson::ondemand::document*/)
{
if (!_currentPageData)
_currentPageData = new uint8_t[_currentPageDataSize];
_currentPage = -1;
simdjson::ondemand::document& settings = *(simdjson::ondemand::document*)opaque;
// pages
for (auto page : settings["pages"].get_array())
{
auto comprData = utils::base64Decode(page);
auto uncomprData = ZipUtils::decompressGZ(std::span{comprData}, _currentPageDataSize);
addNewPageWithData(uncomprData.data(), uncomprData.size());
}
_currentPageOrigX = static_cast<float>(settings["pageX"].get_double());
_currentPageOrigY = static_cast<float>(settings["pageY"].get_double());
// letters
FontLetterDefinition tempDef;
tempDef.rotated = false;
tempDef.validDefinition = true;
std::string strCharCode;
for (auto field : settings["letters"].get_object())
{
strCharCode = static_cast<std::string_view>(field.unescaped_key());
auto letterInfo = field.value();
tempDef.U = static_cast<float>(letterInfo["U"].get_double());
tempDef.V = static_cast<float>(letterInfo["V"].get_double());
tempDef.xAdvance = static_cast<float>(letterInfo["advance"].get_double());
tempDef.width = static_cast<float>(letterInfo["width"].get_double());
tempDef.height = static_cast<float>(letterInfo["height"].get_double());
tempDef.offsetX = static_cast<float>(letterInfo["offsetX"].get_double());
tempDef.offsetY = static_cast<float>(letterInfo["offsetY"].get_double());
2024-04-06 18:05:42 +08:00
tempDef.textureID = static_cast<int>(letterInfo["page"].get_int64());
auto charCode = atoi(strCharCode.c_str());
tempDef.U /= _scaleFactor;
tempDef.V /= _scaleFactor;
tempDef.width /= _scaleFactor;
tempDef.height /= _scaleFactor;
_letterDefinitions.emplace(charCode, tempDef);
}
}
2019-11-23 20:27:39 +08:00
void FontAtlas::reset()
{
releaseTextures();
2021-12-25 10:04:45 +08:00
_currLineHeight = 0;
2019-11-23 20:27:39 +08:00
_currentPageOrigX = 0;
_currentPageOrigY = 0;
_letterDefinitions.clear();
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
reinit();
}
void FontAtlas::releaseTextures()
{
for (auto&& item : _atlasTextures)
2019-11-23 20:27:39 +08:00
{
item.second->release();
}
_atlasTextures.clear();
}
void FontAtlas::purgeTexturesAtlas()
{
if (_fontFreeType)
{
reset();
auto eventDispatcher = Director::getInstance()->getEventDispatcher();
2021-12-25 10:04:45 +08:00
eventDispatcher->dispatchCustomEvent(CMD_PURGE_FONTATLAS, this);
eventDispatcher->dispatchCustomEvent(CMD_RESET_FONTATLAS, this);
2019-11-23 20:27:39 +08:00
}
}
2021-12-25 10:04:45 +08:00
void FontAtlas::listenRendererRecreated(EventCustom* /*event*/)
2019-11-23 20:27:39 +08:00
{
purgeTexturesAtlas();
}
2021-12-25 10:04:45 +08:00
void FontAtlas::addLetterDefinition(char32_t utf32Char, const FontLetterDefinition& letterDefinition)
2019-11-23 20:27:39 +08:00
{
_letterDefinitions[utf32Char] = letterDefinition;
}
void FontAtlas::scaleFontLetterDefinition(float scaleFactor)
{
2021-12-25 10:04:45 +08:00
for (auto&& fontDefinition : _letterDefinitions)
{
2019-11-23 20:27:39 +08:00
auto& letterDefinition = fontDefinition.second;
letterDefinition.width *= scaleFactor;
letterDefinition.height *= scaleFactor;
letterDefinition.offsetX *= scaleFactor;
letterDefinition.offsetY *= scaleFactor;
letterDefinition.xAdvance = (int)(letterDefinition.xAdvance * scaleFactor);
}
}
2021-12-25 10:04:45 +08:00
bool FontAtlas::getLetterDefinitionForChar(char32_t utf32Char, FontLetterDefinition& letterDefinition)
2019-11-23 20:27:39 +08:00
{
auto outIterator = _letterDefinitions.find(utf32Char);
if (outIterator != _letterDefinitions.end())
{
letterDefinition = (*outIterator).second;
return letterDefinition.validDefinition;
}
else
{
return false;
}
}
void FontAtlas::findNewCharacters(const std::u32string& u32Text, std::unordered_set<char32_t>& charset)
2019-11-23 20:27:39 +08:00
{
if (_letterDefinitions.empty())
{
std::copy(u32Text.begin(), u32Text.end(), std::inserter(charset, charset.end()));
2019-11-23 20:27:39 +08:00
}
else
{
for (auto&& charCode : u32Text)
if (_letterDefinitions.find(charCode) == _letterDefinitions.end())
charset.insert(charCode);
2019-11-23 20:27:39 +08:00
}
}
bool FontAtlas::prepareLetterDefinitions(const std::u32string& utf32Text)
{
if (_fontFreeType == nullptr)
{
return false;
}
if (!_currentPageData)
2021-12-25 10:04:45 +08:00
reinit();
std::unordered_set<char32_t> charCodeSet;
findNewCharacters(utf32Text, charCodeSet);
if (charCodeSet.empty())
2019-11-23 20:27:39 +08:00
{
return false;
}
int adjustForDistanceMap = _letterPadding / 2;
2021-12-25 10:04:45 +08:00
int adjustForExtend = _letterEdgeExtend / 2;
int bitmapWidth = 0;
int bitmapHeight = 0;
2019-11-23 20:27:39 +08:00
int glyphHeight;
Rect tempRect;
FontLetterDefinition tempDef;
auto pixelFormat = _pixelFormat;
2019-11-23 20:27:39 +08:00
int startY = (int)_currentPageOrigY;
for (auto&& charCode : charCodeSet)
2019-11-23 20:27:39 +08:00
{
2024-04-08 01:55:41 +08:00
auto missingIt = _missingGlyphFallbackFonts.find(charCode);
uint8_t* bitmap = nullptr;
FontFreeType* charRenderer = _fontFreeType;
if (missingIt == _missingGlyphFallbackFonts.end())
{
FontFaceInfo* fallbackFaceInfo = nullptr;
bitmap = charRenderer->getGlyphBitmap(charCode, bitmapWidth, bitmapHeight, tempRect, tempDef.xAdvance,
&fallbackFaceInfo);
if (!bitmap && fallbackFaceInfo)
{
auto fallbackIt = _missingFallbackFonts.find(fallbackFaceInfo->family);
if (fallbackIt != _missingFallbackFonts.end())
{
charRenderer = fallbackIt->second;
}
else
{
charRenderer = FontFreeType::createWithFaceInfo(fallbackFaceInfo, _fontFreeType);
if (charRenderer)
_missingFallbackFonts.insert(fallbackFaceInfo->family, charRenderer);
}
if (charRenderer)
{
unsigned int glyphIndex = fallbackFaceInfo->currentGlyphIndex;
bitmap =
charRenderer->getGlyphBitmapByIndex(glyphIndex, bitmapWidth, bitmapHeight, tempRect, tempDef.xAdvance);
_missingGlyphFallbackFonts.emplace(charCode, std::make_pair(charRenderer, glyphIndex));
}
}
}
else
{ // found fallback font for missing charas, getGlyphBitmap without fallback
charRenderer = missingIt->second.first;
unsigned int glyphIndex = missingIt->second.second;
bitmap = charRenderer->getGlyphBitmapByIndex(glyphIndex, bitmapWidth, bitmapHeight, tempRect, tempDef.xAdvance);
}
if (bitmap && bitmapWidth > 0 && bitmapHeight > 0)
2019-11-23 20:27:39 +08:00
{
tempDef.validDefinition = true;
2021-12-25 10:04:45 +08:00
tempDef.width = tempRect.size.width + _letterPadding + _letterEdgeExtend;
tempDef.height = tempRect.size.height + _letterPadding + _letterEdgeExtend;
tempDef.offsetX = tempRect.origin.x - adjustForDistanceMap - adjustForExtend;
tempDef.offsetY = _fontAscender + tempRect.origin.y - adjustForDistanceMap - adjustForExtend;
2019-11-23 20:27:39 +08:00
if (_currentPageOrigX + tempDef.width > _width)
2019-11-23 20:27:39 +08:00
{
_currentPageOrigY += _currLineHeight;
2021-12-25 10:04:45 +08:00
_currLineHeight = 0;
2019-11-23 20:27:39 +08:00
_currentPageOrigX = 0;
if (_currentPageOrigY + _lineHeight + _letterPadding + _letterEdgeExtend >= _height)
2019-11-23 20:27:39 +08:00
{
updateTextureContent(pixelFormat, startY);
startY = 0;
addNewPage();
2019-11-23 20:27:39 +08:00
}
}
glyphHeight = static_cast<int>(bitmapHeight) + _letterPadding + _letterEdgeExtend;
if (glyphHeight > _currLineHeight)
{
_currLineHeight = glyphHeight;
}
2024-04-08 01:55:41 +08:00
charRenderer->renderCharAt(_currentPageData, (int)_currentPageOrigX + adjustForExtend,
(int)_currentPageOrigY + adjustForExtend, bitmap, bitmapWidth, bitmapHeight,
2024-04-08 01:55:41 +08:00
_width, _height);
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
tempDef.U = _currentPageOrigX;
tempDef.V = _currentPageOrigY;
2019-11-23 20:27:39 +08:00
tempDef.textureID = _currentPage;
_currentPageOrigX += tempDef.width + 1;
// take from pixels to points
tempDef.width = tempDef.width / _scaleFactor;
tempDef.height = tempDef.height / _scaleFactor;
tempDef.U = tempDef.U / _scaleFactor;
tempDef.V = tempDef.V / _scaleFactor;
tempDef.rotated = false;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
else
{
2021-12-25 10:04:45 +08:00
if (bitmap)
2019-11-23 20:27:39 +08:00
delete[] bitmap;
tempDef.validDefinition = !!tempDef.xAdvance;
tempDef.width = 0;
tempDef.height = 0;
tempDef.U = 0;
tempDef.V = 0;
tempDef.offsetX = 0;
tempDef.offsetY = 0;
tempDef.textureID = 0;
tempDef.rotated = false;
2019-11-23 20:27:39 +08:00
_currentPageOrigX += 1;
}
_letterDefinitions[charCode] = tempDef;
2019-11-23 20:27:39 +08:00
}
updateTextureContent(pixelFormat, startY);
2019-11-23 20:27:39 +08:00
return true;
}
void FontAtlas::updateTextureContent(backend::PixelFormat format, int startY)
{
auto data = _currentPageData + (_width * (int)startY << _strideShift);
_atlasTextures[_currentPage]->updateWithSubData(data, 0, startY, _width,
2024-04-08 01:55:41 +08:00
(std::min)((int)_currentPageOrigY - startY + _currLineHeight, _height));
}
void FontAtlas::addNewPage()
{
memset(_currentPageData, 0, _currentPageDataSize);
addNewPageWithData(_currentPageData, _currentPageDataSize);
_currentPageOrigY = 0;
}
void FontAtlas::addNewPageWithData(const uint8_t* data, size_t size)
{
assert(_currentPageDataSize == size);
auto texture = new Texture2D();
texture->initWithData(data, _currentPageDataSize, _pixelFormat, _width, _height);
if (_antialiasEnabled)
texture->setAntiAliasTexParameters();
else
texture->setAliasTexParameters();
setTexture(++_currentPage, texture);
texture->release();
2019-11-23 20:27:39 +08:00
}
void FontAtlas::setTexture(unsigned int slot, Texture2D* texture)
2019-11-23 20:27:39 +08:00
{
texture->retain();
_atlasTextures[slot] = texture;
}
Texture2D* FontAtlas::getTexture(int slot)
{
return _atlasTextures[slot];
}
void FontAtlas::setLineHeight(float newHeight)
{
_lineHeight = newHeight;
}
std::string_view FontAtlas::getFontName() const
2019-11-23 20:27:39 +08:00
{
std::string_view fontName = _fontFreeType ? _fontFreeType->getFontName() : ""sv;
2021-12-25 10:04:45 +08:00
if (fontName.empty())
return fontName;
2019-11-23 20:27:39 +08:00
auto idx = fontName.rfind('/');
2021-12-25 10:04:45 +08:00
if (idx != std::string::npos)
{
return fontName.substr(idx + 1);
}
2019-11-23 20:27:39 +08:00
idx = fontName.rfind('\\');
2021-12-25 10:04:45 +08:00
if (idx != std::string::npos)
{
return fontName.substr(idx + 1);
}
2019-11-23 20:27:39 +08:00
return fontName;
}
void FontAtlas::setAliasTexParameters()
{
if (_antialiasEnabled)
{
_antialiasEnabled = false;
2021-12-25 10:04:45 +08:00
for (const auto& tex : _atlasTextures)
2019-11-23 20:27:39 +08:00
{
tex.second->setAliasTexParameters();
}
}
}
void FontAtlas::setAntiAliasTexParameters()
{
2021-12-25 10:04:45 +08:00
if (!_antialiasEnabled)
2019-11-23 20:27:39 +08:00
{
_antialiasEnabled = true;
2021-12-25 10:04:45 +08:00
for (const auto& tex : _atlasTextures)
2019-11-23 20:27:39 +08:00
{
tex.second->setAntiAliasTexParameters();
}
}
}
}