initial commit, 4.5 stable
Some checks failed
🔗 GHA / 📊 Static checks (push) Has been cancelled
🔗 GHA / 🤖 Android (push) Has been cancelled
🔗 GHA / 🍏 iOS (push) Has been cancelled
🔗 GHA / 🐧 Linux (push) Has been cancelled
🔗 GHA / 🍎 macOS (push) Has been cancelled
🔗 GHA / 🏁 Windows (push) Has been cancelled
🔗 GHA / 🌐 Web (push) Has been cancelled

This commit is contained in:
2025-09-16 20:46:46 -04:00
commit 9d30169a8d
13378 changed files with 7050105 additions and 0 deletions

2
modules/text_server_fb/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
# Godot-cpp headers
gdextension_build/godot-cpp

View File

@@ -0,0 +1,27 @@
#!/usr/bin/env python
from misc.utility.scons_hints import *
Import("env")
Import("env_modules")
freetype_enabled = "freetype" in env.module_list
msdfgen_enabled = "msdfgen" in env.module_list
env_text_server_fb = env_modules.Clone()
if "svg" in env.module_list:
env_text_server_fb.Prepend(
CPPEXTPATH=["#thirdparty/thorvg/inc", "#thirdparty/thorvg/src/common", "#thirdparty/thorvg/src/renderer"]
)
# Enable ThorVG static object linking.
env_text_server_fb.Append(CPPDEFINES=["TVG_STATIC"])
if env["builtin_msdfgen"] and msdfgen_enabled:
env_text_server_fb.Append(CPPDEFINES=[("MSDFGEN_PUBLIC", "")])
env_text_server_fb.Prepend(CPPEXTPATH=["#thirdparty/msdfgen"])
if env["builtin_freetype"] and freetype_enabled:
env_text_server_fb.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"])
env_text_server_fb.Prepend(CPPEXTPATH=["#thirdparty/freetype/include"])
env_text_server_fb.add_source_files(env.modules_sources, "*.cpp")

View File

@@ -0,0 +1,22 @@
def can_build(env, platform):
env.module_add_dependencies("text_server_fb", ["freetype", "msdfgen", "svg"], True)
return True
def configure(env):
pass
def is_enabled():
# The module is disabled by default. Use module_text_server_fb_enabled=yes to enable it.
return False
def get_doc_classes():
return [
"TextServerFallback",
]
def get_doc_path():
return "doc_classes"

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<class name="TextServerFallback" inherits="TextServerExtension" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
<brief_description>
A fallback implementation of Godot's text server, without support for BiDi and complex text layout.
</brief_description>
<description>
A fallback implementation of Godot's text server. This fallback is faster than [TextServerAdvanced] for processing a lot of text, but it does not support BiDi and complex text layout.
[b]Note:[/b] This text server is not part of official Godot binaries. If you want to use it, compile the engine with the option [code]module_text_server_fb_enabled=yes[/code]. When building with [TextServerFallback], consider also disabling [TextServerAdvanced] with [code]module_text_server_adv_enabled=no[/code] to reduce binary size.
</description>
<tutorials>
</tutorials>
</class>

View File

@@ -0,0 +1,311 @@
#!/usr/bin/env python
# ruff: noqa: F821
import methods
# For the reference:
# - CCFLAGS are compilation flags shared between C and C++
# - CFLAGS are for C-specific compilation flags
# - CXXFLAGS are for C++-specific compilation flags
# - CPPFLAGS are for pre-processor flags
# - CPPDEFINES are for pre-processor defines
# - LINKFLAGS are for linking flags
env = SConscript("./godot-cpp/SConstruct")
env.__class__.disable_warnings = methods.disable_warnings
opts = Variables([], ARGUMENTS)
opts.Add(BoolVariable("brotli_enabled", "Use Brotli library", True))
opts.Add(BoolVariable("freetype_enabled", "Use FreeType library", True))
opts.Add(BoolVariable("msdfgen_enabled", "Use MSDFgen library (require FreeType)", True))
opts.Add(BoolVariable("thorvg_enabled", "Use ThorVG library (require FreeType)", True))
opts.Add(BoolVariable("verbose", "Enable verbose output for the compilation", False))
opts.Update(env)
# ThorVG
if env["thorvg_enabled"] and env["freetype_enabled"]:
env_tvg = env.Clone()
env_tvg.disable_warnings()
thirdparty_tvg_dir = "../../../thirdparty/thorvg/"
thirdparty_tvg_sources = [
# common
"src/common/tvgCompressor.cpp",
"src/common/tvgLines.cpp",
"src/common/tvgMath.cpp",
"src/common/tvgStr.cpp",
# SVG parser
"src/loaders/svg/tvgSvgCssStyle.cpp",
"src/loaders/svg/tvgSvgLoader.cpp",
"src/loaders/svg/tvgSvgPath.cpp",
"src/loaders/svg/tvgSvgSceneBuilder.cpp",
"src/loaders/svg/tvgSvgUtil.cpp",
"src/loaders/svg/tvgXmlParser.cpp",
"src/loaders/raw/tvgRawLoader.cpp",
# image loaders
"src/loaders/external_png/tvgPngLoader.cpp",
"src/loaders/jpg/tvgJpgd.cpp",
"src/loaders/jpg/tvgJpgLoader.cpp",
# renderer common
"src/renderer/tvgAccessor.cpp",
# "src/renderer/tvgAnimation.cpp",
"src/renderer/tvgCanvas.cpp",
"src/renderer/tvgFill.cpp",
# "src/renderer/tvgGlCanvas.cpp",
"src/renderer/tvgInitializer.cpp",
"src/renderer/tvgLoader.cpp",
"src/renderer/tvgPaint.cpp",
"src/renderer/tvgPicture.cpp",
"src/renderer/tvgRender.cpp",
# "src/renderer/tvgSaver.cpp",
"src/renderer/tvgScene.cpp",
"src/renderer/tvgShape.cpp",
"src/renderer/tvgSwCanvas.cpp",
"src/renderer/tvgTaskScheduler.cpp",
"src/renderer/tvgText.cpp",
# "src/renderer/tvgWgCanvas.cpp",
# renderer sw_engine
"src/renderer/sw_engine/tvgSwFill.cpp",
"src/renderer/sw_engine/tvgSwImage.cpp",
"src/renderer/sw_engine/tvgSwMath.cpp",
"src/renderer/sw_engine/tvgSwMemPool.cpp",
"src/renderer/sw_engine/tvgSwRaster.cpp",
"src/renderer/sw_engine/tvgSwRenderer.cpp",
"src/renderer/sw_engine/tvgSwRle.cpp",
"src/renderer/sw_engine/tvgSwShape.cpp",
"src/renderer/sw_engine/tvgSwStroke.cpp",
]
thirdparty_tvg_sources = [thirdparty_tvg_dir + file for file in thirdparty_tvg_sources]
env_tvg.Append(
CPPPATH=[
"../../../thirdparty/thorvg/inc",
"../../../thirdparty/thorvg/src/common",
"../../../thirdparty/thorvg/src/renderer",
"../../../thirdparty/thorvg/src/renderer/sw_engine",
"../../../thirdparty/thorvg/src/loaders/svg",
"../../../thirdparty/thorvg/src/loaders/raw",
"../../../thirdparty/thorvg/src/loaders/external_png",
"../../../thirdparty/thorvg/src/loaders/jpg",
"../../../thirdparty/libpng",
]
)
# Enable ThorVG static object linking.
env_tvg.Append(CPPDEFINES=["TVG_STATIC"])
env.Append(
CPPPATH=[
"../../../thirdparty/thorvg/inc",
"../../../thirdparty/thorvg/src/common",
"../../../thirdparty/thorvg/src/renderer",
]
)
env.Append(CPPDEFINES=["MODULE_SVG_ENABLED"])
lib = env_tvg.Library(
f"tvg_builtin{env['suffix']}{env['LIBSUFFIX']}",
thirdparty_tvg_sources,
)
env.Append(LIBS=[lib])
# MSDFGEN
if env["msdfgen_enabled"] and env["freetype_enabled"]:
env_msdfgen = env.Clone()
env_msdfgen.disable_warnings()
thirdparty_msdfgen_dir = "../../../thirdparty/msdfgen/"
thirdparty_msdfgen_sources = [
"core/Contour.cpp",
"core/DistanceMapping.cpp",
"core/EdgeHolder.cpp",
"core/MSDFErrorCorrection.cpp",
"core/Projection.cpp",
"core/Scanline.cpp",
"core/Shape.cpp",
"core/contour-combiners.cpp",
"core/edge-coloring.cpp",
"core/edge-segments.cpp",
"core/edge-selectors.cpp",
"core/equation-solver.cpp",
# "core/export-svg.cpp",
"core/msdf-error-correction.cpp",
"core/msdfgen.cpp",
"core/rasterization.cpp",
"core/render-sdf.cpp",
# "core/save-bmp.cpp",
# "core/save-fl32.cpp",
# "core/save-rgba.cpp",
# "core/save-tiff.cpp",
"core/sdf-error-estimation.cpp",
"core/shape-description.cpp",
]
thirdparty_msdfgen_sources = [thirdparty_msdfgen_dir + file for file in thirdparty_msdfgen_sources]
env_msdfgen.Append(CPPDEFINES=[("MSDFGEN_PUBLIC", "")])
env_msdfgen.Append(CPPPATH=["../../../thirdparty/freetype/include", "../../../thirdparty/msdfgen"])
env.Append(CPPPATH=["../../../thirdparty/msdfgen"])
env.Append(CPPDEFINES=[("MSDFGEN_PUBLIC", "")])
env.Append(CPPDEFINES=["MODULE_MSDFGEN_ENABLED"])
lib = env_msdfgen.Library(
f"msdfgen_builtin{env['suffix']}{env['LIBSUFFIX']}",
thirdparty_msdfgen_sources,
)
env.Append(LIBS=[lib])
# FreeType
if env["freetype_enabled"]:
env_freetype = env.Clone()
env_freetype.disable_warnings()
thirdparty_freetype_dir = "../../../thirdparty/freetype/"
thirdparty_freetype_sources = [
"src/autofit/autofit.c",
"src/base/ftbase.c",
"src/base/ftbbox.c",
"src/base/ftbdf.c",
"src/base/ftbitmap.c",
"src/base/ftcid.c",
"src/base/ftdebug.c",
"src/base/ftfstype.c",
"src/base/ftgasp.c",
"src/base/ftglyph.c",
"src/base/ftgxval.c",
"src/base/ftinit.c",
"src/base/ftmm.c",
"src/base/ftotval.c",
"src/base/ftpatent.c",
"src/base/ftpfr.c",
"src/base/ftstroke.c",
"src/base/ftsynth.c",
"src/base/ftsystem.c",
"src/base/fttype1.c",
"src/base/ftwinfnt.c",
"src/bdf/bdf.c",
"src/bzip2/ftbzip2.c",
"src/cache/ftcache.c",
"src/cff/cff.c",
"src/cid/type1cid.c",
"src/gxvalid/gxvalid.c",
"src/gzip/ftgzip.c",
"src/lzw/ftlzw.c",
"src/otvalid/otvalid.c",
"src/pcf/pcf.c",
"src/pfr/pfr.c",
"src/psaux/psaux.c",
"src/pshinter/pshinter.c",
"src/psnames/psnames.c",
"src/raster/raster.c",
"src/sdf/sdf.c",
"src/svg/svg.c",
"src/smooth/smooth.c",
"src/truetype/truetype.c",
"src/type1/type1.c",
"src/type42/type42.c",
"src/winfonts/winfnt.c",
"src/sfnt/sfnt.c",
]
thirdparty_freetype_sources = [thirdparty_freetype_dir + file for file in thirdparty_freetype_sources]
thirdparty_png_dir = "../../../thirdparty/libpng/"
thirdparty_png_sources = [
"png.c",
"pngerror.c",
"pngget.c",
"pngmem.c",
"pngpread.c",
"pngread.c",
"pngrio.c",
"pngrtran.c",
"pngrutil.c",
"pngset.c",
"pngtrans.c",
"pngwio.c",
"pngwrite.c",
"pngwtran.c",
"pngwutil.c",
]
thirdparty_freetype_sources += [thirdparty_png_dir + file for file in thirdparty_png_sources]
thirdparty_zlib_dir = "../../../thirdparty/zlib/"
thirdparty_zlib_sources = [
"adler32.c",
"compress.c",
"crc32.c",
"deflate.c",
"inffast.c",
"inflate.c",
"inftrees.c",
"trees.c",
"uncompr.c",
"zutil.c",
]
thirdparty_freetype_sources += [thirdparty_zlib_dir + file for file in thirdparty_zlib_sources]
if env["brotli_enabled"]:
thirdparty_brotli_dir = "../../../thirdparty/brotli/"
thirdparty_brotli_sources = [
"common/constants.c",
"common/context.c",
"common/dictionary.c",
"common/platform.c",
"common/shared_dictionary.c",
"common/transform.c",
"dec/bit_reader.c",
"dec/decode.c",
"dec/huffman.c",
"dec/state.c",
]
thirdparty_freetype_sources += [thirdparty_brotli_dir + file for file in thirdparty_brotli_sources]
env_freetype.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"])
env_freetype.Prepend(CPPPATH=[thirdparty_brotli_dir + "include"])
env.Append(CPPDEFINES=["FT_CONFIG_OPTION_USE_BROTLI"])
env_freetype.Append(CPPPATH=[thirdparty_freetype_dir + "/include", thirdparty_zlib_dir, thirdparty_png_dir])
env.Append(CPPPATH=[thirdparty_freetype_dir + "/include"])
env_freetype.Append(
CPPDEFINES=[
"FT2_BUILD_LIBRARY",
"FT_CONFIG_OPTION_USE_PNG",
"FT_CONFIG_OPTION_SYSTEM_ZLIB",
]
)
if env.dev_build:
env_freetype.Append(CPPDEFINES=["ZLIB_DEBUG"])
env.Append(CPPDEFINES=["MODULE_FREETYPE_ENABLED"])
lib = env_freetype.Library(
f"freetype_builtin{env['suffix']}{env['LIBSUFFIX']}",
thirdparty_freetype_sources,
)
env.Append(LIBS=[lib])
env.Append(CPPDEFINES=["GDEXTENSION"])
env.Append(CPPPATH=["../"])
sources = Glob("../*.cpp")
if env["platform"] == "macos":
methods.write_macos_plist(
f"./bin/libtextserver_fallback.macos.{env['target']}.framework",
f"libtextserver_fallback.macos.{env['target']}",
"org.godotengine.textserver_fallback",
"Fallback Text Server",
)
library = env.SharedLibrary(
f"./bin/libtextserver_fallback.macos.{env['target']}.framework/libtextserver_fallback.macos.{env['target']}",
source=sources,
)
else:
library = env.SharedLibrary(
f"./bin/libtextserver_fallback{env['suffix']}{env['SHLIBSUFFIX']}",
source=sources,
)
Default(library)
methods.prepare_timer()

View File

@@ -0,0 +1,60 @@
def disable_warnings(self):
# 'self' is the environment
if self["platform"] == "windows" and not self["use_mingw"]:
# We have to remove existing warning level defines before appending /w,
# otherwise we get: "warning D9025 : overriding '/W3' with '/w'"
WARN_FLAGS = ["/Wall", "/W4", "/W3", "/W2", "/W1", "/W0"]
self["CCFLAGS"] = [x for x in self["CCFLAGS"] if x not in WARN_FLAGS]
self["CFLAGS"] = [x for x in self["CFLAGS"] if x not in WARN_FLAGS]
self["CXXFLAGS"] = [x for x in self["CXXFLAGS"] if x not in WARN_FLAGS]
self.AppendUnique(CCFLAGS=["/w"])
else:
self.AppendUnique(CCFLAGS=["-w"])
def prepare_timer():
import atexit
import time
def print_elapsed_time(time_at_start: float):
time_elapsed = time.time() - time_at_start
time_formatted = time.strftime("%H:%M:%S", time.gmtime(time_elapsed))
time_centiseconds = round((time_elapsed % 1) * 100)
print(f"[Time elapsed: {time_formatted}.{time_centiseconds}]")
atexit.register(print_elapsed_time, time.time())
def write_macos_plist(target, binary_name, identifier, name):
import os
os.makedirs(f"{target}/Resource/", exist_ok=True)
with open(f"{target}/Resource/Info.plist", "w", encoding="utf-8", newline="\n") as f:
f.write(f"""\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>{binary_name}</string>
<key>CFBundleIdentifier</key>
<string>{identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>{name}</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1.0.0</string>
<key>LSMinimumSystemVersion</key>
<string>10.14</string>
</dict>
</plist>
""")

View File

@@ -0,0 +1,24 @@
[configuration]
entry_symbol = "textserver_fallback_init"
[libraries]
linux.x86_64.debug = "bin/libtextserver_fallback.linux.template_debug.x86_64.so"
linux.x86_64.release = "bin/libtextserver_fallback.linux.template_release.x86_64.so"
linux.x86_32.debug = "bin/libtextserver_fallback.linux.template_debug.x86_32.so"
linux.x86_32.release = "bin/libtextserver_fallback.linux.template_release.x86_32.so"
linux.arm64.debug = "bin/libtextserver_fallback.linux.template_debug.arm64.so"
linux.arm64.release = "bin/libtextserver_fallback.linux.template_release.arm64.so"
linux.rv64.debug = "bin/libtextserver_fallback.linux.template_debug.rv64.so"
linux.rv64.release = "bin/libtextserver_fallback.linux.template_release.rv64.so"
windows.x86_64.debug = "bin/libtextserver_fallback.windows.template_debug.x86_64.dll"
windows.x86_64.release = "bin/libtextserver_fallback.windows.template_release.x86_64.dll"
windows.x86_32.debug = "bin/libtextserver_fallback.windows.template_debug.x86_32.dll"
windows.x86_32.release = "bin/libtextserver_fallback.windows.template_release.x86_32.dll"
windows.arm64.debug = "bin/libtextserver_fallback.windows.template_debug.arm64.dll"
windows.arm64.release = "bin/libtextserver_fallback.windows.template_release.arm64.dll"
macos.debug = "bin/libtextserver_fallback.macos.template_debug.framework"
macos.release = "bin/libtextserver_fallback.macos.template_release.framework"

View File

@@ -0,0 +1,77 @@
/**************************************************************************/
/* register_types.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "register_types.h"
#include "text_server_fb.h"
void initialize_text_server_fb_module(ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SERVERS) {
return;
}
GDREGISTER_CLASS(TextServerFallback);
TextServerManager *tsman = TextServerManager::get_singleton();
if (tsman) {
Ref<TextServerFallback> ts;
ts.instantiate();
tsman->add_interface(ts);
}
}
void uninitialize_text_server_fb_module(ModuleInitializationLevel p_level) {
if (p_level != MODULE_INITIALIZATION_LEVEL_SERVERS) {
return;
}
}
#ifdef GDEXTENSION
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/defs.hpp>
#include <godot_cpp/core/memory.hpp>
using namespace godot;
extern "C" {
GDExtensionBool GDE_EXPORT textserver_fallback_init(GDExtensionInterfaceGetProcAddress p_get_proc_address, const GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization) {
GDExtensionBinding::InitObject init_obj(p_get_proc_address, p_library, r_initialization);
init_obj.register_initializer(&initialize_text_server_fb_module);
init_obj.register_terminator(&uninitialize_text_server_fb_module);
init_obj.set_minimum_library_initialization_level(MODULE_INITIALIZATION_LEVEL_SERVERS);
return init_obj.init();
}
} // ! extern "C"
#endif // ! GDEXTENSION

View File

@@ -0,0 +1,41 @@
/**************************************************************************/
/* register_types.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#ifdef GDEXTENSION
#include <godot_cpp/core/class_db.hpp>
using namespace godot;
#elif defined(GODOT_MODULE)
#include "modules/register_module_types.h"
#endif
void initialize_text_server_fb_module(ModuleInitializationLevel p_level);
void uninitialize_text_server_fb_module(ModuleInitializationLevel p_level);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,909 @@
/**************************************************************************/
/* text_server_fb.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
/*************************************************************************/
/* Fallback Text Server provides simplified TS functionality, without */
/* BiDi, shaping and advanced font features support. */
/*************************************************************************/
#ifdef GDEXTENSION
// Headers for building as GDExtension plug-in.
#include <godot_cpp/godot.hpp>
#include <godot_cpp/core/class_db.hpp>
#include <godot_cpp/core/ext_wrappers.gen.inc>
#include <godot_cpp/core/mutex_lock.hpp>
#include <godot_cpp/variant/array.hpp>
#include <godot_cpp/variant/dictionary.hpp>
#include <godot_cpp/variant/packed_int32_array.hpp>
#include <godot_cpp/variant/packed_string_array.hpp>
#include <godot_cpp/variant/packed_vector2_array.hpp>
#include <godot_cpp/variant/rect2.hpp>
#include <godot_cpp/variant/rid.hpp>
#include <godot_cpp/variant/string.hpp>
#include <godot_cpp/variant/typed_array.hpp>
#include <godot_cpp/variant/vector2.hpp>
#include <godot_cpp/variant/vector2i.hpp>
#include <godot_cpp/classes/text_server.hpp>
#include <godot_cpp/classes/text_server_extension.hpp>
#include <godot_cpp/classes/text_server_manager.hpp>
#include <godot_cpp/classes/caret_info.hpp>
#include <godot_cpp/classes/global_constants_binds.hpp>
#include <godot_cpp/classes/glyph.hpp>
#include <godot_cpp/classes/image.hpp>
#include <godot_cpp/classes/image_texture.hpp>
#include <godot_cpp/classes/ref.hpp>
#include <godot_cpp/classes/worker_thread_pool.hpp>
#include <godot_cpp/templates/hash_map.hpp>
#include <godot_cpp/templates/hash_set.hpp>
#include <godot_cpp/templates/rid_owner.hpp>
#include <godot_cpp/templates/safe_refcount.hpp>
#include <godot_cpp/templates/vector.hpp>
using namespace godot;
#elif defined(GODOT_MODULE)
// Headers for building as built-in module.
#include "core/extension/ext_wrappers.gen.inc"
#include "core/object/worker_thread_pool.h"
#include "core/templates/hash_map.h"
#include "core/templates/rid_owner.h"
#include "core/templates/safe_refcount.h"
#include "scene/resources/image_texture.h"
#include "servers/text/text_server_extension.h"
#include "modules/modules_enabled.gen.h" // For freetype, msdfgen, svg.
#endif
// Thirdparty headers.
#ifdef MODULE_FREETYPE_ENABLED
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TRUETYPE_TABLES_H
#include FT_STROKER_H
#include FT_ADVANCES_H
#include FT_MULTIPLE_MASTERS_H
#include FT_BBOX_H
#include FT_MODULE_H
#include FT_CONFIG_OPTIONS_H
#if !defined(FT_CONFIG_OPTION_USE_BROTLI) && !defined(_MSC_VER)
#warning FreeType is configured without Brotli support, built-in fonts will not be available.
#endif
#endif
/*************************************************************************/
class TextServerFallback : public TextServerExtension {
GDCLASS(TextServerFallback, TextServerExtension);
_THREAD_SAFE_CLASS_
HashMap<StringName, int32_t> feature_sets;
HashMap<int32_t, StringName> feature_sets_inv;
SafeNumeric<TextServer::FontLCDSubpixelLayout> lcd_subpixel_layout{ TextServer::FontLCDSubpixelLayout::FONT_LCD_SUBPIXEL_LAYOUT_NONE };
void _update_settings();
void _insert_feature_sets();
_FORCE_INLINE_ void _insert_feature(const StringName &p_name, int32_t p_tag);
// Font cache data.
#ifdef MODULE_FREETYPE_ENABLED
mutable FT_Library ft_library = nullptr;
#endif
const int rect_range = 1;
struct FontTexturePosition {
int32_t index = -1;
int32_t x = 0;
int32_t y = 0;
FontTexturePosition() {}
FontTexturePosition(int32_t p_id, int32_t p_x, int32_t p_y) :
index(p_id), x(p_x), y(p_y) {}
};
struct Shelf {
int32_t x = 0;
int32_t y = 0;
int32_t w = 0;
int32_t h = 0;
FontTexturePosition alloc_shelf(int32_t p_id, int32_t p_w, int32_t p_h) {
if (p_w > w || p_h > h) {
return FontTexturePosition(-1, 0, 0);
}
int32_t xx = x;
x += p_w;
w -= p_w;
return FontTexturePosition(p_id, xx, y);
}
Shelf() {}
Shelf(int32_t p_x, int32_t p_y, int32_t p_w, int32_t p_h) :
x(p_x), y(p_y), w(p_w), h(p_h) {}
};
struct ShelfPackTexture {
int32_t texture_w = 1024;
int32_t texture_h = 1024;
Ref<Image> image;
Ref<ImageTexture> texture;
bool dirty = true;
List<Shelf> shelves;
FontTexturePosition pack_rect(int32_t p_id, int32_t p_h, int32_t p_w) {
int32_t y = 0;
int32_t waste = 0;
Shelf *best_shelf = nullptr;
int32_t best_waste = std::numeric_limits<std::int32_t>::max();
for (Shelf &E : shelves) {
y += E.h;
if (p_w > E.w) {
continue;
}
if (p_h == E.h) {
return E.alloc_shelf(p_id, p_w, p_h);
}
if (p_h > E.h) {
continue;
}
if (p_h < E.h) {
waste = (E.h - p_h) * p_w;
if (waste < best_waste) {
best_waste = waste;
best_shelf = &E;
}
}
}
if (best_shelf) {
return best_shelf->alloc_shelf(p_id, p_w, p_h);
}
if (p_h <= (texture_h - y) && p_w <= texture_w) {
List<Shelf>::Element *E = shelves.push_back(Shelf(0, y, texture_w, p_h));
return E->get().alloc_shelf(p_id, p_w, p_h);
}
return FontTexturePosition(-1, 0, 0);
}
ShelfPackTexture() {}
ShelfPackTexture(int32_t p_w, int32_t p_h) :
texture_w(p_w), texture_h(p_h) {}
};
struct FontGlyph {
bool found = false;
int texture_idx = -1;
Rect2 rect;
Rect2 uv_rect;
Vector2 advance;
bool from_svg = false;
};
struct FontFallback;
struct FontForSizeFallback {
double ascent = 0.0;
double descent = 0.0;
double underline_position = 0.0;
double underline_thickness = 0.0;
double scale = 1.0;
FontFallback *owner = nullptr;
uint32_t viewport_oversampling = 0;
Vector2i size;
Vector<ShelfPackTexture> textures;
HashMap<int32_t, FontGlyph> glyph_map;
HashMap<Vector2i, Vector2> kerning_map;
#ifdef MODULE_FREETYPE_ENABLED
FT_Face face = nullptr;
FT_StreamRec stream;
#endif
~FontForSizeFallback() {
#ifdef MODULE_FREETYPE_ENABLED
if (face != nullptr) {
FT_Done_Face(face);
}
#endif
}
};
struct OversamplingLevel {
HashSet<FontForSizeFallback *> fonts;
int32_t refcount = 1;
};
mutable HashMap<uint32_t, OversamplingLevel> oversampling_levels;
struct FontFallbackLinkedVariation {
RID base_font;
int extra_spacing[4] = { 0, 0, 0, 0 };
double baseline_offset = 0.0;
};
struct FontFallback {
Mutex mutex;
TextServer::FontAntialiasing antialiasing = TextServer::FONT_ANTIALIASING_GRAY;
bool disable_embedded_bitmaps = true;
bool mipmaps = false;
bool msdf = false;
FixedSizeScaleMode fixed_size_scale_mode = FIXED_SIZE_SCALE_DISABLE;
int msdf_range = 14;
int msdf_source_size = 48;
int fixed_size = 0;
bool force_autohinter = false;
bool allow_system_fallback = true;
bool modulate_color_glyphs = false;
TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO;
bool keep_rounding_remainders = true;
Dictionary variation_coordinates;
double oversampling_override = 0.0;
double embolden = 0.0;
Transform2D transform;
BitField<TextServer::FontStyle> style_flags = 0;
String font_name;
String style_name;
int weight = 400;
int stretch = 100;
int extra_spacing[4] = { 0, 0, 0, 0 };
double baseline_offset = 0.0;
HashMap<Vector2i, FontForSizeFallback *> cache;
bool face_init = false;
Dictionary supported_varaitions;
Dictionary feature_overrides;
// Language/script support override.
HashMap<String, bool> language_support_overrides;
HashMap<String, bool> script_support_overrides;
PackedByteArray data;
const uint8_t *data_ptr;
size_t data_size;
int face_index = 0;
~FontFallback() {
for (const KeyValue<Vector2i, FontForSizeFallback *> &E : cache) {
memdelete(E.value);
}
cache.clear();
}
};
_FORCE_INLINE_ FontTexturePosition find_texture_pos_for_glyph(FontForSizeFallback *p_data, int p_color_size, Image::Format p_image_format, int p_width, int p_height, bool p_msdf) const;
#ifdef MODULE_MSDFGEN_ENABLED
_FORCE_INLINE_ FontGlyph rasterize_msdf(FontFallback *p_font_data, FontForSizeFallback *p_data, int p_pixel_range, int p_rect_margin, FT_Outline *p_outline, const Vector2 &p_advance) const;
#endif
#ifdef MODULE_FREETYPE_ENABLED
_FORCE_INLINE_ FontGlyph rasterize_bitmap(FontForSizeFallback *p_data, int p_rect_margin, FT_Bitmap p_bitmap, int p_yofs, int p_xofs, const Vector2 &p_advance, bool p_bgra) const;
#endif
bool _ensure_glyph(FontFallback *p_font_data, const Vector2i &p_size, int32_t p_glyph, FontGlyph &r_glyph, uint32_t p_oversampling = 0) const;
bool _ensure_cache_for_size(FontFallback *p_font_data, const Vector2i &p_size, FontForSizeFallback *&r_cache_for_size, bool p_silent = false, uint32_t p_oversampling = 0) const;
_FORCE_INLINE_ bool _font_validate(const RID &p_font_rid) const;
_FORCE_INLINE_ void _font_clear_cache(FontFallback *p_font_data);
static void _generateMTSDF_threaded(void *p_td, uint32_t p_y);
_FORCE_INLINE_ Vector2i _get_size(const FontFallback *p_font_data, int p_size) const {
if (p_font_data->msdf) {
return Vector2i(p_font_data->msdf_source_size * 64, 0);
} else if (p_font_data->fixed_size > 0) {
return Vector2i(p_font_data->fixed_size * 64, 0);
} else {
return Vector2i(p_size * 64, 0);
}
}
_FORCE_INLINE_ Vector2i _get_size_outline(const FontFallback *p_font_data, const Vector2i &p_size) const {
if (p_font_data->msdf) {
return Vector2i(p_font_data->msdf_source_size * 64, 0);
} else if (p_font_data->fixed_size > 0) {
return Vector2i(p_font_data->fixed_size * 64, MIN(p_size.y, 1));
} else {
return Vector2i(p_size.x * 64, p_size.y);
}
}
_FORCE_INLINE_ int _font_get_weight_by_name(const String &p_sty_name) const {
String sty_name = p_sty_name.remove_chars(" -");
if (sty_name.contains("thin") || sty_name.contains("hairline")) {
return 100;
} else if (sty_name.contains("extralight") || sty_name.contains("ultralight")) {
return 200;
} else if (sty_name.contains("light")) {
return 300;
} else if (sty_name.contains("semilight")) {
return 350;
} else if (sty_name.contains("regular")) {
return 400;
} else if (sty_name.contains("medium")) {
return 500;
} else if (sty_name.contains("semibold") || sty_name.contains("demibold")) {
return 600;
} else if (sty_name.contains("bold")) {
return 700;
} else if (sty_name.contains("extrabold") || sty_name.contains("ultrabold")) {
return 800;
} else if (sty_name.contains("black") || sty_name.contains("heavy")) {
return 900;
} else if (sty_name.contains("extrablack") || sty_name.contains("ultrablack")) {
return 950;
}
return 400;
}
_FORCE_INLINE_ int _font_get_stretch_by_name(const String &p_sty_name) const {
String sty_name = p_sty_name.remove_chars(" -");
if (sty_name.contains("ultracondensed")) {
return 50;
} else if (sty_name.contains("extracondensed")) {
return 63;
} else if (sty_name.contains("condensed")) {
return 75;
} else if (sty_name.contains("semicondensed")) {
return 87;
} else if (sty_name.contains("semiexpanded")) {
return 113;
} else if (sty_name.contains("expanded")) {
return 125;
} else if (sty_name.contains("extraexpanded")) {
return 150;
} else if (sty_name.contains("ultraexpanded")) {
return 200;
}
return 100;
}
_FORCE_INLINE_ bool _is_ital_style(const String &p_sty_name) const {
return p_sty_name.contains("italic") || p_sty_name.contains("oblique");
}
// Shaped text cache data.
struct TrimData {
int trim_pos = -1;
int ellipsis_pos = -1;
Vector<Glyph> ellipsis_glyph_buf;
};
struct TextRun {
Vector2i range;
RID font_rid;
int font_size = 0;
int64_t span_index = -1;
};
struct ShapedTextDataFallback {
Mutex mutex;
/* Source data */
RID parent; // Substring parent ShapedTextData.
int start = 0; // Substring start offset in the parent string.
int end = 0; // Substring end offset in the parent string.
String text;
String custom_punct;
TextServer::Direction direction = DIRECTION_LTR; // Desired text direction.
TextServer::Orientation orientation = ORIENTATION_HORIZONTAL;
struct Span {
int start = -1;
int end = -1;
Array fonts;
int font_size = 0;
Variant embedded_key;
String language;
Dictionary features;
Variant meta;
};
Vector<Span> spans;
int first_span = 0; // First span in the parent ShapedTextData.
int last_span = 0;
Vector<TextRun> runs;
bool runs_dirty = true;
struct EmbeddedObject {
int start = -1;
int end = -1;
InlineAlignment inline_align = INLINE_ALIGNMENT_CENTER;
Rect2 rect;
double baseline = 0;
};
HashMap<Variant, EmbeddedObject, VariantHasher, VariantComparator> objects;
/* Shaped data */
TextServer::Direction para_direction = DIRECTION_LTR; // Detected text direction.
SafeFlag valid{ false }; // String is shaped.
bool line_breaks_valid = false; // Line and word break flags are populated (and virtual zero width spaces inserted).
bool justification_ops_valid = false; // Virtual elongation glyphs are added to the string.
bool sort_valid = false;
bool text_trimmed = false;
bool preserve_invalid = true; // Draw hex code box instead of missing characters.
bool preserve_control = false; // Draw control characters.
double ascent = 0.0; // Ascent for horizontal layout, 1/2 of width for vertical.
double descent = 0.0; // Descent for horizontal layout, 1/2 of width for vertical.
double width = 0.0; // Width for horizontal layout, height for vertical.
double width_trimmed = 0.0;
int extra_spacing[4] = { 0, 0, 0, 0 };
double upos = 0.0;
double uthk = 0.0;
char32_t el_char = 0x2026;
TrimData overrun_trim_data;
bool fit_width_minimum_reached = false;
Vector<Glyph> glyphs;
Vector<Glyph> glyphs_logical;
};
// Common data.
mutable RID_PtrOwner<FontFallbackLinkedVariation> font_var_owner;
mutable RID_PtrOwner<FontFallback> font_owner;
mutable RID_PtrOwner<ShapedTextDataFallback> shaped_owner;
_FORCE_INLINE_ FontFallback *_get_font_data(const RID &p_font_rid) const {
RID rid = p_font_rid;
FontFallbackLinkedVariation *fdv = font_var_owner.get_or_null(rid);
if (unlikely(fdv)) {
rid = fdv->base_font;
}
return font_owner.get_or_null(rid);
}
struct SystemFontKey {
String font_name;
TextServer::FontAntialiasing antialiasing = TextServer::FONT_ANTIALIASING_GRAY;
bool disable_embedded_bitmaps = true;
bool italic = false;
bool mipmaps = false;
bool msdf = false;
bool force_autohinter = false;
int weight = 400;
int stretch = 100;
int msdf_range = 14;
int msdf_source_size = 48;
int fixed_size = 0;
TextServer::Hinting hinting = TextServer::HINTING_LIGHT;
TextServer::SubpixelPositioning subpixel_positioning = TextServer::SUBPIXEL_POSITIONING_AUTO;
bool keep_rounding_remainders = true;
Dictionary variation_coordinates;
double embolden = 0.0;
Transform2D transform;
int extra_spacing[4] = { 0, 0, 0, 0 };
double baseline_offset = 0.0;
bool operator==(const SystemFontKey &p_b) const {
return (font_name == p_b.font_name) && (antialiasing == p_b.antialiasing) && (italic == p_b.italic) && (disable_embedded_bitmaps == p_b.disable_embedded_bitmaps) && (mipmaps == p_b.mipmaps) && (msdf == p_b.msdf) && (force_autohinter == p_b.force_autohinter) && (weight == p_b.weight) && (stretch == p_b.stretch) && (msdf_range == p_b.msdf_range) && (msdf_source_size == p_b.msdf_source_size) && (fixed_size == p_b.fixed_size) && (hinting == p_b.hinting) && (subpixel_positioning == p_b.subpixel_positioning) && (keep_rounding_remainders == p_b.keep_rounding_remainders) && (variation_coordinates == p_b.variation_coordinates) && (embolden == p_b.embolden) && (transform == p_b.transform) && (extra_spacing[SPACING_TOP] == p_b.extra_spacing[SPACING_TOP]) && (extra_spacing[SPACING_BOTTOM] == p_b.extra_spacing[SPACING_BOTTOM]) && (extra_spacing[SPACING_SPACE] == p_b.extra_spacing[SPACING_SPACE]) && (extra_spacing[SPACING_GLYPH] == p_b.extra_spacing[SPACING_GLYPH]) && (baseline_offset == p_b.baseline_offset);
}
SystemFontKey(const String &p_font_name, bool p_italic, int p_weight, int p_stretch, RID p_font, const TextServerFallback *p_fb) {
font_name = p_font_name;
italic = p_italic;
weight = p_weight;
stretch = p_stretch;
antialiasing = p_fb->_font_get_antialiasing(p_font);
disable_embedded_bitmaps = p_fb->_font_get_disable_embedded_bitmaps(p_font);
mipmaps = p_fb->_font_get_generate_mipmaps(p_font);
msdf = p_fb->_font_is_multichannel_signed_distance_field(p_font);
msdf_range = p_fb->_font_get_msdf_pixel_range(p_font);
msdf_source_size = p_fb->_font_get_msdf_size(p_font);
fixed_size = p_fb->_font_get_fixed_size(p_font);
force_autohinter = p_fb->_font_is_force_autohinter(p_font);
hinting = p_fb->_font_get_hinting(p_font);
subpixel_positioning = p_fb->_font_get_subpixel_positioning(p_font);
keep_rounding_remainders = p_fb->_font_get_keep_rounding_remainders(p_font);
variation_coordinates = p_fb->_font_get_variation_coordinates(p_font);
embolden = p_fb->_font_get_embolden(p_font);
transform = p_fb->_font_get_transform(p_font);
extra_spacing[SPACING_TOP] = p_fb->_font_get_spacing(p_font, SPACING_TOP);
extra_spacing[SPACING_BOTTOM] = p_fb->_font_get_spacing(p_font, SPACING_BOTTOM);
extra_spacing[SPACING_SPACE] = p_fb->_font_get_spacing(p_font, SPACING_SPACE);
extra_spacing[SPACING_GLYPH] = p_fb->_font_get_spacing(p_font, SPACING_GLYPH);
baseline_offset = p_fb->_font_get_baseline_offset(p_font);
}
};
struct SystemFontCacheRec {
RID rid;
int index = 0;
};
struct SystemFontCache {
Vector<SystemFontCacheRec> var;
int max_var = 0;
};
struct SystemFontKeyHasher {
_FORCE_INLINE_ static uint32_t hash(const SystemFontKey &p_a) {
uint32_t hash = p_a.font_name.hash();
hash = hash_murmur3_one_32(p_a.variation_coordinates.hash(), hash);
hash = hash_murmur3_one_32(p_a.weight, hash);
hash = hash_murmur3_one_32(p_a.stretch, hash);
hash = hash_murmur3_one_32(p_a.msdf_range, hash);
hash = hash_murmur3_one_32(p_a.msdf_source_size, hash);
hash = hash_murmur3_one_32(p_a.fixed_size, hash);
hash = hash_murmur3_one_double(p_a.embolden, hash);
hash = hash_murmur3_one_real(p_a.transform[0].x, hash);
hash = hash_murmur3_one_real(p_a.transform[0].y, hash);
hash = hash_murmur3_one_real(p_a.transform[1].x, hash);
hash = hash_murmur3_one_real(p_a.transform[1].y, hash);
hash = hash_murmur3_one_32(p_a.extra_spacing[SPACING_TOP], hash);
hash = hash_murmur3_one_32(p_a.extra_spacing[SPACING_BOTTOM], hash);
hash = hash_murmur3_one_32(p_a.extra_spacing[SPACING_SPACE], hash);
hash = hash_murmur3_one_32(p_a.extra_spacing[SPACING_GLYPH], hash);
hash = hash_murmur3_one_double(p_a.baseline_offset, hash);
return hash_fmix32(hash_murmur3_one_32(((int)p_a.mipmaps) | ((int)p_a.msdf << 1) | ((int)p_a.italic << 2) | ((int)p_a.force_autohinter << 3) | ((int)p_a.hinting << 4) | ((int)p_a.subpixel_positioning << 8) | ((int)p_a.antialiasing << 12) | ((int)p_a.disable_embedded_bitmaps << 14) | ((int)p_a.keep_rounding_remainders << 15), hash));
}
};
mutable HashMap<SystemFontKey, SystemFontCache, SystemFontKeyHasher> system_fonts;
mutable HashMap<String, PackedByteArray> system_font_data;
void _generate_runs(ShapedTextDataFallback *p_sd) const;
void _realign(ShapedTextDataFallback *p_sd) const;
_FORCE_INLINE_ RID _find_sys_font_for_text(const RID &p_fdef, const String &p_script_code, const String &p_language, const String &p_text);
Mutex ft_mutex;
protected:
static void _bind_methods() {}
void full_copy(ShapedTextDataFallback *p_shaped);
void invalidate(ShapedTextDataFallback *p_shaped);
public:
MODBIND1RC(bool, has_feature, Feature);
MODBIND0RC(String, get_name);
MODBIND0RC(int64_t, get_features);
MODBIND1(free_rid, const RID &);
MODBIND1R(bool, has, const RID &);
MODBIND1R(bool, load_support_data, const String &);
MODBIND0RC(String, get_support_data_filename);
MODBIND0RC(String, get_support_data_info);
MODBIND1RC(bool, save_support_data, const String &);
MODBIND0RC(PackedByteArray, get_support_data);
MODBIND1RC(bool, is_locale_right_to_left, const String &);
MODBIND1RC(int64_t, name_to_tag, const String &);
MODBIND1RC(String, tag_to_name, int64_t);
/* Font interface */
MODBIND0R(RID, create_font);
MODBIND1R(RID, create_font_linked_variation, const RID &);
MODBIND2(font_set_data, const RID &, const PackedByteArray &);
MODBIND3(font_set_data_ptr, const RID &, const uint8_t *, int64_t);
MODBIND2(font_set_face_index, const RID &, int64_t);
MODBIND1RC(int64_t, font_get_face_index, const RID &);
MODBIND1RC(int64_t, font_get_face_count, const RID &);
MODBIND2(font_set_style, const RID &, BitField<FontStyle>);
MODBIND1RC(BitField<FontStyle>, font_get_style, const RID &);
MODBIND2(font_set_style_name, const RID &, const String &);
MODBIND1RC(String, font_get_style_name, const RID &);
MODBIND2(font_set_weight, const RID &, int64_t);
MODBIND1RC(int64_t, font_get_weight, const RID &);
MODBIND2(font_set_stretch, const RID &, int64_t);
MODBIND1RC(int64_t, font_get_stretch, const RID &);
MODBIND2(font_set_name, const RID &, const String &);
MODBIND1RC(String, font_get_name, const RID &);
MODBIND2(font_set_antialiasing, const RID &, TextServer::FontAntialiasing);
MODBIND1RC(TextServer::FontAntialiasing, font_get_antialiasing, const RID &);
MODBIND2(font_set_disable_embedded_bitmaps, const RID &, bool);
MODBIND1RC(bool, font_get_disable_embedded_bitmaps, const RID &);
MODBIND2(font_set_generate_mipmaps, const RID &, bool);
MODBIND1RC(bool, font_get_generate_mipmaps, const RID &);
MODBIND2(font_set_multichannel_signed_distance_field, const RID &, bool);
MODBIND1RC(bool, font_is_multichannel_signed_distance_field, const RID &);
MODBIND2(font_set_msdf_pixel_range, const RID &, int64_t);
MODBIND1RC(int64_t, font_get_msdf_pixel_range, const RID &);
MODBIND2(font_set_msdf_size, const RID &, int64_t);
MODBIND1RC(int64_t, font_get_msdf_size, const RID &);
MODBIND2(font_set_fixed_size, const RID &, int64_t);
MODBIND1RC(int64_t, font_get_fixed_size, const RID &);
MODBIND2(font_set_fixed_size_scale_mode, const RID &, FixedSizeScaleMode);
MODBIND1RC(FixedSizeScaleMode, font_get_fixed_size_scale_mode, const RID &);
MODBIND2(font_set_allow_system_fallback, const RID &, bool);
MODBIND1RC(bool, font_is_allow_system_fallback, const RID &);
MODBIND0(font_clear_system_fallback_cache);
MODBIND2(font_set_force_autohinter, const RID &, bool);
MODBIND1RC(bool, font_is_force_autohinter, const RID &);
MODBIND2(font_set_modulate_color_glyphs, const RID &, bool);
MODBIND1RC(bool, font_is_modulate_color_glyphs, const RID &);
MODBIND2(font_set_subpixel_positioning, const RID &, SubpixelPositioning);
MODBIND1RC(SubpixelPositioning, font_get_subpixel_positioning, const RID &);
MODBIND2(font_set_keep_rounding_remainders, const RID &, bool);
MODBIND1RC(bool, font_get_keep_rounding_remainders, const RID &);
MODBIND2(font_set_embolden, const RID &, double);
MODBIND1RC(double, font_get_embolden, const RID &);
MODBIND3(font_set_spacing, const RID &, SpacingType, int64_t);
MODBIND2RC(int64_t, font_get_spacing, const RID &, SpacingType);
MODBIND2(font_set_baseline_offset, const RID &, double);
MODBIND1RC(double, font_get_baseline_offset, const RID &);
MODBIND2(font_set_transform, const RID &, const Transform2D &);
MODBIND1RC(Transform2D, font_get_transform, const RID &);
MODBIND2(font_set_variation_coordinates, const RID &, const Dictionary &);
MODBIND1RC(Dictionary, font_get_variation_coordinates, const RID &);
MODBIND2(font_set_oversampling, const RID &, double);
MODBIND1RC(double, font_get_oversampling, const RID &);
MODBIND2(font_set_hinting, const RID &, TextServer::Hinting);
MODBIND1RC(TextServer::Hinting, font_get_hinting, const RID &);
MODBIND1RC(TypedArray<Vector2i>, font_get_size_cache_list, const RID &);
MODBIND1(font_clear_size_cache, const RID &);
MODBIND2(font_remove_size_cache, const RID &, const Vector2i &);
MODBIND1RC(TypedArray<Dictionary>, font_get_size_cache_info, const RID &);
MODBIND3(font_set_ascent, const RID &, int64_t, double);
MODBIND2RC(double, font_get_ascent, const RID &, int64_t);
MODBIND3(font_set_descent, const RID &, int64_t, double);
MODBIND2RC(double, font_get_descent, const RID &, int64_t);
MODBIND3(font_set_underline_position, const RID &, int64_t, double);
MODBIND2RC(double, font_get_underline_position, const RID &, int64_t);
MODBIND3(font_set_underline_thickness, const RID &, int64_t, double);
MODBIND2RC(double, font_get_underline_thickness, const RID &, int64_t);
MODBIND3(font_set_scale, const RID &, int64_t, double);
MODBIND2RC(double, font_get_scale, const RID &, int64_t);
MODBIND2RC(int64_t, font_get_texture_count, const RID &, const Vector2i &);
MODBIND2(font_clear_textures, const RID &, const Vector2i &);
MODBIND3(font_remove_texture, const RID &, const Vector2i &, int64_t);
MODBIND4(font_set_texture_image, const RID &, const Vector2i &, int64_t, const Ref<Image> &);
MODBIND3RC(Ref<Image>, font_get_texture_image, const RID &, const Vector2i &, int64_t);
MODBIND4(font_set_texture_offsets, const RID &, const Vector2i &, int64_t, const PackedInt32Array &);
MODBIND3RC(PackedInt32Array, font_get_texture_offsets, const RID &, const Vector2i &, int64_t);
MODBIND2RC(PackedInt32Array, font_get_glyph_list, const RID &, const Vector2i &);
MODBIND2(font_clear_glyphs, const RID &, const Vector2i &);
MODBIND3(font_remove_glyph, const RID &, const Vector2i &, int64_t);
MODBIND3RC(Vector2, font_get_glyph_advance, const RID &, int64_t, int64_t);
MODBIND4(font_set_glyph_advance, const RID &, int64_t, int64_t, const Vector2 &);
MODBIND3RC(Vector2, font_get_glyph_offset, const RID &, const Vector2i &, int64_t);
MODBIND4(font_set_glyph_offset, const RID &, const Vector2i &, int64_t, const Vector2 &);
MODBIND3RC(Vector2, font_get_glyph_size, const RID &, const Vector2i &, int64_t);
MODBIND4(font_set_glyph_size, const RID &, const Vector2i &, int64_t, const Vector2 &);
MODBIND3RC(Rect2, font_get_glyph_uv_rect, const RID &, const Vector2i &, int64_t);
MODBIND4(font_set_glyph_uv_rect, const RID &, const Vector2i &, int64_t, const Rect2 &);
MODBIND3RC(int64_t, font_get_glyph_texture_idx, const RID &, const Vector2i &, int64_t);
MODBIND4(font_set_glyph_texture_idx, const RID &, const Vector2i &, int64_t, int64_t);
MODBIND3RC(RID, font_get_glyph_texture_rid, const RID &, const Vector2i &, int64_t);
MODBIND3RC(Size2, font_get_glyph_texture_size, const RID &, const Vector2i &, int64_t);
MODBIND3RC(Dictionary, font_get_glyph_contours, const RID &, int64_t, int64_t);
MODBIND2RC(TypedArray<Vector2i>, font_get_kerning_list, const RID &, int64_t);
MODBIND2(font_clear_kerning_map, const RID &, int64_t);
MODBIND3(font_remove_kerning, const RID &, int64_t, const Vector2i &);
MODBIND4(font_set_kerning, const RID &, int64_t, const Vector2i &, const Vector2 &);
MODBIND3RC(Vector2, font_get_kerning, const RID &, int64_t, const Vector2i &);
MODBIND4RC(int64_t, font_get_glyph_index, const RID &, int64_t, int64_t, int64_t);
MODBIND3RC(int64_t, font_get_char_from_glyph_index, const RID &, int64_t, int64_t);
MODBIND2RC(bool, font_has_char, const RID &, int64_t);
MODBIND1RC(String, font_get_supported_chars, const RID &);
MODBIND1RC(PackedInt32Array, font_get_supported_glyphs, const RID &);
MODBIND4(font_render_range, const RID &, const Vector2i &, int64_t, int64_t);
MODBIND3(font_render_glyph, const RID &, const Vector2i &, int64_t);
MODBIND7C(font_draw_glyph, const RID &, const RID &, int64_t, const Vector2 &, int64_t, const Color &, float);
MODBIND8C(font_draw_glyph_outline, const RID &, const RID &, int64_t, int64_t, const Vector2 &, int64_t, const Color &, float);
MODBIND2RC(bool, font_is_language_supported, const RID &, const String &);
MODBIND3(font_set_language_support_override, const RID &, const String &, bool);
MODBIND2R(bool, font_get_language_support_override, const RID &, const String &);
MODBIND2(font_remove_language_support_override, const RID &, const String &);
MODBIND1R(PackedStringArray, font_get_language_support_overrides, const RID &);
MODBIND2RC(bool, font_is_script_supported, const RID &, const String &);
MODBIND3(font_set_script_support_override, const RID &, const String &, bool);
MODBIND2R(bool, font_get_script_support_override, const RID &, const String &);
MODBIND2(font_remove_script_support_override, const RID &, const String &);
MODBIND1R(PackedStringArray, font_get_script_support_overrides, const RID &);
MODBIND2(font_set_opentype_feature_overrides, const RID &, const Dictionary &);
MODBIND1RC(Dictionary, font_get_opentype_feature_overrides, const RID &);
MODBIND1RC(Dictionary, font_supported_feature_list, const RID &);
MODBIND1RC(Dictionary, font_supported_variation_list, const RID &);
MODBIND1(reference_oversampling_level, double);
MODBIND1(unreference_oversampling_level, double);
/* Shaped text buffer interface */
MODBIND2R(RID, create_shaped_text, Direction, Orientation);
MODBIND1(shaped_text_clear, const RID &);
MODBIND2(shaped_text_set_direction, const RID &, Direction);
MODBIND1RC(Direction, shaped_text_get_direction, const RID &);
MODBIND1RC(Direction, shaped_text_get_inferred_direction, const RID &);
MODBIND2(shaped_text_set_bidi_override, const RID &, const Array &);
MODBIND2(shaped_text_set_custom_punctuation, const RID &, const String &);
MODBIND1RC(String, shaped_text_get_custom_punctuation, const RID &);
MODBIND2(shaped_text_set_custom_ellipsis, const RID &, int64_t);
MODBIND1RC(int64_t, shaped_text_get_custom_ellipsis, const RID &);
MODBIND2(shaped_text_set_orientation, const RID &, Orientation);
MODBIND1RC(Orientation, shaped_text_get_orientation, const RID &);
MODBIND2(shaped_text_set_preserve_invalid, const RID &, bool);
MODBIND1RC(bool, shaped_text_get_preserve_invalid, const RID &);
MODBIND2(shaped_text_set_preserve_control, const RID &, bool);
MODBIND1RC(bool, shaped_text_get_preserve_control, const RID &);
MODBIND3(shaped_text_set_spacing, const RID &, SpacingType, int64_t);
MODBIND2RC(int64_t, shaped_text_get_spacing, const RID &, SpacingType);
MODBIND7R(bool, shaped_text_add_string, const RID &, const String &, const TypedArray<RID> &, int64_t, const Dictionary &, const String &, const Variant &);
MODBIND6R(bool, shaped_text_add_object, const RID &, const Variant &, const Size2 &, InlineAlignment, int64_t, double);
MODBIND5R(bool, shaped_text_resize_object, const RID &, const Variant &, const Size2 &, InlineAlignment, double);
MODBIND1RC(String, shaped_get_text, const RID &);
MODBIND1RC(int64_t, shaped_get_span_count, const RID &);
MODBIND2RC(Variant, shaped_get_span_meta, const RID &, int64_t);
MODBIND2RC(Variant, shaped_get_span_embedded_object, const RID &, int64_t);
MODBIND2RC(String, shaped_get_span_text, const RID &, int64_t);
MODBIND2RC(Variant, shaped_get_span_object, const RID &, int64_t);
MODBIND5(shaped_set_span_update_font, const RID &, int64_t, const TypedArray<RID> &, int64_t, const Dictionary &);
MODBIND1RC(int64_t, shaped_get_run_count, const RID &);
MODBIND2RC(String, shaped_get_run_text, const RID &, int64_t);
MODBIND2RC(Vector2i, shaped_get_run_range, const RID &, int64_t);
MODBIND2RC(RID, shaped_get_run_font_rid, const RID &, int64_t);
MODBIND2RC(int, shaped_get_run_font_size, const RID &, int64_t);
MODBIND2RC(String, shaped_get_run_language, const RID &, int64_t);
MODBIND2RC(Direction, shaped_get_run_direction, const RID &, int64_t);
MODBIND2RC(Variant, shaped_get_run_object, const RID &, int64_t);
MODBIND3RC(RID, shaped_text_substr, const RID &, int64_t, int64_t);
MODBIND1RC(RID, shaped_text_get_parent, const RID &);
MODBIND3R(double, shaped_text_fit_to_width, const RID &, double, BitField<TextServer::JustificationFlag>);
MODBIND2R(double, shaped_text_tab_align, const RID &, const PackedFloat32Array &);
MODBIND1R(bool, shaped_text_shape, const RID &);
MODBIND1R(bool, shaped_text_update_breaks, const RID &);
MODBIND1R(bool, shaped_text_update_justification_ops, const RID &);
MODBIND1RC(int64_t, shaped_text_get_trim_pos, const RID &);
MODBIND1RC(int64_t, shaped_text_get_ellipsis_pos, const RID &);
MODBIND1RC(const Glyph *, shaped_text_get_ellipsis_glyphs, const RID &);
MODBIND1RC(int64_t, shaped_text_get_ellipsis_glyph_count, const RID &);
MODBIND3(shaped_text_overrun_trim_to_width, const RID &, double, BitField<TextServer::TextOverrunFlag>);
MODBIND1RC(bool, shaped_text_is_ready, const RID &);
MODBIND1RC(const Glyph *, shaped_text_get_glyphs, const RID &);
MODBIND1R(const Glyph *, shaped_text_sort_logical, const RID &);
MODBIND1RC(int64_t, shaped_text_get_glyph_count, const RID &);
MODBIND1RC(Vector2i, shaped_text_get_range, const RID &);
MODBIND1RC(Array, shaped_text_get_objects, const RID &);
MODBIND2RC(Rect2, shaped_text_get_object_rect, const RID &, const Variant &);
MODBIND2RC(Vector2i, shaped_text_get_object_range, const RID &, const Variant &);
MODBIND2RC(int64_t, shaped_text_get_object_glyph, const RID &, const Variant &);
MODBIND1RC(Size2, shaped_text_get_size, const RID &);
MODBIND1RC(double, shaped_text_get_ascent, const RID &);
MODBIND1RC(double, shaped_text_get_descent, const RID &);
MODBIND1RC(double, shaped_text_get_width, const RID &);
MODBIND1RC(double, shaped_text_get_underline_position, const RID &);
MODBIND1RC(double, shaped_text_get_underline_thickness, const RID &);
MODBIND1RC(PackedInt32Array, shaped_text_get_character_breaks, const RID &);
MODBIND3RC(PackedInt32Array, string_get_word_breaks, const String &, const String &, int64_t);
MODBIND2RC(String, string_to_upper, const String &, const String &);
MODBIND2RC(String, string_to_lower, const String &, const String &);
MODBIND2RC(String, string_to_title, const String &, const String &);
MODBIND0(cleanup);
TextServerFallback();
~TextServerFallback();
};

View File

@@ -0,0 +1,381 @@
/**************************************************************************/
/* thorvg_svg_in_ot.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "thorvg_svg_in_ot.h"
#ifdef GDEXTENSION
// Headers for building as GDExtension plug-in.
#include <godot_cpp/classes/xml_parser.hpp>
#include <godot_cpp/core/mutex_lock.hpp>
#include <godot_cpp/godot.hpp>
#include <godot_cpp/templates/vector.hpp>
using namespace godot;
#elif defined(GODOT_MODULE)
// Headers for building as built-in module.
#include "core/error/error_macros.h"
#include "core/io/xml_parser.h"
#include "core/os/memory.h"
#include "core/os/os.h"
#include "core/string/ustring.h"
#include "core/typedefs.h"
#include "core/variant/variant.h"
#include "modules/modules_enabled.gen.h" // For svg, freetype.
#endif
#ifdef MODULE_SVG_ENABLED
#ifdef MODULE_FREETYPE_ENABLED
#include <freetype/otsvg.h>
#include <ft2build.h>
#include <cstdlib>
FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state) {
*p_state = memnew(TVG_State);
return FT_Err_Ok;
}
void tvg_svg_in_ot_free(FT_Pointer *p_state) {
TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
memdelete(state);
}
static void construct_xml(Ref<XMLParser> &parser, double &r_embox_x, double &r_embox_y, String *p_xml, int64_t &r_tag_count) {
if (parser->get_node_type() == XMLParser::NODE_ELEMENT) {
*p_xml += vformat("<%s", parser->get_node_name());
bool is_svg_tag = parser->get_node_name() == "svg";
for (int i = 0; i < parser->get_attribute_count(); i++) {
String aname = parser->get_attribute_name(i);
String value = parser->get_attribute_value(i);
if (is_svg_tag && aname == "viewBox") {
PackedStringArray vb = value.split(" ");
if (vb.size() == 4) {
r_embox_x = vb[2].to_float();
r_embox_y = vb[3].to_float();
}
} else if (is_svg_tag && aname == "width") {
r_embox_x = value.to_float();
} else if (is_svg_tag && aname == "height") {
r_embox_y = value.to_float();
} else {
*p_xml += vformat(" %s=\"%s\"", aname, value);
}
}
if (parser->is_empty()) {
*p_xml += "/>";
} else {
*p_xml += ">";
if (r_tag_count >= 0) {
r_tag_count++;
}
}
} else if (parser->get_node_type() == XMLParser::NODE_TEXT) {
*p_xml += parser->get_node_data();
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END) {
*p_xml += vformat("</%s>", parser->get_node_name());
if (r_tag_count > 0) {
r_tag_count--;
}
}
}
FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state) {
TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
if (!state) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
}
MutexLock lock(state->mutex);
FT_SVG_Document document = (FT_SVG_Document)p_slot->other;
FT_Size_Metrics metrics = document->metrics;
GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
if (!gl_state.ready) {
Ref<XMLParser> parser;
parser.instantiate();
parser->_open_buffer((const uint8_t *)document->svg_document, document->svg_document_length);
String xml_body;
double embox_x = document->units_per_EM;
double embox_y = document->units_per_EM;
TVG_DocumentCache &cache = state->document_map[document->svg_document];
if (!cache.xml_body.is_empty()) {
// If we have a cached document, that means we have already parsed it.
// All node cache should be available.
xml_body = cache.xml_body;
embox_x = cache.embox_x;
embox_y = cache.embox_y;
ERR_FAIL_COND_V(!cache.node_caches.has(p_slot->glyph_index), FT_Err_Invalid_SVG_Document);
Vector<TVG_NodeCache> &ncs = cache.node_caches[p_slot->glyph_index];
uint64_t offset = 0;
for (TVG_NodeCache &nc : ncs) {
// Seek will call read() internally.
if (parser->seek(nc.document_offset) == OK) {
int64_t tag_count = 0;
String xml_node;
// We only parse the glyph node.
do {
construct_xml(parser, embox_x, embox_y, &xml_node, tag_count);
} while (tag_count != 0 && parser->read() == OK);
xml_body = xml_body.insert(nc.body_offset + offset, xml_node);
offset += xml_node.length();
}
}
} else {
String xml_node;
String xml_body_temp;
String *p_xml = &xml_body_temp;
int64_t tag_count = -1;
bool is_in_defs = false;
while (parser->read() == OK) {
if (parser->get_node_type() == XMLParser::NODE_ELEMENT && parser->get_node_name().to_lower() == "defs") {
is_in_defs = true;
} else if (parser->get_node_type() == XMLParser::NODE_ELEMENT_END && parser->get_node_name().to_lower() == "defs") {
is_in_defs = false;
}
if (!is_in_defs && parser->has_attribute("id")) {
const String &gl_name = parser->get_named_attribute_value("id");
if (gl_name.begins_with("glyph")) {
#ifdef GDEXTENSION
int dot_pos = gl_name.find(".");
#else
int dot_pos = gl_name.find_char('.');
#endif // GDEXTENSION
int64_t gl_idx = gl_name.substr(5, (dot_pos > 0) ? dot_pos - 5 : -1).to_int();
TVG_NodeCache node_cache = TVG_NodeCache();
node_cache.document_offset = parser->get_node_offset(),
node_cache.body_offset = (uint64_t)cache.xml_body.length();
cache.node_caches[gl_idx].push_back(node_cache);
if (p_slot->glyph_index != gl_idx) {
parser->skip_section();
continue;
}
tag_count = 0;
xml_node = "";
p_xml = &xml_node;
}
}
xml_body_temp = "";
construct_xml(parser, embox_x, embox_y, p_xml, tag_count);
if (xml_body_temp.length() > 0) {
xml_body += xml_body_temp;
cache.xml_body += xml_body_temp;
continue;
}
if (tag_count == 0) {
p_xml = &xml_body_temp;
tag_count = -1;
xml_body += xml_node;
}
}
cache.embox_x = embox_x;
cache.embox_y = embox_y;
}
std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
gl_state.xml_code = xml_body.utf8();
tvg::Result result = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
if (result != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph metrics).");
}
float svg_width, svg_height;
picture->size(&svg_width, &svg_height);
double aspect_x = (svg_width > svg_height) ? svg_width / svg_height : 1.0;
double aspect_y = (svg_width < svg_height) ? svg_height / svg_width : 1.0;
result = picture->size(embox_x * aspect_x, embox_y * aspect_y);
if (result != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
}
double scale = double(embox_x * aspect_x) / double(svg_width);
double yoff = double(document->metrics.ascender + document->metrics.descender) / double(document->metrics.ascender);
double x_svg_to_out = (double)metrics.x_ppem / embox_x / scale;
double y_svg_to_out = (double)metrics.y_ppem / embox_y / scale;
gl_state.m.e11 = (double)document->transform.xx / (1 << 16);
gl_state.m.e12 = -(double)document->transform.xy / (1 << 16);
gl_state.m.e21 = -(double)document->transform.yx / (1 << 16);
gl_state.m.e22 = (double)document->transform.yy / (1 << 16);
gl_state.m.e13 = (double)document->delta.x / 64 * embox_x / metrics.x_ppem * scale;
gl_state.m.e23 = -(double)document->delta.y / 64 * embox_y / metrics.y_ppem * scale;
gl_state.m.e31 = 0;
gl_state.m.e32 = 0;
gl_state.m.e33 = 1;
result = picture->size(embox_x * aspect_x * x_svg_to_out, embox_y * aspect_y * y_svg_to_out);
if (result != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
}
result = picture->transform(gl_state.m);
if (result != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
}
picture->size(&gl_state.w, &gl_state.h);
gl_state.x = (double(p_slot->metrics.horiAdvance) / 64.0 - gl_state.w) / 2.0;
gl_state.y = -Math::ceil(gl_state.h * yoff);
gl_state.ready = true;
}
p_slot->bitmap_left = (FT_Int)gl_state.x;
p_slot->bitmap_top = (FT_Int)-gl_state.y;
double tmpd = Math::ceil(gl_state.h);
p_slot->bitmap.rows = (unsigned int)tmpd;
tmpd = Math::ceil(gl_state.w);
p_slot->bitmap.width = (unsigned int)tmpd;
p_slot->bitmap.pitch = (int)p_slot->bitmap.width * 4;
p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
float metrics_width = (float)gl_state.w;
float metrics_height = (float)gl_state.h;
float horiBearingX = (float)gl_state.x;
float horiBearingY = (float)-gl_state.y;
float vertBearingX = p_slot->metrics.horiBearingX / 64.0f - p_slot->metrics.horiAdvance / 64.0f / 2;
float vertBearingY = (p_slot->metrics.vertAdvance / 64.0f - p_slot->metrics.height / 64.0f) / 2;
float tmpf = Math::round(metrics_width * 64);
p_slot->metrics.width = (FT_Pos)tmpf;
tmpf = Math::round(metrics_height * 64);
p_slot->metrics.height = (FT_Pos)tmpf;
p_slot->metrics.horiBearingX = (FT_Pos)(horiBearingX * 64);
p_slot->metrics.horiBearingY = (FT_Pos)(horiBearingY * 64);
p_slot->metrics.vertBearingX = (FT_Pos)(vertBearingX * 64);
p_slot->metrics.vertBearingY = (FT_Pos)(vertBearingY * 64);
if (p_slot->metrics.vertAdvance == 0) {
p_slot->metrics.vertAdvance = (FT_Pos)(metrics_height * 1.2f * 64);
}
return FT_Err_Ok;
}
FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state) {
TVG_State *state = *reinterpret_cast<TVG_State **>(p_state);
if (!state) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG in OT state not initialized.");
}
MutexLock lock(state->mutex);
if (!state->glyph_map.has(p_slot->glyph_index)) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "SVG glyph not loaded.");
}
GL_State &gl_state = state->glyph_map[p_slot->glyph_index];
ERR_FAIL_COND_V_MSG(!gl_state.ready, FT_Err_Invalid_SVG_Document, "SVG glyph not ready.");
std::unique_ptr<tvg::Picture> picture = tvg::Picture::gen();
tvg::Result res = picture->load(gl_state.xml_code.get_data(), gl_state.xml_code.length(), "svg+xml", false);
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to load SVG document (glyph rendering).");
}
res = picture->size(gl_state.w, gl_state.h);
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to resize SVG document.");
}
res = picture->transform(gl_state.m);
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_SVG_Document, "Failed to apply transform to SVG document.");
}
std::unique_ptr<tvg::SwCanvas> sw_canvas = tvg::SwCanvas::gen();
res = sw_canvas->target((uint32_t *)p_slot->bitmap.buffer, (int)p_slot->bitmap.width, (int)p_slot->bitmap.width, (int)p_slot->bitmap.rows, tvg::SwCanvas::ARGB8888S);
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to create SVG canvas.");
}
res = sw_canvas->push(std::move(picture));
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to set SVG canvas source.");
}
res = sw_canvas->draw();
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to draw to SVG canvas.");
}
res = sw_canvas->sync();
if (res != tvg::Result::Success) {
ERR_FAIL_V_MSG(FT_Err_Invalid_Outline, "Failed to sync SVG canvas.");
}
state->glyph_map.erase(p_slot->glyph_index);
p_slot->bitmap.pixel_mode = FT_PIXEL_MODE_BGRA;
p_slot->bitmap.num_grays = 256;
p_slot->format = FT_GLYPH_FORMAT_BITMAP;
return FT_Err_Ok;
}
SVG_RendererHooks tvg_svg_in_ot_hooks = {
(SVG_Lib_Init_Func)tvg_svg_in_ot_init,
(SVG_Lib_Free_Func)tvg_svg_in_ot_free,
(SVG_Lib_Render_Func)tvg_svg_in_ot_render,
(SVG_Lib_Preset_Slot_Func)tvg_svg_in_ot_preset_slot,
};
SVG_RendererHooks *get_tvg_svg_in_ot_hooks() {
return &tvg_svg_in_ot_hooks;
}
#endif // MODULE_FREETYPE_ENABLED
#endif // MODULE_SVG_ENABLED

View File

@@ -0,0 +1,96 @@
/**************************************************************************/
/* thorvg_svg_in_ot.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#ifdef GDEXTENSION
// Headers for building as GDExtension plug-in.
#include <godot_cpp/core/mutex_lock.hpp>
#include <godot_cpp/godot.hpp>
#include <godot_cpp/templates/hash_map.hpp>
using namespace godot;
#elif defined(GODOT_MODULE)
// Headers for building as built-in module.
#include "core/os/mutex.h"
#include "core/templates/hash_map.h"
#include "core/typedefs.h"
#include "modules/modules_enabled.gen.h" // For svg, freetype.
#endif
#ifdef MODULE_SVG_ENABLED
#ifdef MODULE_FREETYPE_ENABLED
#include <freetype/freetype.h>
#include <freetype/otsvg.h>
#include <ft2build.h>
#include <thorvg.h>
struct GL_State {
bool ready = false;
float x = 0;
float y = 0;
float w = 0;
float h = 0;
CharString xml_code;
tvg::Matrix m;
};
struct TVG_NodeCache {
uint64_t document_offset;
uint64_t body_offset;
};
struct TVG_DocumentCache {
String xml_body;
double embox_x;
double embox_y;
HashMap<int64_t, Vector<TVG_NodeCache>> node_caches;
};
struct TVG_State {
Mutex mutex;
HashMap<uint32_t, GL_State> glyph_map;
HashMap<FT_Byte *, TVG_DocumentCache> document_map;
};
FT_Error tvg_svg_in_ot_init(FT_Pointer *p_state);
void tvg_svg_in_ot_free(FT_Pointer *p_state);
FT_Error tvg_svg_in_ot_preset_slot(FT_GlyphSlot p_slot, FT_Bool p_cache, FT_Pointer *p_state);
FT_Error tvg_svg_in_ot_render(FT_GlyphSlot p_slot, FT_Pointer *p_state);
SVG_RendererHooks *get_tvg_svg_in_ot_hooks();
#endif // MODULE_FREETYPE_ENABLED
#endif // MODULE_SVG_ENABLED