Skip to content

armgit / godot

Public Imported from GitHub
0

Godot Engine – Multi-platform 2D and 3D game engine

thorvg: Update to 1.1.3

Rémi Verscheldeedc166b0e47f
diff --git a/misc/error_suppressions/ubsan.txt b/misc/error_suppressions/ubsan.txt
index 1f6688a3984..e69adb030eb 100644
--- a/misc/error_suppressions/ubsan.txt
+++ b/misc/error_suppressions/ubsan.txt
@@ -10,7 +10,7 @@ enum:thirdparty/glslang/SPIRV/spirv.hpp
float-divide-by-zero:thirdparty/amd-fsr2/ffx_fsr2.cpp
float-divide-by-zero:thirdparty/misc/ok_color.h
float-divide-by-zero:thirdparty/rvo2/rvo2_2d/Agent2d.cpp
-float-divide-by-zero:thirdparty/thorvg/src/renderer/sw_engine/tvgSwFill.cpp
+float-divide-by-zero:thirdparty/thorvg/src/renderer/cpu_engine/tvgSwFill.cpp
float-divide-by-zero:thirdparty/thorvg/src/renderer/tvgText.h
function:thirdparty/embree/common/sys/thread.cpp
function:thirdparty/embree/kernels/common/accel.h
@@ -65,7 +65,7 @@ implicit-integer-sign-change:thirdparty/recastnavigation/Recast/Source/RecastMes
implicit-integer-sign-change:thirdparty/sdl/SDL_guid.c
implicit-integer-sign-change:thirdparty/spirv-reflect/spirv_reflect.c
implicit-integer-sign-change:thirdparty/thorvg/src/common/tvgCompressor.cpp
-implicit-integer-sign-change:thirdparty/thorvg/src/renderer/sw_engine/tvgSwRaster.cpp
+implicit-integer-sign-change:thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRaster.cpp
implicit-integer-sign-change:thirdparty/tinyexr/tinyexr.h
implicit-integer-sign-change:thirdparty/vulkan/vk_mem_alloc.h
implicit-integer-sign-change:thirdparty/xatlas/xatlas.cpp
diff --git a/modules/svg/SCsub b/modules/svg/SCsub
index 92ab5f2de6d..d985f5853f2 100644
--- a/modules/svg/SCsub
+++ b/modules/svg/SCsub
@@ -13,15 +13,14 @@ thirdparty_obj = []
thirdparty_dir = "#thirdparty/thorvg/"
thirdparty_sources = [
# common
- "src/common/tvgColor.cpp",
"src/common/tvgCompressor.cpp",
"src/common/tvgMath.cpp",
"src/common/tvgStr.cpp",
# SVG parser
+ "src/loaders/svg/tvgSvgBuilder.cpp",
"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",
@@ -33,7 +32,7 @@ thirdparty_sources = [
"src/renderer/tvgCanvas.cpp",
"src/renderer/tvgFill.cpp",
"src/renderer/tvgInitializer.cpp",
- "src/renderer/tvgLoader.cpp",
+ "src/renderer/tvgLoaderMgr.cpp",
"src/renderer/tvgPaint.cpp",
"src/renderer/tvgPicture.cpp",
"src/renderer/tvgRender.cpp",
@@ -42,17 +41,20 @@ thirdparty_sources = [
"src/renderer/tvgShape.cpp",
"src/renderer/tvgTaskScheduler.cpp",
"src/renderer/tvgText.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/tvgSwPostEffect.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",
+ # renderer cpu_engine
+ "src/renderer/cpu_engine/tvgSwBlendOp.cpp",
+ "src/renderer/cpu_engine/tvgSwFill.cpp",
+ "src/renderer/cpu_engine/tvgSwImage.cpp",
+ "src/renderer/cpu_engine/tvgSwMemPool.cpp",
+ "src/renderer/cpu_engine/tvgSwPostEffect.cpp",
+ "src/renderer/cpu_engine/tvgSwRaster.cpp",
+ "src/renderer/cpu_engine/tvgSwRasterCore.cpp",
+ # "src/renderer/cpu_engine/tvgSwRasterSimd.cpp",
+ "src/renderer/cpu_engine/tvgSwRenderer.cpp",
+ "src/renderer/cpu_engine/tvgSwRle.cpp",
+ "src/renderer/cpu_engine/tvgSwShape.cpp",
+ "src/renderer/cpu_engine/tvgSwStroke.cpp",
+ "src/renderer/cpu_engine/tvgSwUtil.cpp",
]
if env["module_webp_enabled"]:
@@ -78,7 +80,7 @@ env_thirdparty.Prepend(
thirdparty_dir + "src/common",
thirdparty_dir + "src/loaders/svg",
thirdparty_dir + "src/renderer",
- thirdparty_dir + "src/renderer/sw_engine",
+ thirdparty_dir + "src/renderer/cpu_engine",
thirdparty_dir + "src/loaders/raw",
thirdparty_dir + "src/loaders/external_png",
]
diff --git a/thirdparty/README.md b/thirdparty/README.md
index cbabe51a514..fbc2c379717 100644
--- a/thirdparty/README.md
+++ b/thirdparty/README.md
@@ -1108,7 +1108,7 @@ Files extracted from upstream source:
## thorvg
- Upstream: https://github.com/thorvg/thorvg
-- Version: 1.0.3 (d114cd9e3c32d7f77bc9b324ae5c71d7775cb7ae, 2026)
+- Version: 1.1.3 (589bc4120f2097fb1b135e552c2ef39f6581612b, 2026)
- License: MIT
Files extracted from upstream source:
diff --git a/thirdparty/thorvg/CONTRIBUTORS.md b/thirdparty/thorvg/CONTRIBUTORS.md
index 169fef1e5bf..9469ec741b2 100644
--- a/thirdparty/thorvg/CONTRIBUTORS.md
+++ b/thirdparty/thorvg/CONTRIBUTORS.md
@@ -1,60 +1,68 @@
## Project Lead
-- Hermet Park <[email protected]>
+- Hermet Park @hermet
## Core Contributors
-- Pranay Samanta <[email protected]>
-- Junsu Choi <[email protected]>
-- Mira Grudzinska <[email protected]>
-- Ruiwen Tang <[email protected]>
-- Sergii Liebodkin <[email protected]>
-- Jinny You <[email protected]>
-- Jay WenJie <[email protected]>
+- Pranay Kumar Samanta @pks2707
+- Junsu Choi @JSUYA
+- Mira Grudzinska @mgrudzinska
+- Ruiwen Tang @RuiwenTang
+- Sergii Liebodkin @SergeyLebedkin
+- Jinny You @tinyjin
+- Jay WenJie @wenjieshen
+- SoonGeon Noh @Nor-s
## Contributors
-- Prudhvi Raj Vasireddi <[email protected]>
-- Mateusz Palkowski <[email protected]>
-- Subhransu Mohanty <[email protected]>
-- Michal Szczecinski <[email protected]>
-- Shinwoo Kim <[email protected]>
-- Piotr Kalota <[email protected]>
-- Vincent Torri <[email protected]>
-- Pankaj Kumar <[email protected]>
-- Patryk Kaczmarek <[email protected]>
-- Michal Maciola <[email protected]>
-- Peter Vullings <[email protected]>
-- K. S. Ernest (iFire) Lee <[email protected]>
-- Rémi Verschelde <[email protected]>
-- Martin Liska <[email protected]>
-- Vincenzo Pupillo <[email protected]>
-- EunSik Jeong <[email protected]>
-- Rafał Mikrut <[email protected]>
-- Martin Capitanio <[email protected]>
-- YouJin Lee <[email protected]>
-- Nattu Adnan <[email protected]>
-- Gabor Kiss-Vamosi <[email protected]>
-- Lorcán Mc Donagh <[email protected]>
-- Lucas Niu <[email protected]>
-- Francisco Ramírez <[email protected]>
-- Abdelrahman Ashraf <[email protected]>
-- Neo Xu <[email protected]>
-- Thaddeus Crews <[email protected]>
-- Josh Soref <[email protected]>
-- Elliott Sales de Andrade <[email protected]>
-- Łukasz Pomietło <[email protected]>
-- Kelly Loh <[email protected]>
-- Dragoș Tiselice <[email protected]>
-- Marcin Baszczewski <[email protected]>
-- Fabian Blatz <[email protected]>
-- Jakub Marcowski <[email protected]>
-- Benjamin Halko <[email protected]>
-- Benson Muite <[email protected]>
-- kkocdko <[email protected]>
-- SoonGeon Noh <[email protected]>
-- Giseong Ji <[email protected]>
-- KunYoung Park <[email protected]>
-- Wang SiMiao 王思淼 <[email protected]>
-- Jackson Hu <[email protected]>
-- Andy French <[email protected]>
-- Andreas Deininger <[email protected]>
-- Jonathan Liu <[email protected]>
-- Shiny Chang <[email protected]>
+- Prudhvi Raj Vasireddi @prudhvirajv
+- Mateusz Palkowski @MathewP1
+- Subhransu Mohanty @smohantty
+- Michal Szczecinski @mihashco
+- Shinwoo Kim @kimcinoo
+- Piotr Kalota @pkalota
+- Vincent Torri @vtorri
+- Patryk Kaczmarek @patrykka
+- Michal Maciola @mmaciola
+- Peter Vullings @projectitis
+- K. S. Ernest @iFire @fire
+- Rémi Verschelde @akien-mga
+- Martin Liska @marxin
+- Vincenzo Pupillo @vpxyz
+- EunSik Jeong @rinechran
+- Rafał Mikrut @qarmin
+- Martin Capitanio @capnm
+- YouJin Lee @ol-of
+- Nattu Adnan @reallynattu
+- Gabor Kiss-Vamosi @kisvegabor
+- Lorcán Mc Donagh @lmdsp
+- Lucas Niu @fall2019
+- Francisco Ramírez @franramirez688
+- Abdelrahman Ashraf @theashraf
+- Neo Xu @XuNeo
+- Thaddeus Crews @Repiteo
+- Josh Soref @jsoref
+- Elliott Sales de Andrade @QuLogic
+- Łukasz Pomietło @lpogic
+- Dragoș Tiselice @dragostis
+- Marcin Baszczewski @baszczewski
+- Fabian Blatz @faxe1008
+- Jakub Marcowski @Chubercik
+- Benjamin Halko @BenjaminHalko
+- Benson Muite @bkmgit
+- kkocdko @kkocdko
+- Giseong Ji @jiggyjiggy
+- KunYoung Park @kunyoungparkk
+- Wang SiMiao 王思淼 @wangsimiao1
+- Jackson Hu @huming2207
+- Andy French @andyf-canva
+- Andreas Deininger @deining
+- Jonathan Liu @net147
+- Shiny Chang @ShinyChang
+- Mattia Basaglia @mbasaglia
+- Jongmin Kim @jmkim
+- Andrew X @LizzaM1net
+- Geordie Jay @ephemer
+- Weihang Ding @xiaozhuai
+- Duram Kim @alpakaDurumi
+- Hoyang Tsai @hoyangtsai
+- DaHee Chae @chae-dahee
+- Sunyong Jeong @jeongsunyong
+- Park Sung Jun @J-unStiN
diff --git a/thirdparty/thorvg/inc/config.h b/thirdparty/thorvg/inc/config.h
index e405722eb0a..077a16a6045 100644
--- a/thirdparty/thorvg/inc/config.h
+++ b/thirdparty/thorvg/inc/config.h
@@ -1,7 +1,7 @@
#ifndef THORVG_CONFIG_H
#define THORVG_CONFIG_H
-#define THORVG_SW_RASTER_SUPPORT
+#define THORVG_CPU_ENGINE_SUPPORT
#define THORVG_SVG_LOADER_SUPPORT
#define THORVG_PNG_LOADER_SUPPORT
#ifndef WEB_ENABLED
@@ -15,5 +15,5 @@
// For internal debugging:
//#define THORVG_LOG_ENABLED
-#define THORVG_VERSION_STRING "1.0.3"
+#define THORVG_VERSION_STRING "1.1.3"
#endif
diff --git a/thirdparty/thorvg/inc/thorvg.h b/thirdparty/thorvg/inc/thorvg.h
index 2594499e654..ea7f5da44b3 100644
--- a/thirdparty/thorvg/inc/thorvg.h
+++ b/thirdparty/thorvg/inc/thorvg.h
@@ -7,7 +7,7 @@
#include <cstdarg>
#define TVG_VERSION_MAJOR 1 // for compile-time checks
-#define TVG_VERSION_MINOR 0 // for compile-time checks
+#define TVG_VERSION_MINOR 1 // for compile-time checks
#define TVG_VERSION_MICRO 3 // for compile-time checks
#ifdef TVG_API
@@ -46,44 +46,50 @@
#define TVG_DEPRECATED
#endif
-#define _TVG_DECLARE_PRIVATE(A) \
+#define _TVG_PROTECTED_CTOR(A) \
protected: \
A(const A&) = delete; \
const A& operator=(const A&) = delete; \
A()
-#define _TVG_DECLARE_PRIVATE_BASE(A) \
- _TVG_DECLARE_PRIVATE(A); \
+#define _TVG_PROTECTED_CTOR_PIMPL(A) \
+ _TVG_PROTECTED_CTOR(A); \
public: \
struct Impl; \
Impl* pImpl
-#define _TVG_DECLARE_PRIVATE_DERIVE(A) \
- _TVG_DECLARE_PRIVATE(A); \
-protected: \
- ~A() {}
+#define _TVG_PUBLIC_DTOR_PIMPL(A) \
+ _TVG_PROTECTED_CTOR_PIMPL(A); \
+ virtual ~A()
+
+#define _TVG_PUBLIC_DTOR(A) \
+ _TVG_PROTECTED_CTOR(A); \
+public: \
+ virtual ~A() = default;
-#define _TVG_DISABLE_CTOR(A) \
+#define _TVG_DISABLE_INST(A) \
A() = delete; \
~A() = delete
-#define _TVG_DECLARE_ACCESSOR(A) \
+#define _TVG_FRIEND(A) \
friend A
namespace tvg
{
-struct RenderMethod;
struct Animation;
struct Shape;
/**
* @defgroup ThorVG ThorVG
* @brief ThorVG classes and enumerations providing C++ APIs.
+ *
+ * @note Memory allocation failure is not guaranteed to be recoverable:
+ * functions declared \c noexcept may terminate the process instead of returning a failure value.
+ * Do not rely on \c nullptr or @ref Result::FailedAllocation unless the individual API documents it.
+ * \{
*/
-/**@{*/
-
/**
* @brief Enumeration specifying the result from the APIs.
*
@@ -99,6 +105,7 @@ enum struct Result
FailedAllocation, ///< The value returned in case of unsuccessful memory allocation.
MemoryCorruption, ///< The value returned in the event of bad memory handling - e.g. failing in pointer releasing or casting
NonSupport, ///< The value returned in case of choosing unsupported engine features(options).
+ SystemError, ///< The value returned when an underlying system operation fails. @note Experimental API
Unknown = 255 ///< The value returned in all other cases.
};
@@ -108,15 +115,16 @@ enum struct Result
*/
enum struct ColorSpace : uint8_t
{
- ABGR8888 = 0, ///< The channels are joined in the order: alpha, blue, green, red. Colors are alpha-premultiplied.
- ARGB8888, ///< The channels are joined in the order: alpha, red, green, blue. Colors are alpha-premultiplied.
- ABGR8888S, ///< The channels are joined in the order: alpha, blue, green, red. Colors are un-alpha-premultiplied. @since 0.12
- ARGB8888S, ///< The channels are joined in the order: alpha, red, green, blue. Colors are un-alpha-premultiplied. @since 0.12
- Grayscale8, ///< One single channel data.
- Unknown = 255 ///< Unknown channel data. This is reserved for an initial ColorSpace value. @since 1.0
+ ABGR8888 = 0, ///< The channels are joined in the order: alpha, blue, green, red. Colors are alpha-premultiplied.
+ ARGB8888, ///< The channels are joined in the order: alpha, red, green, blue. Colors are alpha-premultiplied.
+ ABGR8888S, ///< The channels are joined in the order: alpha, blue, green, red. Colors are un-alpha-premultiplied. @since 0.12
+ ARGB8888S, ///< The channels are joined in the order: alpha, red, green, blue. Colors are un-alpha-premultiplied. @since 0.12
+ Grayscale8, ///< Single channel, 1 byte per pixel 8-bit grayscale.
+ XBGR8888, ///< 32-bit opaque color in the order: unused, blue, green, red. @note Experimental API
+ XRGB8888, ///< 32-bit opaque color in the order: unused, red, green, blue. @note Experimental API
+ Unknown = 255 ///< Unknown channel data. This is reserved for an initial ColorSpace value. @since 1.0
};
-
/**
* @brief Enumeration to specify rendering engine behavior.
*
@@ -133,9 +141,10 @@ enum struct ColorSpace : uint8_t
*/
enum struct EngineOption : uint8_t
{
- None = 0, /**< No engine options are enabled. This may be used to explicitly disable all optional behaviors. */
- Default = 1 << 0, /**< Uses the default rendering mode. */
- SmartRender = 1 << 1 /**< Enables automatic partial (smart) rendering optimizations. */
+ None = 0, /**< No engine options are enabled. This may be used to explicitly disable all optional behaviors. */
+ Default = 1 << 0, /**< Uses the default rendering mode. */
+ SmartRender = 1 << 1, /**< Enables automatic partial (smart) rendering optimizations. */
+ Aliased = 1 << 2 /**< Disables anti-aliased rendering. @note Experimental API */
};
@@ -193,11 +202,10 @@ enum struct FillRule : uint8_t
EvenOdd ///< A line from the point to a location outside the shape is drawn and its intersections with the path segments of the shape are counted. If the number of intersections is an odd number, the point is inside the shape.
};
-
/**
* @brief Defines the image filtering method used during image scaling or transformation.
*
- * @note Experimental API
+ * @since 1.1
*/
enum struct FilterMethod : uint8_t
{
@@ -249,13 +257,13 @@ enum struct BlendMethod : uint8_t
ColorDodge, ///< Divides the bottom layer by the inverted top layer. D / (255 - S)
ColorBurn, ///< Divides the inverted bottom layer by the top layer, and then inverts the result. 255 - (255 - D) / S
HardLight, ///< The same as Overlay but with the color roles reversed. (2 * S * D) if (S < 128), otherwise 255 - 2 * (255 - S) * (255 - D)
- SoftLight, ///< The same as Overlay but with applying pure black or white does not result in pure black or white. (255 - 2 * S) * (D * D) + (2 * S * D)
+ SoftLight, ///< Darkens or lightens the colors, depending on the source color value. If S <= 0.5: D - (1 - 2 * S) * D * (1 - D), otherwise: D + (2 * S - 1) * (G(D) - D), where G(D) = ((16 * D - 12) * D + 4) * D if D <= 0.25, otherwise sqrt(D).
Difference, ///< Subtracts the bottom layer from the top layer or the other way around, to always get a non-negative value. (S - D) if (S > D), otherwise (D - S)
Exclusion, ///< The result is twice the product of the top and bottom layers, subtracted from their sum. S + D - (2 * S * D)
- Hue, ///< Combine with HSL(Sh + Ds + Dl) then convert it to RGB. @since 1.0
- Saturation, ///< Combine with HSL(Dh + Ss + Dl) then convert it to RGB. @since 1.0
- Color, ///< Combine with HSL(Sh + Ss + Dl) then convert it to RGB. @since 1.0
- Luminosity, ///< Combine with HSL(Dh + Ds + Sl) then convert it to RGB. @since 1.0
+ Hue, ///< Uses the hue of the source and the saturation and luminosity of the destination. @since 1.0
+ Saturation, ///< Uses the saturation of the source and the hue and luminosity of the destination. @since 1.0
+ Color, ///< Uses the hue and saturation of the source and the luminosity of the destination. @since 1.0
+ Luminosity, ///< Uses the luminosity of the source and the hue and saturation of the destination. @since 1.0
Add, ///< Simply adds pixel values of one layer with the other. (S + D)
Composition = 255 ///< For intermediate composition layers; suitable for use with Scene or Picture. @since 1.0
};
@@ -273,15 +281,15 @@ enum struct BlendMethod : uint8_t
*/
enum struct SceneEffect : uint8_t
{
- Clear = 0, ///< Clear all previously applied scene effects, restoring the scene to its original state.
- GaussianBlur, ///< Apply a blur effect with a Gaussian filter. Param(4) = {sigma(double)[> 0], direction(int)[both: 0 / horizontal: 1 / vertical: 2], border(int)[duplicate: 0 / wrap: 1], quality(int)[0 - 100]}
- DropShadow, ///< Apply a drop shadow effect with a Gaussian Blur filter. Param(8) = {color_R(int)[0 - 255], color_G(int)[0 - 255], color_B(int)[0 - 255], opacity(int)[0 - 255], angle(double)[0 - 360], distance(double), blur_sigma(double)[> 0], quality(int)[0 - 100]}
- Fill, ///< Override the scene content color with a given fill information. Param(4) = {color_R(int)[0 - 255], color_G(int)[0 - 255], color_B(int)[0 - 255], opacity(int)[0 - 255]}
- Tint, ///< Tinting the current scene color with a given black, white color parameters. Param(7) = {black_R(int)[0 - 255], black_G(int)[0 - 255], black_B(int)[0 - 255], white_R(int)[0 - 255], white_G(int)[0 - 255], white_B(int)[0 - 255], intensity(double)[0 - 100]}
- Tritone ///< Apply a tritone color effect to the scene using three color parameters for shadows, midtones, and highlights. A blending factor determines the mix between the original color and the tritone colors. Param(9) = {Shadow_R(int)[0 - 255], Shadow_G(int)[0 - 255], Shadow_B(int)[0 - 255], Midtone_R(int)[0 - 255], Midtone_G(int)[0 - 255], Midtone_B(int)[0 - 255], Highlight_R(int)[0 - 255], Highlight_G(int)[0 - 255], Highlight_B(int)[0 - 255], Blend(int)[0 - 255]}
+ Clear = 0, ///< Clear all previously applied scene effects, restoring the scene to its original state.
+ GaussianBlur, ///< Apply a blur effect with a Gaussian filter. Param(4) = {sigma(double)[>= 0], direction(int)[both: 0 / horizontal: 1 / vertical: 2], border(int)[unused], quality(int)[0 - 100]}
+ DropShadow, ///< Apply a drop shadow effect with a Gaussian Blur filter. Param(8) = {color_R(int)[0 - 255], color_G(int)[0 - 255], color_B(int)[0 - 255], opacity(int)[0 - 255], angle(double)[0 - 360], distance(double), blur_sigma(double)[> 0], quality(int)[0 - 100]}
+ Fill, ///< Override the scene content color with a given fill information. Param(4) = {color_R(int)[0 - 255], color_G(int)[0 - 255], color_B(int)[0 - 255], opacity(int)[0 - 255]}
+ Tint, ///< Tinting the current scene color with a given black, white color parameters. Param(7) = {black_R(int)[0 - 255], black_G(int)[0 - 255], black_B(int)[0 - 255], white_R(int)[0 - 255], white_G(int)[0 - 255], white_B(int)[0 - 255], intensity(double)[0 - 100]}
+ Tritone, ///< Apply a tritone color effect to the scene using three color parameters for shadows, midtones, and highlights. A blending factor determines the mix between the original color and the tritone colors. Param(9) = {Shadow_R(int)[0 - 255], Shadow_G(int)[0 - 255], Shadow_B(int)[0 - 255], Midtone_R(int)[0 - 255], Midtone_G(int)[0 - 255], Midtone_B(int)[0 - 255], Highlight_R(int)[0 - 255], Highlight_G(int)[0 - 255], Highlight_B(int)[0 - 255], Blend(int)[0 - 255]}
+ MotionBlur ///< Apply a centered linear motion blur. Param(3) = {distance(double)[>= 0, scene-local units], angle(double)[degrees, clockwise from the positive X axis], quality(int)[0 - 100]} @note Experimental API
};
-
/**
* @brief Enumeration that defines methods used for wrapping text.
*
@@ -320,7 +328,8 @@ enum struct Type : uint8_t
Picture, ///< Picture class
Text, ///< Text class
LinearGradient = 10, ///< LinearGradient class
- RadialGradient ///< RadialGradient class
+ RadialGradient, ///< RadialGradient class
+ ConicGradient ///< ConicGradient class
};
@@ -351,6 +360,18 @@ struct Matrix
float e31, e32, e33;
};
+/**
+ * @brief A data structure representing an axis-aligned rectangular region.
+ *
+ * The region is defined by its minimum and maximum x and y coordinates.
+ *
+ * @note Experimental API
+ */
+struct Region
+{
+ int32_t xMin, yMin;
+ int32_t xMax, yMax;
+};
/**
* @brief Describes the font metrics of a text object.
@@ -427,7 +448,7 @@ struct TVG_API Paint
*
* This is useful for selectively excluding paint objects during rendering.
*
- * @param[in] on A boolean flag indicating visibility. The default is @c true.
+ * @param[in] on A boolean flag indicating visibility. The initial value is @c true.
* @c true, the object will be rendered by the engine.
* @c false, the object will be excluded from the drawing process.
*
@@ -459,7 +480,7 @@ struct TVG_API Paint
/**
* @brief Sets the scale value of the object.
*
- * @param[in] factor The value of the scaling factor. The default value is 1.
+ * @param[in] factor The value of the scaling factor. The initial value is 1.
*
* @retval Result::InsufficientCondition in case a custom transform is applied.
* @see Paint::transform()
@@ -613,11 +634,41 @@ struct TVG_API Paint
* @note To test a single point, set the region size to w = 1, h = 1.
* @note For efficiency, an AABB (axis-aligned bounding box) test is performed internally before precise hit detection.
* @note This test does not take into account the results of blending or masking.
- * @note This test does take into account the the hidden paints as well. @see Paint::visible()
+ * @note This test does take into account hidden paints as well.
+ * @see Paint::visible() const
* @since 1.0
*/
bool intersects(int32_t x, int32_t y, int32_t w = 1, int32_t h = 1) noexcept;
+ /**
+ * @brief Checks whether a given region intersects the filled area of the paint.
+ *
+ * This function determines whether the specified rectangular region—defined by (`x`, `y`, `w`, `h`)—
+ * intersects the geometric fill region of the paint object.
+ *
+ * This is useful for hit-testing purposes, such as detecting whether a user interaction (e.g., touch or click)
+ * occurs within a painted region.
+ *
+ * The paint must be updated in a Canvas beforehand—typically after the Canvas has been
+ * drawn and synchronized.
+ *
+ * @param[in] x The x-coordinate of the top-left corner of the test region.
+ * @param[in] y The y-coordinate of the top-left corner of the test region.
+ * @param[in] w The width of the region to test. Must be greater than 0.
+ * @param[in] h The height of the region to test. Must be greater than 0.
+ * @param[in] visibleOnly If @c true, hidden paints are excluded from the intersection test.
+ *
+ * @return @c true if any part of the region intersects the filled area; otherwise, @c false.
+ *
+ * @note To test a single point, set the region size to w = 1, h = 1.
+ * @note This test does not take into account the results of blending or masking.
+ *
+ * @see Paint::visible(bool on)
+ *
+ * @since Experimental API
+ */
+ bool intersects(int32_t x, int32_t y, int32_t w, int32_t h, bool visibleOnly) noexcept;
+
/**
* @brief Duplicates the object.
*
@@ -737,6 +788,15 @@ struct TVG_API Paint
*/
uint32_t id = 0;
+ /**
+ * @brief User-defined data associated with this instance.
+ *
+ * ThorVG does not interpret or manage the lifetime of this data.
+ *
+ * @note Experimental API
+ */
+ void* data = nullptr;
+
/**
* @brief Safely releases a Paint object.
*
@@ -749,10 +809,7 @@ struct TVG_API Paint
*/
static void rel(Paint* paint) noexcept;
-protected:
- virtual ~Paint();
-
- _TVG_DECLARE_PRIVATE_BASE(Paint);
+ _TVG_PUBLIC_DTOR_PIMPL(Paint);
};
@@ -814,7 +871,7 @@ struct TVG_API Fill
*
* @return The number of colors used in the gradient. This value corresponds to the length of the @p colorStops array.
*/
- uint32_t colorStops(const ColorStop** colorStops) const noexcept;
+ uint32_t colorStops(const ColorStop** colorStops = nullptr) const noexcept;
/**
* @brief Gets the FillSpread value of the fill.
@@ -852,7 +909,7 @@ struct TVG_API Fill
*/
virtual Type type() const noexcept = 0;
- _TVG_DECLARE_PRIVATE_BASE(Fill);
+ _TVG_PROTECTED_CTOR_PIMPL(Fill);
};
@@ -868,8 +925,6 @@ struct TVG_API Fill
*/
struct TVG_API Canvas
{
- virtual ~Canvas();
-
/**
* @brief Returns the list of paints currently held by the Canvas.
*
@@ -1006,7 +1061,37 @@ struct TVG_API Canvas
*/
Result sync() noexcept;
- _TVG_DECLARE_PRIVATE_BASE(Canvas);
+ /**
+ * @brief Returns the number of dirty regions of the canvas.
+ *
+ * @return The number of regions available for retrieval.
+ *
+ * @note If the active rendering backend does not support @c EngineOption::SmartRender, this function returns 1.
+ * @note This function must be called after @ref Canvas::draw() and before @ref Canvas::sync().
+ * @note Experimental API
+ *
+ * @see Canvas::dirtyRegions(Region*, uint32_t)
+ */
+ uint32_t dirtyRegions() const noexcept;
+
+ /**
+ * @brief Retrieves the dirty regions of the canvas.
+ *
+ * @param[out] regions An array to receive the dirty regions.
+ * @param[in] cnt The number of Region elements that the array can hold.
+ *
+ * @retval Result::InvalidArguments If @p regions is @c nullptr or @p cnt is zero.
+ * @retval Result::InsufficientCondition If called outside the interval after Canvas::draw() and before Canvas::sync().
+ *
+ * @note If the active rendering backend does not support @c EngineOption::SmartRender,
+ * a single region covering the entire render target is returned.
+ * @note Experimental API
+ *
+ * @see Canvas::dirtyRegions()
+ */
+ Result dirtyRegions(Region* regions, uint32_t cnt) const noexcept;
+
+ _TVG_PUBLIC_DTOR_PIMPL(Canvas);
};
@@ -1071,7 +1156,7 @@ struct TVG_API LinearGradient : Fill
*/
Type type() const noexcept override;
- _TVG_DECLARE_PRIVATE(LinearGradient);
+ _TVG_PROTECTED_CTOR(LinearGradient);
};
@@ -1137,13 +1222,73 @@ struct TVG_API RadialGradient : Fill
*
* This method can be used to check the current concrete instance type.
*
- * @return The class type ID of the LinearGradient instance.
+ * @return The class type ID of the RadialGradient instance.
*
* @since 1.0
*/
Type type() const noexcept override;
- _TVG_DECLARE_PRIVATE(RadialGradient);
+ _TVG_PROTECTED_CTOR(RadialGradient);
+};
+
+
+/**
+ * @class ConicGradient
+ *
+ * @brief A class representing the conic gradient fill of the Shape object.
+ *
+ * The gradient color transitions by the angle measured around a center point,
+ * completing a full clockwise turn from the start angle.
+ *
+ * @warning This class is not designed for inheritance.
+ *
+ * @note FillSpread options are ignored because the gradient always sweeps a full turn.
+ * @note Experimental API
+ */
+struct TVG_API ConicGradient : Fill
+{
+ /**
+ * @brief Sets the conic gradient attributes.
+ *
+ * The gradient sweeps a full turn clockwise around the center (@p cx, @p cy), beginning at @p angle.
+ * Color stop offsets from 0% to 100% map clockwise over one full turn from @p angle.
+ *
+ * @param[in] cx The horizontal coordinate of the center of the gradient.
+ * @param[in] cy The vertical coordinate of the center of the gradient.
+ * @param[in] angle The initial angle in degrees, measured clockwise from the 3 o'clock direction (positive x-axis). The default is 0.0f.
+ *
+ * @see ConicGradient::conic(float* cx, float* cy, float* angle)
+ */
+ Result conic(float cx, float cy, float angle = 0.0f) noexcept;
+
+ /**
+ * @brief Gets the conic gradient attributes.
+ *
+ * @param[out] cx The horizontal coordinate of the center of the gradient.
+ * @param[out] cy The vertical coordinate of the center of the gradient.
+ * @param[out] angle The start angle in degrees.
+ *
+ * @see ConicGradient::conic(float cx, float cy, float angle)
+ */
+ Result conic(float* cx, float* cy, float* angle = nullptr) const noexcept;
+
+ /**
+ * @brief Creates a new ConicGradient object.
+ *
+ * @return A new ConicGradient object.
+ */
+ static ConicGradient* gen() noexcept;
+
+ /**
+ * @brief Returns the ID value of this class.
+ *
+ * This method can be used to check the current concrete instance type.
+ *
+ * @return The class type ID of the ConicGradient instance.
+ */
+ Type type() const noexcept override;
+
+ _TVG_PROTECTED_CTOR(ConicGradient);
};
@@ -1207,7 +1352,7 @@ struct TVG_API Shape : Paint
* @param[in] x The horizontal coordinate of the end-point of the curve.
* @param[in] y The vertical coordinate of the end-point of the curve.
*
- * @note In case this is the first command in the path, no data from the path are rendered.
+ * @warning cubicTo must not be the first command in the path. Otherwise, rendering is not guaranteed.
*/
Result cubicTo(float cx1, float cy1, float cx2, float cy2, float x, float y) noexcept;
@@ -1230,8 +1375,8 @@ struct TVG_API Shape : Paint
*
* The rectangle is treated as a new sub-path - it is not connected with the previous sub-path.
*
- * The value of the current point is set to (@p x + @p rx, @p y) - in case @p rx is greater
- * than @p w/2 the current point is set to (@p x + @p w/2, @p y)
+ * The value of the current point is set to (@p x + @p w, @p y + @p ry) - in case @p ry is greater
+ * than @p h/2 the current point is set to (@p x + @p w, @p y + @p h/2).
*
* @param[in] x The horizontal coordinate of the upper-left corner of the rectangle.
* @param[in] y The vertical coordinate of the upper-left corner of the rectangle.
@@ -1286,7 +1431,7 @@ struct TVG_API Shape : Paint
* in the path object. A stroke is the outline drawn along the edges of the
* path's geometry.
*
- * @param[in] width The width of the stroke in pixels. Must be positive value. (The default is 0)
+ * @param[in] width The width of the stroke in pixels. Must be positive value. (The initial value is 0)
*
* @note A value of @p width 0 disables the stroke.
*
@@ -1301,12 +1446,12 @@ struct TVG_API Shape : Paint
* in the path object. The stroke color is used when rendering the outline
* of the path geometry.
*
- * @param[in] r The red color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] g The green color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] b The blue color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] a The alpha channel value in the range [0 ~ 255], where 0 is completely transparent and 255 is opaque. The default value is 0.
+ * @param[in] r The red color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] g The green color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] b The blue color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] a The alpha channel value in the range [0 ~ 255], where 0 is completely transparent and 255 is opaque. The initial value is 0.
*
- * @note If the stroke width is 0 (default), the stroke will not be visible regardless of the color.
+ * @note If the stroke width is 0 (initial value), the stroke will not be visible regardless of the color.
* @note Either a solid color or a gradient fill is applied, depending on what was set as last.
*
* @see strokeWidth()
@@ -1321,7 +1466,7 @@ struct TVG_API Shape : Paint
*
* @retval Result::InvalidArgument In case a @c nullptr is passed as the argument.
*
- * @note If the stroke width is 0 (default), the stroke will not be visible regardless of the color.
+ * @note If the stroke width is 0 (initial value), the stroke will not be visible regardless of the color.
* @note Either a solid color or a gradient fill is applied, depending on what was set as last.
*
* @see strokeFill(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
@@ -1350,7 +1495,7 @@ struct TVG_API Shape : Paint
/**
* @brief Sets the cap style of the stroke in the open sub-paths.
*
- * @param[in] cap The cap style value. The default value is @c StrokeCap::Square.
+ * @param[in] cap The cap style value. The initial value is @c StrokeCap::Square.
*
*/
Result strokeCap(StrokeCap cap) noexcept;
@@ -1360,7 +1505,7 @@ struct TVG_API Shape : Paint
*
* The join style is used for joining the two line segment while stroking the path.
*
- * @param[in] join The join style value. The default value is @c StrokeJoin::Bevel.
+ * @param[in] join The join style value. The initial value is @c StrokeJoin::Bevel.
*
*/
Result strokeJoin(StrokeJoin join) noexcept;
@@ -1368,7 +1513,7 @@ struct TVG_API Shape : Paint
/**
* @brief Sets the stroke miterlimit.
*
- * @param[in] miterlimit The miterlimit imposes a limit on the extent of the stroke join, when the @c StrokeJoin::Miter join style is set. The default value is 4.
+ * @param[in] miterlimit The miterlimit imposes a limit on the extent of the stroke join, when the @c StrokeJoin::Miter join style is set. The initial value is 4.
*
* @retval Result::InvalidArgument for @p miterlimit values less than zero.
*
@@ -1395,10 +1540,10 @@ struct TVG_API Shape : Paint
*
* The parts of the shape defined as inner are colored.
*
- * @param[in] r The red color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] g The green color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] b The blue color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] a The alpha channel value in the range [0 ~ 255], where 0 is completely transparent and 255 is opaque. The default value is 0.
+ * @param[in] r The red color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] g The green color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] b The blue color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] a The alpha channel value in the range [0 ~ 255], where 0 is completely transparent and 255 is opaque. The initial value is 0.
*
* @note Either a solid color or a gradient fill is applied, depending on what was set as last.
*/
@@ -1419,7 +1564,7 @@ struct TVG_API Shape : Paint
* @brief Sets the fill rule for the shape.
*
* Specifies how the interior of the shape is determined when its path intersects itself.
- * The default fill rule is @c FillRule::NonZero.
+ * The initial fill rule is @c FillRule::NonZero.
*
* @param[in] r The fill rule to apply to the shape.
*/
@@ -1428,7 +1573,7 @@ struct TVG_API Shape : Paint
/**
* @brief Sets the rendering order of the stroke and the fill.
*
- * @param[in] strokeFirst If @c true the stroke is rendered before the fill, otherwise the stroke is rendered as the second one (the default option).
+ * @param[in] strokeFirst If @c true the stroke is rendered before the fill, otherwise the stroke is rendered as the second one (the initial option).
*
* @since 0.10
*/
@@ -1563,7 +1708,7 @@ struct TVG_API Shape : Paint
*/
Type type() const noexcept override;
- _TVG_DECLARE_PRIVATE_DERIVE(Shape);
+ _TVG_PROTECTED_CTOR(Shape);
};
@@ -1612,6 +1757,7 @@ struct TVG_API Picture : Paint
*
* @retval Result::InvalidArguments In case no data are provided or the @p size is zero or less.
* @retval Result::NonSupport When trying to load a file with an unknown extension.
+ * @retval Result::InsufficientCondition If a vector asset has already been loaded into the picture.
*
* @warning It's the user responsibility to release the @p data memory.
*
@@ -1699,6 +1845,9 @@ struct TVG_API Picture : Paint
* @param[in] cs Specifies how the 32-bit color values should be interpreted.
* @param[in] copy If @c true, the data is copied into the engine's local buffer. If @c false, the data is not copied.
*
+ * @note If the memory data pointed to by @p data is modified, calling this API will re-upload the updated content to the canvas.
+ * @note @c ColorSpace::XBGR8888 and @c ColorSpace::XRGB8888 overwrite fully covered pixels without alpha blending.
+ *
* @since 0.9
*/
Result load(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, bool copy = false) noexcept;
@@ -1733,25 +1882,28 @@ struct TVG_API Picture : Paint
* Specifies how the image data should be filtered when it is scaled or transformed
* during rendering. This affects the visual quality and performance of the output.
*
- * @param[in] method The filtering method to apply. Default is @c FilterMethod::Bilinear.
+ * @param[in] method The filtering method to apply. The initial value is @c FilterMethod::Bilinear.
*
* @return Always returns @c Result::Success.
*
* @see FilterMethod
- * @note Experimental API
+ * @since 1.1
*/
Result filter(FilterMethod method) noexcept;
/**
- * @brief Retrieve a paint object from the Picture scene by its Unique ID.
+ * @brief Retrieve a Paint object from the Picture scene by its unique ID.
+ *
+ * Searches for a Paint object within the Picture scene that matches the given @p id.
*
- * This function searches for a paint object within the Picture scene that matches the provided @p id.
+ * @param[in] id The unique identifier of the Paint object.
*
- * @param[in] id The Unique ID of the paint object.
+ * @return A pointer to the matching Paint object, or @c nullptr if not found.
*
- * @return A pointer to the paint object that matches the given identifier, or @c nullptr if no matching paint object is found.
+ * @note Setting @ref Picture::accessible to @c true enables more efficient access.
*
* @see Accessor::id()
+ * @see Picture::accessible
*
* @since 1.0
*/
@@ -1780,8 +1932,25 @@ struct TVG_API Picture : Paint
*/
Type type() const noexcept override;
- _TVG_DECLARE_ACCESSOR(Animation);
- _TVG_DECLARE_PRIVATE_DERIVE(Picture);
+ /**
+ * @brief Enable or disable accessible mode for a Picture.
+ *
+ * When accessible mode is enabled, the Picture maintains an internal mapping
+ * of ID-accessible vector assets nodes (such as SVG), allowing efficient access to Paint objects
+ * and their associated identifier information via Accessor APIs.
+ *
+ * When disabled, no additional mapping is maintained and all nodes are treated
+ * as general traversal targets.
+ *
+ * @see Picture::paint()
+ * @see Accessor::name()
+ *
+ * @since 1.1
+ */
+ bool accessible = false;
+
+ _TVG_FRIEND(Animation);
+ _TVG_PROTECTED_CTOR(Picture);
};
@@ -1902,7 +2071,7 @@ struct TVG_API Scene : Paint
*/
Type type() const noexcept override;
- _TVG_DECLARE_PRIVATE_DERIVE(Scene);
+ _TVG_PROTECTED_CTOR(Scene);
};
@@ -1990,8 +2159,8 @@ struct TVG_API Text : Paint
* Otherwise, treat it as an anchor within the text bounds which point of
* the text box is pinned to the paint position.
*
- * @param[in] x Horizontal alignment/anchor in [0..1]: 0=left/start, 0.5=center, 1=right/end. (Default is 0)
- * @param[in] y Vertical alignment/anchor in [0..1]: 0=top, 0.5=middle, 1=bottom. (Default is 0)
+ * @param[in] x Horizontal alignment/anchor in [0..1]: 0=left/start, 0.5=center, 1=right/end. (The initial value is 0)
+ * @param[in] y Vertical alignment/anchor in [0..1]: 0=top, 0.5=middle, 1=bottom. (The initial value is 0)
*
* @since 1.0
*
@@ -2006,8 +2175,8 @@ struct TVG_API Text : Paint
* the text may wrap/align inside it. If width/height == 0, the axis is
* unconstrained and @ref align() acts as an anchor on that axis.
*
- * @param[in] w Layout width in user space. Use 0 for no horizontal constraint. (Default is 0)
- * @param[in] h Layout height in user space. Use 0 for no vertical constraint. (Default is 0)
+ * @param[in] w Layout width in user space. Use 0 for no horizontal constraint. (The initial value is 0)
+ * @param[in] h Layout height in user space. Use 0 for no vertical constraint. (The initial value is 0)
*
* @note This defines constraints only; alignment/anchoring is controlled by @ref align().
* @since 1.0
@@ -2024,7 +2193,7 @@ struct TVG_API Text : Paint
* The wrapping mode determines whether text is truncated, wrapped by character or word,
* or adjusted automatically. An ellipsis mode is also available for truncation with "...".
*
- * @param[in] mode The wrapping strategy to apply. Default is @c TextWrap::None
+ * @param[in] mode The wrapping strategy to apply. The initial value is @c TextWrap::None
*
* @see TextWrap
* @see Text::lines()
@@ -2042,7 +2211,7 @@ struct TVG_API Text : Paint
* @return The total number of lines.
*
* @see Text::wrap()
- * @since Experimental API
+ * @since 1.1
*/
uint32_t lines() noexcept;
@@ -2074,7 +2243,7 @@ struct TVG_API Text : Paint
* This function adds an outline to the text with the specified width and RGB color.
* The outline enhances the visibility of the text by rendering a stroke around its glyphs.
*
- * @param width The width of the outline. Must be positive value. (The default is 0)
+ * @param width The width of the outline. Must be positive value. (The initial value is 0)
* @param r Red component of the outline color (0–255).
* @param g Green component of the outline color (0–255).
* @param b Blue component of the outline color (0–255).
@@ -2089,9 +2258,9 @@ struct TVG_API Text : Paint
/**
* @brief Sets the text color.
*
- * @param[in] r The red color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] g The green color channel value in the range [0 ~ 255]. The default value is 0.
- * @param[in] b The blue color channel value in the range [0 ~ 255]. The default value is 0.
+ * @param[in] r The red color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] g The green color channel value in the range [0 ~ 255]. The initial value is 0.
+ * @param[in] b The blue color channel value in the range [0 ~ 255]. The initial value is 0.
*
* @see Text::font()
* @see Text::outline()
@@ -2126,11 +2295,11 @@ struct TVG_API Text : Paint
*
* @param[in] letter The scale factor for letter spacing.
* Values > 1.0 increase spacing, values < 1.0 decrease it.
- * Must be greater than or equal to 0.0. (default: 1.0)
+ * Must be greater than or equal to 0.0. The initial value is 1.0.
*
* @param[in] line The scale factor for line spacing.
* Values > 1.0 increase line spacing, values < 1.0 decrease it.
- * Must be greater than or equal to 0.0. (default: 1.0)
+ * Must be greater than or equal to 0.0. The initial value is 1.0.
*
* @since 1.0
*/
@@ -2167,6 +2336,8 @@ struct TVG_API Text : Paint
*
* @param[in] ch A pointer to a UTF-8 encoded character.
* @param[out] metrics A reference to a @ref GlyphMetrics structure to be filled with the resulting values.
+ * @param[out] next An optional pointer that receives the position immediately
+ * following the processed UTF-8 character.
*
* @return Result::InsufficientCondition if no font or size has been set yet.
* @return Result::InvalidArguments if the given character is invalid or not supported.
@@ -2175,10 +2346,10 @@ struct TVG_API Text : Paint
* @note Currently, ThorVG only supports horizontal text layout.
* @note Experimental API
*/
- Result metrics(const char* ch, GlyphMetrics& metrics) const noexcept;
+ Result metrics(const char* ch, GlyphMetrics& metrics, const char** next = nullptr) const noexcept;
/**
- * @brief Loads a scalable font data (ttf) from a file.
+ * @brief Loads a scalable font data (ttf/otf) from a file.
*
* ThorVG efficiently caches the loaded data using the specified @p path as a key.
* This means that loading the same file again will not result in duplicate operations;
@@ -2196,7 +2367,7 @@ struct TVG_API Text : Paint
static Result load(const char* filename) noexcept;
/**
- * @brief Loads a scalable font data (ttf) from a memory block of a given size.
+ * @brief Loads a scalable font data (ttf/otf) from a memory block of a given size.
*
* ThorVG efficiently caches the loaded font data using the specified @p name as a key.
* This means that loading the same fonts again will not result in duplicate operations.
@@ -2263,7 +2434,7 @@ struct TVG_API Text : Paint
*/
Type type() const noexcept override;
- _TVG_DECLARE_PRIVATE_DERIVE(Text);
+ _TVG_PROTECTED_CTOR(Text);
};
@@ -2293,9 +2464,11 @@ struct TVG_API SwCanvas final : Canvas
*
* @warning Do not access @p buffer during Canvas::add() - Canvas::sync(). It should not be accessed while the engine is writing on it.
*
+ * @note Currently, only @c ColorSpace::ABGR8888S, @c ColorSpace::ABGR8888, @c ColorSpace::ARGB8888S, and @c ColorSpace::ARGB8888 are supported for @p cs.
+ *
* @see Canvas::viewport()
* @see Canvas::sync()
- */
+ */
Result target(uint32_t* buffer, uint32_t stride, uint32_t w, uint32_t h, ColorSpace cs) noexcept;
/**
@@ -2312,7 +2485,7 @@ struct TVG_API SwCanvas final : Canvas
*/
static SwCanvas* gen(EngineOption op = EngineOption::Default) noexcept;
- _TVG_DECLARE_PRIVATE(SwCanvas);
+ _TVG_PROTECTED_CTOR(SwCanvas);
};
@@ -2372,7 +2545,7 @@ struct TVG_API GlCanvas final : Canvas
*/
static GlCanvas* gen(EngineOption op = EngineOption::Default) noexcept;
- _TVG_DECLARE_PRIVATE(GlCanvas);
+ _TVG_PROTECTED_CTOR(GlCanvas);
};
@@ -2381,35 +2554,72 @@ struct TVG_API GlCanvas final : Canvas
*
* @brief A class for the rendering graphic elements with a WebGPU raster engine.
*
- * @warning Please do not use it. This class is not fully supported yet.
- *
* @since 0.15
*/
struct TVG_API WgCanvas final : Canvas
{
~WgCanvas() override;
+ /**
+ * @brief Encapsulates the WebGPU context required for rendering.
+ *
+ * This structure contains the WebGPU objects used to initialize the rendering backend.
+ *
+ * @note Experimental API
+ */
+ struct Context
+ {
+ void* instance; // WGPUInstance, context for all other wgpu objects.
+ void* adapter; // WGPUAdapter, the adapter associated with the rendering device.
+ void* device; // WGPUDevice, a desired handle for the wgpu device.
+ };
+
/**
* @brief Sets the drawing target for the rasterization.
*
- * @param[in] device WGPUDevice, a desired handle for the wgpu device. If it is @c nullptr, ThorVG will assign an appropriate device internally.
+ * @param[in] device WGPUDevice, a desired handle for the wgpu device.
* @param[in] instance WGPUInstance, context for all other wgpu objects.
* @param[in] target Either WGPUSurface or WGPUTexture, serving as handles to a presentable surface or texture.
* @param[in] w The width of the target.
* @param[in] h The height of the target.
- * @param[in] cs Specifies how the pixel values should be interpreted. Currently, it only allows @c ColorSpace::ABGR8888S as @c WGPUTextureFormat_RGBA8Unorm.
+ * @param[in] cs Specifies how the pixel values should be interpreted. Currently, it allows @c ColorSpace::ABGR8888, @c ColorSpace::ABGR8888S, and @c ColorSpace::XBGR8888.
* @param[in] type @c 0: surface, @c 1: texture are used as pesentable target.
*
* @retval Result::InsufficientCondition if the canvas is performing rendering. Please ensure the canvas is synced.
* @retval Result::NonSupport In case the wg engine is not supported.
*
- * @since 1.0
+ * @warning For alpha formats, this target API uses the default alpha mode.
+ * @note @c ColorSpace::XBGR8888 selects opaque surface composition and ignores output alpha. This format requires @p type to be @c 0.
*
+ * @see WgCanvas::target(const Context&, void*, uint32_t, uint32_t, ColorSpace, int)
* @see Canvas::viewport()
* @see Canvas::sync()
+ *
+ * @since 1.0
*/
Result target(void* device, void* instance, void* target, uint32_t w, uint32_t h, ColorSpace cs, int type = 0) noexcept;
+ /**
+ * @brief Sets the drawing target for the rasterization.
+ *
+ * @param[in] context WebGPU context.
+ * @param[in] target Either WGPUSurface or WGPUTexture, serving as handles to a presentable surface or texture.
+ * @param[in] w The width of the target.
+ * @param[in] h The height of the target.
+ * @param[in] cs Specifies how the pixel values should be interpreted. Currently, it allows @c ColorSpace::ABGR8888, @c ColorSpace::ABGR8888S, and @c ColorSpace::XBGR8888.
+ * @param[in] type @c 0: surface, @c 1: texture are used as pesentable target.
+ *
+ * @retval Result::InsufficientCondition if the canvas is performing rendering. Please ensure the canvas is synced.
+ * @retval Result::NonSupport In case the wg engine is not supported.
+ *
+ * @see Canvas::viewport()
+ * @see Canvas::sync()
+ *
+ * @note @c ColorSpace::XBGR8888 selects opaque surface composition and ignores output alpha. This format requires @p type to be @c 0.
+ * @note Experimental API
+ */
+ Result target(const Context& context, void* target, uint32_t w, uint32_t h, ColorSpace cs, int type = 0) noexcept;
+
/**
* @brief Creates a new WebGPU Canvas object with optional rendering engine settings.
*
@@ -2428,7 +2638,7 @@ struct TVG_API WgCanvas final : Canvas
*/
static WgCanvas* gen(EngineOption op = EngineOption::Default) noexcept;
- _TVG_DECLARE_PRIVATE(WgCanvas);
+ _TVG_PROTECTED_CTOR(WgCanvas);
};
@@ -2442,18 +2652,19 @@ struct TVG_API Initializer final
/**
* @brief Initializes the ThorVG engine runtime.
*
- * ThorVG requires an active runtime environment for rendering operations.
- * This function sets up an internal task scheduler and creates a specified number
- * of worker threads to enable parallel rendering.
+ * Sets up the internal task scheduler and launches the specified
+ * number of worker threads for parallel rendering operations.
*
- * @param[in] threads The number of worker threads to launch.
- * A value of 0 indicates that only the main thread will be used.
+ * @param[in] threads The number of worker threads to create.
+ * A value of 0 disables worker threads, executing rendering tasks on the calling thread.
*
* @return Result indicating success or failure of initialization.
*
- * @note This function uses internal reference counting to allow multiple init() calls.
- * However, the number of threads is fixed during the first successful initialization
- * and cannot be changed in subsequent calls.
+ * @note Initialization is reference-counted. Each successful call increments the reference count.
+ * The worker thread count is determined by the first successful initialization and remains
+ * unchanged until the engine is fully terminated.
+ *
+ * @warning Each pair of init() and term() calls must be made from the same thread.
*
* @see Initializer::term()
*/
@@ -2462,12 +2673,15 @@ struct TVG_API Initializer final
/**
* @brief Terminates the ThorVG engine.
*
- * Cleans up resources and stops any internal threads initialized by init().
+ * Releases internal resources and shuts down worker threads initialized by Initializer::init().
*
- * @retval Result::InsufficientCondition Returned if there is nothing to terminate (e.g., init() was not called).
+ * @retval Result::InsufficientCondition If the engine is not initialized.
+ *
+ * @note Initialization is reference-counted. Each call to term() decrements the reference count,
+ * and the engine is fully terminated only when the count reaches zero.
+ *
+ * @warning Each pair of init() and term() calls must be made from the same thread.
*
- * @note The initializer maintains a reference count for safe repeated use.
- * Only the final call to term() will fully shut down the engine.
* @see Initializer::init()
*/
static Result term() noexcept;
@@ -2485,7 +2699,7 @@ struct TVG_API Initializer final
*/
static const char* version(uint32_t* major, uint32_t* minor, uint32_t* micro) noexcept;
- _TVG_DISABLE_CTOR(Initializer);
+ _TVG_DISABLE_INST(Initializer);
};
@@ -2500,8 +2714,6 @@ struct TVG_API Initializer final
*/
struct TVG_API Animation
{
- virtual ~Animation();
-
/**
* @brief Specifies the current frame in the animation.
*
@@ -2577,7 +2789,7 @@ struct TVG_API Animation
* @retval Result::InvalidArguments If the @p begin is higher than @p end.
* @retval Result::NonSupport When it's not animatable.
*
- * @note Animation allows a range from 0.0 to the total frame. @p end should not be higher than @p begin.
+ * @note Animation allows a range from 0.0 to the total frame. @p end should not be lower than @p begin.
* @note If a marker has been specified, its range will be disregarded.
*
* @see LottieAnimation::segment(const char* marker)
@@ -2607,10 +2819,9 @@ struct TVG_API Animation
*/
static Animation* gen() noexcept;
- _TVG_DECLARE_PRIVATE_BASE(Animation);
+ _TVG_PUBLIC_DTOR_PIMPL(Animation);
};
-
/**
* @class Saver
*
@@ -2626,12 +2837,12 @@ struct TVG_API Animation
*
* @see Picture::load()
*
+ * @warning This class is not designed for inheritance.
+ *
* @since 0.5
*/
-struct TVG_API Saver final
+struct TVG_API Saver
{
- ~Saver();
-
/**
* @brief Sets the base background content for the saved image.
*
@@ -2709,10 +2920,9 @@ struct TVG_API Saver final
*/
static Saver* gen() noexcept;
- _TVG_DECLARE_PRIVATE_BASE(Saver);
+ _TVG_PUBLIC_DTOR(Saver);
};
-
/**
* @class Accessor
*
@@ -2721,13 +2931,12 @@ struct TVG_API Saver final
* The Accessor helps you search specific nodes to read the property information, figure out the structure of the scene tree and its size.
*
* @warning We strongly warn you not to change the paints of a scene unless you really know the design-structure.
+ * @warning This class is not designed for inheritance.
*
* @since 0.10
*/
-struct TVG_API Accessor final
+struct TVG_API Accessor
{
- ~Accessor();
-
/**
* @brief Set the access function for traversing the Picture scene tree nodes.
*
@@ -2752,11 +2961,34 @@ struct TVG_API Accessor final
* @return The generated unique identifier value.
*
* @see Paint::id
+ * @see Picture::paint()
*
* @since 1.0
*/
static uint32_t id(const char* name) noexcept;
+ /**
+ * @brief Retrieve the original name string from a given unique ID.
+ *
+ * Returns the name associated with the specified identifier.
+ *
+ * This method is only valid when @ref Picture::accessible is set to @c true
+ * for the Picture associated with the given @p paint in @ref Accessor::set() Otherwise, the name
+ * information may not be available.
+ *
+ * @param[in] id The unique identifier.
+ *
+ * @return The corresponding name string, or @c nullptr if not found or unavailable.
+ *
+ * @see Accessor::id()
+ * @see Accessor::set()
+ * @see Picture::accessible
+ *
+ * @note This function is only available within Accessor callbacks registered via @ref Accessor::set().
+ * @since 1.1
+ */
+ const char* name(uint32_t id) noexcept;
+
/**
* @brief Creates a new Accessor object.
*
@@ -2764,7 +2996,7 @@ struct TVG_API Accessor final
*/
static Accessor* gen() noexcept;
- _TVG_DECLARE_PRIVATE_BASE(Accessor);
+ _TVG_PUBLIC_DTOR(Accessor);
};
/** @}*/
diff --git a/thirdparty/thorvg/patches/0001-let-delete-be-delete.patch b/thirdparty/thorvg/patches/0001-let-delete-be-delete.patch
index 430950c22bc..2aee2a99d5c 100644
--- a/thirdparty/thorvg/patches/0001-let-delete-be-delete.patch
+++ b/thirdparty/thorvg/patches/0001-let-delete-be-delete.patch
@@ -1,22 +1,22 @@
diff --git a/thirdparty/thorvg/src/common/tvgCommon.h b/thirdparty/thorvg/src/common/tvgCommon.h
-index a98d5eb818..386df483b5 100644
+index e07c879241..829da57d02 100644
--- a/thirdparty/thorvg/src/common/tvgCommon.h
+++ b/thirdparty/thorvg/src/common/tvgCommon.h
-@@ -67,9 +67,6 @@ using namespace tvg;
- #define strncpy strncpy_s
+@@ -63,9 +63,6 @@ using namespace tvg;
+ #define TVG_FALLTHROUGH
#endif
-void* operator new(std::size_t size);
-void operator delete(void* ptr) noexcept;
-
- namespace tvg {
-
- enum class FileType { Png = 0, Jpg, Webp, Svg, Lot, Ttf, Raw, Gif, Unknown };
+ namespace tvg
+ {
+ enum class FileType
diff --git a/thirdparty/thorvg/src/renderer/tvgInitializer.cpp b/thirdparty/thorvg/src/renderer/tvgInitializer.cpp
-index cd47d70f30..6c7777889f 100644
+index e52971a67b..74502807d8 100644
--- a/thirdparty/thorvg/src/renderer/tvgInitializer.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgInitializer.cpp
-@@ -131,27 +131,3 @@ uint16_t THORVG_VERSION_NUMBER()
+@@ -136,27 +136,3 @@ uint16_t THORVG_VERSION_NUMBER()
{
return _version;
}
diff --git a/thirdparty/thorvg/src/common/tvgArray.h b/thirdparty/thorvg/src/common/tvgArray.h
index c2b273d1422..56b17ed4edd 100644
--- a/thirdparty/thorvg/src/common/tvgArray.h
+++ b/thirdparty/thorvg/src/common/tvgArray.h
@@ -159,6 +159,11 @@ struct Array
return data[0];
}
+ T& pick()
+ {
+ return data[--count];
+ }
+
void pop()
{
if (count > 0) --count;
diff --git a/thirdparty/thorvg/src/common/tvgColor.cpp b/thirdparty/thorvg/src/common/tvgColor.cpp
deleted file mode 100644
index b025ee14733..00000000000
--- a/thirdparty/thorvg/src/common/tvgColor.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2026 ThorVG project. All rights reserved.
-
- * 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 "tvgMath.h"
-#include "tvgColor.h"
-namespace tvg
-{
-
-void hsl2rgb(float h, float s, float l, uint8_t& r, uint8_t& g, uint8_t& b)
-{
- if (tvg::zero(s)) {
- r = g = b = (uint8_t)nearbyint(l * 255.0f);
- return;
- }
-
- if (tvg::equal(h, 360.0f)) {
- h = 0.0f;
- } else {
- h = fmod(h, 360.0f);
- if (h < 0.0f) h += 360.0f;
- h /= 60.0f;
- }
-
- auto v = (l <= 0.5f) ? (l * (1.0f + s)) : (l + s - (l * s));
- auto p = l + l - v;
- auto sv = tvg::zero(v) ? 0.0f : (v - p) / v;
- auto i = static_cast<uint8_t>(h);
- auto f = h - i;
- auto vsf = v * sv * f;
- auto t = p + vsf;
- auto q = v - vsf;
- float tr, tg, tb;
-
- switch (i) {
- case 0: tr = v; tg = t; tb = p; break;
- case 1: tr = q; tg = v; tb = p; break;
- case 2: tr = p; tg = v; tb = t; break;
- case 3: tr = p; tg = q; tb = v; break;
- case 4: tr = t; tg = p; tb = v; break;
- case 5: tr = v; tg = p; tb = q; break;
- default: tr = tg = tb = 0.0f; break;
- }
- r = (uint8_t)nearbyint(tr * 255.0f);
- g = (uint8_t)nearbyint(tg * 255.0f);
- b = (uint8_t)nearbyint(tb * 255.0f);
-}
-
-}
diff --git a/thirdparty/thorvg/src/common/tvgColor.h b/thirdparty/thorvg/src/common/tvgColor.h
index 8a00707047f..401208f44b4 100644
--- a/thirdparty/thorvg/src/common/tvgColor.h
+++ b/thirdparty/thorvg/src/common/tvgColor.h
@@ -42,8 +42,6 @@ namespace tvg
{
float h, s, l;
};
-
- void hsl2rgb(float h, float s, float l, uint8_t& r, uint8_t& g, uint8_t& b);
}
#endif //_TVG_COLOR_H_
diff --git a/thirdparty/thorvg/src/common/tvgCommon.h b/thirdparty/thorvg/src/common/tvgCommon.h
index 386df483b50..829da57d029 100644
--- a/thirdparty/thorvg/src/common/tvgCommon.h
+++ b/thirdparty/thorvg/src/common/tvgCommon.h
@@ -63,13 +63,21 @@ using namespace tvg;
#define TVG_FALLTHROUGH
#endif
-#if defined(_MSC_VER) && defined(__clang__)
- #define strncpy strncpy_s
-#endif
-
-namespace tvg {
-
- enum class FileType { Png = 0, Jpg, Webp, Svg, Lot, Ttf, Raw, Gif, Unknown };
+namespace tvg
+{
+ enum class FileType
+ {
+ Svg = 0,
+ Lot,
+ Sfnt,
+ Png,
+ Jpg,
+ Webp,
+ Media,
+ Raw,
+ Gif,
+ Unknown
+ };
#ifdef THORVG_LOG_ENABLED
constexpr auto ErrorColor = "\033[31m"; //red
diff --git a/thirdparty/thorvg/src/common/tvgInlist.h b/thirdparty/thorvg/src/common/tvgInlist.h
index 3abe966957b..32c219b25f4 100644
--- a/thirdparty/thorvg/src/common/tvgInlist.h
+++ b/thirdparty/thorvg/src/common/tvgInlist.h
@@ -23,7 +23,10 @@
#ifndef _TVG_INLIST_H_
#define _TVG_INLIST_H_
-namespace tvg {
+#include <cstdint>
+
+namespace tvg
+{
//NOTE: declare this in your list item
#define INLIST_ITEM(T) \
@@ -35,6 +38,7 @@ struct Inlist
{
T* head = nullptr;
T* tail = nullptr;
+ uint32_t count = 0;
~Inlist()
{
@@ -49,6 +53,7 @@ struct Inlist
delete(t);
}
head = tail = nullptr;
+ count = 0;
}
void back(T* element)
@@ -63,6 +68,7 @@ struct Inlist
element->prev = nullptr;
element->next = nullptr;
}
+ ++count;
}
void front(T* element)
@@ -77,11 +83,13 @@ struct Inlist
element->prev = nullptr;
element->next = nullptr;
}
+ ++count;
}
T* back()
{
if (!tail) return nullptr;
+ --count;
auto t = tail;
tail = t->prev;
if (!tail) head = nullptr;
@@ -91,6 +99,7 @@ struct Inlist
T* front()
{
if (!head) return nullptr;
+ --count;
auto t = head;
head = t->next;
if (!head) tail = nullptr;
@@ -103,6 +112,8 @@ struct Inlist
if (element->next) element->next->prev = element->prev;
if (element == head) head = element->next;
if (element == tail) tail = element->prev;
+ element->prev = element->next = nullptr;
+ --count;
}
bool empty() const
diff --git a/thirdparty/thorvg/src/common/tvgLock.h b/thirdparty/thorvg/src/common/tvgLock.h
index b71ba7e649a..e23abc3b232 100644
--- a/thirdparty/thorvg/src/common/tvgLock.h
+++ b/thirdparty/thorvg/src/common/tvgLock.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2024 the ThorVG project. All rights reserved.
+ * Copyright (c) 2024 - 2026 ThorVG project. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@@ -32,6 +32,20 @@ namespace tvg
struct Key
{
std::mutex mtx;
+
+ void lock()
+ {
+ mtx.lock();
+ }
+
+ void unlock()
+ {
+ mtx.unlock();
+ }
+ };
+
+ struct StrictKey : Key
+ {
};
struct ScopedLock
@@ -46,22 +60,59 @@ namespace tvg
}
}
+ ScopedLock(StrictKey& k)
+ {
+ k.mtx.lock();
+ key = &k;
+ }
+
~ScopedLock()
{
- if (TaskScheduler::threads() > 0) {
- key->mtx.unlock();
- }
+ if (key) key->mtx.unlock();
}
};
#else //THORVG_THREAD_SUPPORT
struct Key {};
+ struct StrictKey : Key
+ {
+#ifdef __STDCPP_THREADS__
+ std::mutex mtx;
+#endif
+
+ void lock()
+ {
+#ifdef __STDCPP_THREADS__
+ mtx.lock();
+#endif
+ }
+
+ void unlock()
+ {
+#ifdef __STDCPP_THREADS__
+ mtx.unlock();
+#endif
+ }
+ };
+
struct ScopedLock
{
- ScopedLock(Key& key) {}
+ StrictKey* key = nullptr;
+
+ ScopedLock(Key& k) {}
+
+ ScopedLock(StrictKey& k)
+ {
+ k.lock();
+ key = &k;
+ }
+
+ ~ScopedLock()
+ {
+ if (key) key->unlock();
+ }
};
#endif //THORVG_THREAD_SUPPORT
}
#endif //_TVG_LOCK_H_
-
diff --git a/thirdparty/thorvg/src/common/tvgMap.h b/thirdparty/thorvg/src/common/tvgMap.h
new file mode 100644
index 00000000000..50562afbad4
--- /dev/null
+++ b/thirdparty/thorvg/src/common/tvgMap.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2026 ThorVG project. All rights reserved.
+
+ * 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.
+ */
+
+#ifndef _TVG_MAP_H_
+#define _TVG_MAP_H_
+
+#include "tvgCommon.h"
+#include "tvgInlist.h"
+
+namespace tvg
+{
+
+template<typename K, typename V>
+struct Map
+{
+ struct Item
+ {
+ INLIST_ITEM(Item);
+ K key;
+ V val;
+
+ Item(const K& key) : key(key), val{} {}
+ };
+
+ Item* find(const K& key)
+ {
+ auto& bucket = buckets[hash(key)];
+ INLIST_FOREACH(bucket, item) {
+ if (item->key == key) return item;
+ }
+ return nullptr;
+ }
+
+ void remove(const K& key)
+ {
+ auto& bucket = buckets[hash(key)];
+ INLIST_FOREACH(bucket, item) {
+ if (item->key == key) {
+ bucket.remove(item);
+ delete (item);
+ return;
+ }
+ }
+ }
+
+ void clear()
+ {
+ for (size_t i = 0; i < size; ++i) {
+ buckets[i].free();
+ }
+ }
+
+ V& operator[](const K& key)
+ {
+ if (auto item = find(key)) return item->val;
+
+ auto& bucket = buckets[hash(key)];
+ auto item = new Item(key);
+ bucket.back(item);
+ return item->val;
+ }
+
+ Map(size_t size = 32)
+ {
+ if (size < 1) size = 1;
+ buckets = new Inlist<Item>[size];
+ this->size = size;
+ }
+
+ ~Map()
+ {
+ delete[] buckets;
+ }
+
+ Map(const Map&) = delete;
+ Map& operator=(const Map&) = delete;
+
+ Inlist<Item>* buckets = nullptr;
+ size_t size = 0;
+
+private:
+ uintptr_t shuffle(uintptr_t x) const
+ {
+ x ^= x >> (sizeof(uintptr_t) * 4);
+ x *= 0x9e3779b1u;
+ x ^= x >> (sizeof(uintptr_t) * 4);
+ return x;
+ }
+
+ template<typename T>
+ uintptr_t hash(T v) const
+ {
+ return shuffle(static_cast<uintptr_t>(v)) % size;
+ }
+
+ template<typename T>
+ uintptr_t hash(T* p) const
+ {
+ return shuffle(reinterpret_cast<uintptr_t>(p)) % size;
+ }
+};
+
+} // namespace tvg
+
+#endif //_TVG_MAP_H_
diff --git a/thirdparty/thorvg/src/common/tvgMath.cpp b/thirdparty/thorvg/src/common/tvgMath.cpp
index a919efabed3..920a5f2a5cc 100644
--- a/thirdparty/thorvg/src/common/tvgMath.cpp
+++ b/thirdparty/thorvg/src/common/tvgMath.cpp
@@ -30,19 +30,12 @@
/* Internal Class Implementation */
/************************************************************************/
-static float _lineLengthApprox(const Point& pt1, const Point& pt2)
+static float _lengthApprox(const Point& pt1, const Point& pt2)
{
- /* approximate sqrt(x*x + y*y) using alpha max plus beta min algorithm.
- With alpha = 1, beta = 3/8, giving results with the largest error less
- than 7% compared to the exact value. */
- Point diff = {pt2.x - pt1.x, pt2.y - pt1.y};
- if (diff.x < 0) diff.x = -diff.x;
- if (diff.y < 0) diff.y = -diff.y;
- return (diff.x > diff.y) ? (diff.x + diff.y * 0.375f) : (diff.y + diff.x * 0.375f);
+ return tvg::length(pt1, pt2);
}
-
-static float _lineLength(const Point& pt1, const Point& pt2)
+static float _length(const Point& pt1, const Point& pt2)
{
Point diff = {pt2.x - pt1.x, pt2.y - pt1.y};
return sqrtf(diff.x * diff.x + diff.y * diff.y);
@@ -101,12 +94,6 @@ float _bezAt(const Bezier& bz, float at, float length, LengthFunc lineLengthFunc
namespace tvg {
-uint8_t lerp(const uint8_t &start, const uint8_t &end, float t)
-{
- return static_cast<uint8_t>(tvg::clamp(static_cast<int>(start + (end - start) * t), 0, 255));
-}
-
-
float length(const PathCommand* cmds, uint32_t cmdsCnt, const Point* pts, uint32_t ptsCnt)
{
if (ptsCnt < 2) return 0.0f;
@@ -276,10 +263,9 @@ void normalize(Point& pt)
float Line::length() const
{
- return _lineLength(pt1, pt2);
+ return _length(pt1, pt2);
}
-
void Line::split(float at, Line& left, Line& right) const
{
auto len = length();
@@ -292,22 +278,6 @@ void Line::split(float at, Line& left, Line& right) const
right.pt2 = pt2;
}
-
-Bezier::Bezier(const Point& st, const Point& ed, float radius)
-{
- // Calculate the angle between the start and end points
- auto angle = tvg::atan2(ed.y - st.y, ed.x - st.x);
-
- // Calculate the control points of the cubic bezier curve
- auto c = radius * PATH_KAPPA; // c = radius * (4/3) * tan(pi/8)
-
- start = {st.x, st.y};
- ctrl1 = {st.x + radius * cos(angle), st.y + radius * sin(angle)};
- ctrl2 = {ed.x - c * cos(angle), ed.y - c * sin(angle)};
- end = {ed.x, ed.y};
-}
-
-
void Bezier::split(Bezier& left, Bezier& right) const
{
auto c = (ctrl1.x + ctrl2.x) * 0.5f;
@@ -329,7 +299,6 @@ void Bezier::split(Bezier& left, Bezier& right) const
left.end.y = right.start.y = (left.ctrl2.y + right.ctrl1.y) * 0.5f;
}
-
void Bezier::split(float at, Bezier& left, Bezier& right) const
{
right = *this;
@@ -337,99 +306,37 @@ void Bezier::split(float at, Bezier& left, Bezier& right) const
right.split(t, left);
}
-
float Bezier::length() const
{
- return _bezLength(*this, _lineLength);
+ return _bezLength(*this, _length);
}
-
float Bezier::lengthApprox() const
{
- return _bezLength(*this, _lineLengthApprox);
+ return _bezLength(*this, _lengthApprox);
}
-
void Bezier::split(float t, Bezier& left)
{
left.start = start;
-
- left.ctrl1.x = start.x + t * (ctrl1.x - start.x);
- left.ctrl1.y = start.y + t * (ctrl1.y - start.y);
-
- left.ctrl2.x = ctrl1.x + t * (ctrl2.x - ctrl1.x); //temporary holding spot
- left.ctrl2.y = ctrl1.y + t * (ctrl2.y - ctrl1.y); //temporary holding spot
-
- ctrl2.x = ctrl2.x + t * (end.x - ctrl2.x);
- ctrl2.y = ctrl2.y + t * (end.y - ctrl2.y);
-
- ctrl1.x = left.ctrl2.x + t * (ctrl2.x - left.ctrl2.x);
- ctrl1.y = left.ctrl2.y + t * (ctrl2.y - left.ctrl2.y);
-
- left.ctrl2.x = left.ctrl1.x + t * (left.ctrl2.x - left.ctrl1.x);
- left.ctrl2.y = left.ctrl1.y + t * (left.ctrl2.y - left.ctrl1.y);
-
- left.end.x = start.x = left.ctrl2.x + t * (ctrl1.x - left.ctrl2.x);
- left.end.y = start.y = left.ctrl2.y + t * (ctrl1.y - left.ctrl2.y);
+ left.ctrl1 = start + t * (ctrl1 - start);
+ left.ctrl2 = ctrl1 + t * (ctrl2 - ctrl1); // temporary holding spot
+ ctrl2 = ctrl2 + t * (end - ctrl2);
+ ctrl1 = left.ctrl2 + t * (ctrl2 - left.ctrl2);
+ left.ctrl2 = left.ctrl1 + t * (left.ctrl2 - left.ctrl1);
+ left.end = start = left.ctrl2 + t * (ctrl1 - left.ctrl2);
}
-
float Bezier::at(float at, float length) const
{
- return _bezAt(*this, at, length, _lineLength);
+ return _bezAt(*this, at, length, _length);
}
-
float Bezier::atApprox(float at, float length) const
{
- return _bezAt(*this, at, length, _lineLengthApprox);
-}
-
-
-Point Bezier::at(float t) const
-{
- Point cur;
- auto it = 1.0f - t;
-
- auto ax = start.x * it + ctrl1.x * t;
- auto bx = ctrl1.x * it + ctrl2.x * t;
- auto cx = ctrl2.x * it + end.x * t;
- ax = ax * it + bx * t;
- bx = bx * it + cx * t;
- cur.x = ax * it + bx * t;
-
- float ay = start.y * it + ctrl1.y * t;
- float by = ctrl1.y * it + ctrl2.y * t;
- float cy = ctrl2.y * it + end.y * t;
- ay = ay * it + by * t;
- by = by * it + cy * t;
- cur.y = ay * it + by * t;
-
- return cur;
-}
-
-
-float Bezier::angle(float t) const
-{
- if (t < 0 || t > 1) return 0;
-
- //derivate
- // p'(t) = 3 * (-(1-2t+t^2) * p0 + (1 - 4 * t + 3 * t^2) * p1 + (2 * t - 3 *
- // t^2) * p2 + t^2 * p3)
- float mt = 1.0f - t;
- float d = t * t;
- float a = -mt * mt;
- float b = 1 - 4 * t + 3 * d;
- float c = 2 * t - 3 * d;
-
- Point pt ={a * start.x + b * ctrl1.x + c * ctrl2.x + d * end.x, a * start.y + b * ctrl1.y + c * ctrl2.y + d * end.y};
- pt.x *= 3;
- pt.y *= 3;
-
- return rad2deg(tvg::atan2(pt.y, pt.x));
+ return _bezAt(*this, at, length, _lengthApprox);
}
-
void Bezier::bounds(BBox& box, const Point& start, const Point& ctrl1, const Point& ctrl2, const Point& end)
{
if (box.min.x > start.x) box.min.x = start.x;
@@ -447,6 +354,18 @@ void Bezier::bounds(BBox& box, const Point& start, const Point& ctrl1, const Poi
auto a = -1.0f * start + 3.0f * ctrl1 - 3.0f * ctrl2 + end;
auto b = start - 2.0f * ctrl1 + ctrl2;
auto c = -1.0f * start + ctrl1;
+ if (tvg::zero(a)) {
+ if (tvg::zero(b)) return;
+ auto t = -c / (2.0f * b);
+ if (t > 0.0f && t < 1.0f) {
+ auto s = 1.0f - t;
+ auto q = s * s * s * start + 3.0f * s * s * t * ctrl1 + 3.0f * s * t * t * ctrl2 + t * t * t * end;
+ if (q < min) min = q;
+ if (q > max) max = q;
+ }
+ return;
+ }
+
auto h = b * b - a * c;
if (h <= 0.0f) return;
h = sqrtf(h);
@@ -464,8 +383,7 @@ void Bezier::bounds(BBox& box, const Point& start, const Point& ctrl1, const Poi
findMinMax(start.y, ctrl1.y, ctrl2.y, end.y, box.min.y, box.max.y);
}
-
-bool Bezier::flatten() const
+bool Bezier::flatten(float tolerance) const
{
float diff1_x = fabsf((ctrl1.x * 3.f) - (start.x * 2.f) - end.x);
float diff1_y = fabsf((ctrl1.y * 3.f) - (start.y * 2.f) - end.y);
@@ -473,22 +391,21 @@ bool Bezier::flatten() const
float diff2_y = fabsf((ctrl2.y * 3.f) - (end.y * 2.f) - start.y);
if (diff1_x < diff2_x) diff1_x = diff2_x;
if (diff1_y < diff2_y) diff1_y = diff2_y;
- return (diff1_x + diff1_y <= 0.5f);
+ return (diff1_x + diff1_y <= tolerance);
}
-
-uint32_t Bezier::segments() const
+uint32_t Bezier::segments(float scale) const
{
static constexpr uint32_t MaxSegments = 1u << 10; // 2^10 segments cap keeps runtime bounded
+ auto tolerance = 0.5f / scale;
uint32_t count = 0;
Array<Bezier> stack;
stack.push(*this);
Bezier left, right;
while (!stack.empty()) {
- auto current = stack.last();
- stack.pop();
- if (current.flatten()) {
+ auto current = stack.pick();
+ if (current.flatten(tolerance)) {
++count;
continue;
}
@@ -503,10 +420,4 @@ uint32_t Bezier::segments() const
return count;
}
-
-Bezier Bezier::operator*(const Matrix& m)
-{
- return Bezier{start * m, ctrl1* m, ctrl2 * m, end * m};
-}
-
} // namespace tvg
diff --git a/thirdparty/thorvg/src/common/tvgMath.h b/thirdparty/thorvg/src/common/tvgMath.h
index 2768d44d19e..f09ca98ebd3 100644
--- a/thirdparty/thorvg/src/common/tvgMath.h
+++ b/thirdparty/thorvg/src/common/tvgMath.h
@@ -33,7 +33,8 @@ namespace tvg
{
#define MATH_PI 3.14159265358979323846f
-#define MATH_PI2 1.57079632679489661923f
+#define MATH_PI2 (MATH_PI * 0.5f)
+#define MATH_2PI (MATH_PI * 2.0f)
#define FLOAT_EPSILON 1.0e-06f //1.192092896e-07f
#define PATH_KAPPA 0.552284f
@@ -44,6 +45,10 @@ namespace tvg
float atan2(float y, float x);
float length(const PathCommand* cmds, uint32_t cmdsCnt, const Point* pts, uint32_t ptsCnt);
+static inline float atan(const Point& pt)
+{
+ return atan2(pt.y, pt.x);
+}
static inline float deg2rad(float degree)
{
@@ -77,6 +82,12 @@ static inline constexpr const T& clamp(const T& v, const T& min, const T& max)
return v;
}
+template<typename T = uint8_t>
+static inline T remap255(float val)
+{
+ return static_cast<T>(nearbyintf(val * 255.0f));
+}
+
/************************************************************************/
/* Matrix functions */
/************************************************************************/
@@ -130,7 +141,9 @@ static inline constexpr const Matrix identity()
static inline float scaling(const Matrix& m)
{
- return sqrtf(m.e11 * m.e11 + m.e21 * m.e21);
+ auto sx = m.e11 * m.e11 + m.e21 * m.e21;
+ auto sy = m.e12 * m.e12 + m.e22 * m.e22;
+ return sqrtf((sx > sy) ? sx : sy);
}
@@ -249,6 +262,9 @@ static inline bool zero(const Point& p)
static inline float length(const Point& a, const Point& b)
{
+ /* approximate sqrt(x*x + y*y) using alpha max plus beta min algorithm.
+ With alpha = 1, beta = 3/8, giving results with the largest error less
+ than 7% compared to the exact value. */
auto x = b.x - a.x;
auto y = b.y - a.y;
@@ -326,6 +342,11 @@ static inline void operator*=(Point& lhs, const Point& rhs)
lhs.y *= rhs.y;
}
+static inline void operator/=(Point& lhs, const Point& rhs)
+{
+ lhs.x /= rhs.x;
+ lhs.y /= rhs.y;
+}
static inline Point operator*(const Point& lhs, const float rhs)
{
@@ -370,7 +391,6 @@ enum class Orientation
CounterClockwise,
};
-
static inline Orientation orientation(const Point& p1, const Point& p2, const Point& p3)
{
auto val = cross(p2 - p1, p3 - p1);
@@ -378,13 +398,6 @@ static inline Orientation orientation(const Point& p1, const Point& p2, const Po
else return val > 0 ? Orientation::Clockwise : Orientation::CounterClockwise;
}
-
-static inline void log(const Point& pt)
-{
- TVGLOG("COMMON", "Point: [%f %f]", pt.x, pt.y);
-}
-
-
static inline bool closed(const Point& lhs, const Point& rhs, float tolerance)
{
float dx = lhs.x - rhs.x;
@@ -392,6 +405,27 @@ static inline bool closed(const Point& lhs, const Point& rhs, float tolerance)
return (dx * dx + dy * dy) < (tolerance * tolerance);
}
+/************************************************************************/
+/* Point3 functions */
+/************************************************************************/
+
+struct Point3
+{
+ float x, y, z;
+};
+
+static inline Point3 operator+(const Point3& a, const Point3& b)
+{
+ return {a.x + b.x, a.y + b.y, a.z + b.z};
+}
+static inline Point3 operator-(const Point3& a, const Point3& b)
+{
+ return {a.x - b.x, a.y - b.y, a.z - b.z};
+}
+static inline Point3 operator*(const Point3& a, float t)
+{
+ return {a.x * t, a.y * t, a.z * t};
+}
/************************************************************************/
/* Line functions */
@@ -399,8 +433,7 @@ static inline bool closed(const Point& lhs, const Point& rhs, float tolerance)
struct Line
{
- Point pt1;
- Point pt2;
+ Point pt1, pt2;
void split(float at, Line& left, Line& right) const;
float length() const;
@@ -415,23 +448,32 @@ struct BBox
{
Point min, max;
+ bool inside(const Point& pt) const
+ {
+ return (pt.x >= min.x && pt.x <= max.x && pt.y >= min.y && pt.y <= max.y);
+ }
+
void init()
{
min = {FLT_MAX, FLT_MAX};
max = {-FLT_MAX, -FLT_MAX};
}
-};
+ bool zero()
+ {
+ return (max.x == 0.0f && max.y == 0.0f);
+ }
-static inline uint32_t arcSegmentsCnt(float arcAngle, float pixelRadius)
-{
- if (pixelRadius < FLOAT_EPSILON) return 2;
- static constexpr auto PX_TOLERANCE = 0.25f;
- // Sagitta-based formula Approximation: 1 - cos(θ/2) ≈ (θ/2)²/2, so θ ≈ 2 * sqrt(2 * s/r)
- auto segmentAngle = 2.0f * sqrtf(2.0f * PX_TOLERANCE / pixelRadius);
- return static_cast<uint32_t>(ceilf(fabsf(arcAngle) / segmentAngle)) + 1;
-}
+ float w()
+ {
+ return max.x - min.x;
+ }
+ float h()
+ {
+ return max.y - min.y;
+ }
+};
/************************************************************************/
/* Bezier functions */
@@ -439,145 +481,87 @@ static inline uint32_t arcSegmentsCnt(float arcAngle, float pixelRadius)
struct Bezier
{
- Point start;
- Point ctrl1;
- Point ctrl2;
- Point end;
+ Point start, ctrl1, ctrl2, end;
Bezier() {}
Bezier(const Point& p0, const Point& p1, const Point& p2, const Point& p3):
start(p0), ctrl1(p1), ctrl2(p2), end(p3) {}
- // Constructor that approximates a quarter-circle segment of arc between 'start' and 'end' points
- // using a cubic Bezier curve with a given 'radius'.
- Bezier(const Point& start, const Point& end, float radius);
-
- void split(float t, Bezier& left);
- void split(Bezier& left, Bezier& right) const;
- void split(float at, Bezier& left, Bezier& right) const;
- float length() const;
- float lengthApprox() const;
- float at(float at, float length) const;
- float atApprox(float at, float length) const;
- Point at(float t) const;
- float angle(float t) const;
- bool flatten() const;
- uint32_t segments() const;
- Bezier operator*(const Matrix& m);
-
- static void bounds(BBox& box, const Point& start, const Point& ctrl1, const Point& ctrl2, const Point& end);
-};
-
-static inline bool edgesCross(const Point& p0, const Point& p1, const Point& p2, const Point& p3)
-{
- auto orientSign = [](const Point& a, const Point& b, const Point& c) {
- auto value = cross(b - a, c - a);
- if (zero(value)) return int8_t{0};
- return (value > 0.0f) ? int8_t{1} : int8_t{-1};
- };
-
- auto straddlesLine = [&](const Point& a, const Point& b, const Point& c, const Point& d) {
- return orientSign(a, b, c) * orientSign(a, b, d) < 0;
- };
-
- return straddlesLine(p0, p1, p2, p3) && straddlesLine(p2, p3, p0, p1);
-}
-
-// Conservative triangle-fan safety check
-// The fill is emitted as (v0,v1,v2), (v0,v2,v3), (v0,v3,v4), ...
-// Usage:
-// 1. Setup: default-construct `ConvexProbe probe` for one tessellation pass.
-// 2. Feed one contour at a time: call `nextContour()` on MoveTo, then stream
-// each contour edge with `addEdge(curr - prev)`, and finish with
-// `addContourClose(first - prev)` on Close. For cubic segments, callers may
-// pre-reject looping control polygons with `edgesCross(start, ctrl1, ctrl2, end)`.
-// 3. Read `probe.convex` as the result. `true` means the contour stayed within
-// the cheap triangle-fan fast-path assumptions; `false` means fall back.
-// Cost: O(1) work per edge and O(1) memory.
-struct ConvexProbe
-{
- bool convex = true;
- int8_t winding = 0;
- Point firstEdge = {};
- Point prevEdge = {};
- int8_t prevXDir = 0;
- int8_t prevYDir = 0;
- uint8_t xDirChanges = 0;
- uint8_t yDirChanges = 0;
- uint8_t reversals = 0;
- bool contourHasEdges = false;
-
- void nextContour()
- {
- if (contourHasEdges) convex = false;
- resetContour();
- }
-
- void addEdge(const Point& edge)
+ // Constructor that approximates a quarter-circle segment of arc between 'start' and 'end' points
+ // using a cubic Bezier curve with a given 'radius'.
+ Bezier(const Point& st, const Point& ed, float radius)
{
- if (zero(edge)) return;
-
- contourHasEdges = true;
- if (!convex) return;
+ // Calculate the angle between the start and end points
+ auto angle = tvg::atan(ed - st);
- if (zero(firstEdge)) firstEdge = edge;
+ // Calculate the control points of the cubic bezier curve
+ auto c = radius * PATH_KAPPA; // c = radius * (4/3) * tan(pi/8)
- updateDir(edge.x, prevXDir, xDirChanges);
- updateDir(edge.y, prevYDir, yDirChanges);
- if (!convex) return;
-
- if (zero(prevEdge)) {
- prevEdge = edge;
- return;
- }
-
- auto turn = cross(prevEdge, edge);
- if (zero(turn)) {
- if (dot(prevEdge, edge) < 0.0f && ++reversals > MaxCollinearReversals) convex = false;
- } else {
- auto sign = (turn > 0.0f) ? int8_t{1} : int8_t{-1};
- if (winding == 0) winding = sign;
- else if (sign != winding) convex = false;
- }
-
- prevEdge = edge;
+ start = {st.x, st.y};
+ ctrl1 = {st.x + radius * cos(angle), st.y + radius * sin(angle)};
+ ctrl2 = {ed.x - c * cos(angle), ed.y - c * sin(angle)};
+ end = {ed.x, ed.y};
}
- void addContourClose(const Point& edge)
+ float angle(float t) const
{
- addEdge(edge);
- if (convex && !zero(firstEdge)) addEdge(firstEdge);
+ if (t < 0 || t > 1) return 0;
+ return rad2deg(tvg::atan(tangent(t)));
}
-private:
- enum : uint8_t
+ Bezier operator*(const Matrix& m)
{
- MaxAxisDirChanges = 3,
- MaxCollinearReversals = 2
- };
+ return Bezier{start * m, ctrl1 * m, ctrl2 * m, end * m};
+ }
- void resetContour()
+ Point tangent(float t) const
{
- firstEdge = {};
- prevEdge = {};
- prevXDir = prevYDir = 0;
- xDirChanges = yDirChanges = 0;
- reversals = 0;
- contourHasEdges = false;
+ // derivate
+ // p'(t) = 3 * (-(1-2t+t^2) * p0 + (1 - 4 * t + 3 * t^2) * p1 + (2 * t - 3 *
+ // t^2) * p2 + t^2 * p3)
+ auto mt = 1.0f - t;
+ auto d = t * t;
+ auto a = -mt * mt;
+ auto b = 1.0f - 4.0f * t + 3.0f * d;
+ auto c = 2.0f * t - 3.0f * d;
+ auto pt = Point{a * start.x + b * ctrl1.x + c * ctrl2.x + d * end.x, a * start.y + b * ctrl1.y + c * ctrl2.y + d * end.y};
+
+ return pt * 3.0f;
}
- void updateDir(float value, int8_t& prevDir, uint8_t& changes)
+ Point at(float t) const
{
- int8_t dir = 0;
- if (!zero(value)) dir = (value > 0.0f) ? int8_t{1} : int8_t{-1};
- if (dir == 0 || !convex) return;
-
- if (prevDir != 0 && prevDir != dir && ++changes > MaxAxisDirChanges) {
- convex = false;
- return;
- }
- prevDir = dir;
+ Point cur;
+ auto it = 1.0f - t;
+
+ auto ax = start.x * it + ctrl1.x * t;
+ auto bx = ctrl1.x * it + ctrl2.x * t;
+ auto cx = ctrl2.x * it + end.x * t;
+ ax = ax * it + bx * t;
+ bx = bx * it + cx * t;
+ cur.x = ax * it + bx * t;
+
+ float ay = start.y * it + ctrl1.y * t;
+ float by = ctrl1.y * it + ctrl2.y * t;
+ float cy = ctrl2.y * it + end.y * t;
+ ay = ay * it + by * t;
+ by = by * it + cy * t;
+ cur.y = ay * it + by * t;
+
+ return cur;
}
+
+ void split(float t, Bezier& left);
+ void split(Bezier& left, Bezier& right) const;
+ void split(float at, Bezier& left, Bezier& right) const;
+ float length() const;
+ float lengthApprox() const;
+ float at(float at, float length) const;
+ float atApprox(float at, float length) const;
+ bool flatten(float tolerance) const;
+ uint32_t segments(float scale = 1.0f) const;
+
+ static void bounds(BBox& box, const Point& start, const Point& ctrl1, const Point& ctrl2, const Point& end);
};
/************************************************************************/
@@ -590,8 +574,20 @@ static inline T lerp(const T &start, const T &end, float t)
return static_cast<T>(start + (end - start) * t);
}
-uint8_t lerp(const uint8_t &start, const uint8_t &end, float t);
+static inline uint8_t lerp(const uint8_t& start, const uint8_t& end, float t)
+{
+ return static_cast<uint8_t>(clamp(static_cast<int>(start + (end - start) * t), 0, 255));
+}
+static inline Fill::ColorStop lerp(const Fill::ColorStop& from, const Fill::ColorStop& to, float t)
+{
+ return {
+ tvg::lerp(from.offset, to.offset, t),
+ tvg::lerp(from.r, to.r, t),
+ tvg::lerp(from.g, to.g, t),
+ tvg::lerp(from.b, to.b, t),
+ tvg::lerp(from.a, to.a, t)};
+}
}
#endif //_TVG_MATH_H_
diff --git a/thirdparty/thorvg/src/common/tvgStr.cpp b/thirdparty/thorvg/src/common/tvgStr.cpp
index 8da3aeea95a..63a8d05edd7 100644
--- a/thirdparty/thorvg/src/common/tvgStr.cpp
+++ b/thirdparty/thorvg/src/common/tvgStr.cpp
@@ -139,9 +139,8 @@ float toFloat(const char *str, char **end)
if (*iter == 'e' || *iter == 'E') {
++iter;
- //Exception: svg may have 'em' unit for fonts. ex) 5em, 10.5em
+ // Exception: svg 'em' unit. The caller resolves the multiplier.
if ((*iter == 'm') || (*iter == 'M')) {
- //TODO: We don't support font em unit now, but has to multiply val * font size later...
a = iter + 1;
goto success;
}
diff --git a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp b/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp
index 75505b12f76..7cb2e1be902 100644
--- a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp
+++ b/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.cpp
@@ -20,6 +20,7 @@
* SOFTWARE.
*/
+#include <climits>
#include <turbojpeg.h>
#include "tvgJpgLoader.h"
@@ -29,22 +30,20 @@
void JpgLoader::clear()
{
- if (freeData) tvg::free(data);
+ if (owner != Ownership::Borrow) tvg::free(data);
data = nullptr;
size = 0;
- freeData = false;
+ owner = Ownership::Borrow;
}
/************************************************************************/
/* External Class Implementation */
/************************************************************************/
-JpgLoader::JpgLoader() : ImageLoader(FileType::Jpg)
+JpgLoader::JpgLoader() : BitmapLoader(FileType::Jpg), jpegDecompressor(tjInitDecompress())
{
- jpegDecompressor = tjInitDecompress();
}
-
JpgLoader::~JpgLoader()
{
clear();
@@ -54,65 +53,62 @@ JpgLoader::~JpgLoader()
tjFree(surface.buf8);
}
-
-bool JpgLoader::open(const char* path)
+Result JpgLoader::open(const char* path, const LoaderOps& ops)
{
#ifdef THORVG_FILE_IO_SUPPORT
- if (!(data = (unsigned char*) LoadModule::open(path, size))) return false;
+ if (!(data = (unsigned char*)Loader::open(path, size))) return Result::InvalidArguments;
+ owner = Ownership::Transfer;
int width, height, subSample, colorSpace;
- if (tjDecompressHeader3(jpegDecompressor, data, size, &width, &height, &subSample, &colorSpace) < 0) return false;
+ if (tjDecompressHeader3(jpegDecompressor, data, size, &width, &height, &subSample, &colorSpace) < 0) return Result::InvalidArguments;
w = static_cast<float>(width);
h = static_cast<float>(height);
- freeData = true;
- return true;
+ return Result::Success;
#else
- return false;
+ return Result::NonSupport;
#endif
}
-
-bool JpgLoader::open(const char* data, uint32_t size, TVG_UNUSED const char* rpath, bool copy)
+Result JpgLoader::open(const char* data, uint32_t size, const LoaderOps& ops)
{
int width, height, subSample, colorSpace;
- if (tjDecompressHeader3(jpegDecompressor, (unsigned char *) data, size, &width, &height, &subSample, &colorSpace) < 0) return false;
+ if (tjDecompressHeader3(jpegDecompressor, (unsigned char*)data, size, &width, &height, &subSample, &colorSpace) < 0) return Result::InvalidArguments;
- if (copy) {
+ if (ops.owner == Ownership::Copy) {
this->data = tvg::malloc<unsigned char>(size);
- if (!this->data) return false;
memcpy((unsigned char *)this->data, data, size);
- freeData = true;
} else {
this->data = (unsigned char *) data;
- freeData = false;
}
-
+ owner = ops.owner;
w = static_cast<float>(width);
h = static_cast<float>(height);
this->size = size;
- return true;
+ return Result::Success;
}
bool JpgLoader::read()
{
- if (!LoadModule::read()) return true;
+ if (!Loader::read()) return true;
if (w == 0 || h == 0) return false;
//determine the image format
+ ColorSpace cs;
TJPF format;
- if (ImageLoader::cs == ColorSpace::ARGB8888 || ImageLoader::cs == ColorSpace::ARGB8888S) {
+ if (BitmapLoader::cs == ColorSpace::ARGB8888 || BitmapLoader::cs == ColorSpace::ARGB8888S) {
format = TJPF_BGRX;
- surface.cs = ColorSpace::ARGB8888;
+ cs = ColorSpace::XRGB8888;
} else {
format = TJPF_RGBX;
- surface.cs = ColorSpace::ABGR8888;
+ cs = ColorSpace::XBGR8888;
}
+ if (static_cast<int>(w) > INT_MAX / static_cast<int>(h) / tjPixelSize[format]) return false;
+
auto image = (unsigned char *)tjAlloc(static_cast<int>(w) * static_cast<int>(h) * tjPixelSize[format]);
- if (!image) return false;
//decompress jpg image
if (tjDecompress2(jpegDecompressor, data, size, image, static_cast<int>(w), 0, static_cast<int>(h), format, 0) < 0) {
@@ -122,14 +118,7 @@ bool JpgLoader::read()
return false;
}
- //setup the surface
- surface.buf8 = image;
- surface.stride = w;
- surface.w = w;
- surface.h = h;
- surface.channelSize = sizeof(uint32_t);
- surface.premultiplied = true;
-
+ surface.setup((pixel_t*)image, w, w, h, sizeof(uint32_t), cs);
clear();
return true;
}
diff --git a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h b/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h
index c73a1534253..7e134cc11d9 100644
--- a/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h
+++ b/thirdparty/thorvg/src/loaders/external_jpg/tvgJpgLoader.h
@@ -28,14 +28,13 @@
using tjhandle = void*;
//TODO: Use Task?
-class JpgLoader : public ImageLoader
+struct JpgLoader : BitmapLoader
{
-public:
JpgLoader();
~JpgLoader();
- bool open(const char* path) override;
- bool open(const char* data, uint32_t size, const char* rpath, bool copy) override;
+ Result open(const char* path, const LoaderOps& ops) override;
+ Result open(const char* data, uint32_t size, const LoaderOps& ops) override;
bool read() override;
private:
@@ -44,7 +43,6 @@ private:
tjhandle jpegDecompressor;
unsigned char* data = nullptr;
uint32_t size = 0;
- bool freeData = false;
};
#endif //_TVG_JPG_LOADER_H_
diff --git a/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.cpp b/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.cpp
index c0eb493806e..36620d0d2dc 100644
--- a/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.cpp
+++ b/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.cpp
@@ -37,7 +37,7 @@ void PngLoader::clear()
/* External Class Implementation */
/************************************************************************/
-PngLoader::PngLoader() : ImageLoader(FileType::Png)
+PngLoader::PngLoader() : BitmapLoader(FileType::Png)
{
image = tvg::calloc<png_image>(1, sizeof(png_image));
image->version = PNG_IMAGE_VERSION;
@@ -50,49 +50,50 @@ PngLoader::~PngLoader()
tvg::free(surface.buf32);
}
-
-bool PngLoader::open(const char* path)
+Result PngLoader::open(const char* path, TVG_UNUSED const LoaderOps& ops)
{
+#ifdef THORVG_FILE_IO_SUPPORT
image->opaque = nullptr;
- if (!png_image_begin_read_from_file(image, path)) return false;
+ if (!png_image_begin_read_from_file(image, path)) return Result::InvalidArguments;
w = (float)image->width;
h = (float)image->height;
- return true;
+ return Result::Success;
+#else
+ return Result::NonSupport;
+#endif
}
-
-bool PngLoader::open(const char* data, uint32_t size, TVG_UNUSED const char* rpath, bool copy)
+Result PngLoader::open(const char* data, uint32_t size, TVG_UNUSED const LoaderOps& ops)
{
-#ifdef THORVG_FILE_IO_SUPPORT
image->opaque = nullptr;
- if (!png_image_begin_read_from_memory(image, data, size)) return false;
+ if (!png_image_begin_read_from_memory(image, data, size)) return Result::InvalidArguments;
w = (float)image->width;
h = (float)image->height;
- return true;
-#else
- return false;
-#endif
+ return Result::Success;
}
bool PngLoader::read()
{
- if (!LoadModule::read()) return true;
+ if (!Loader::read()) return true;
if (w == 0 || h == 0) return false;
- if (ImageLoader::cs == ColorSpace::ARGB8888 || ImageLoader::cs == ColorSpace::ARGB8888S) {
+ ColorSpace cs;
+
+ // TODO: we can acquire a pre-multiplied image. See "png_structrp"
+ if (BitmapLoader::cs == ColorSpace::ARGB8888 || BitmapLoader::cs == ColorSpace::ARGB8888S) {
image->format = PNG_FORMAT_BGRA;
- surface.cs = ColorSpace::ARGB8888S;
+ cs = ColorSpace::ARGB8888S;
} else {
image->format = PNG_FORMAT_RGBA;
- surface.cs = ColorSpace::ABGR8888S;
+ cs = ColorSpace::ABGR8888S;
}
auto buffer = tvg::malloc<png_byte>(PNG_IMAGE_SIZE((*image)));
@@ -101,14 +102,7 @@ bool PngLoader::read()
return false;
}
- //setup the surface
- surface.buf32 = reinterpret_cast<uint32_t*>(buffer);
- surface.stride = (uint32_t)w;
- surface.w = (uint32_t)w;
- surface.h = (uint32_t)h;
- surface.channelSize = sizeof(uint32_t);
- //TODO: we can acquire a pre-multiplied image. See "png_structrp"
- surface.premultiplied = false;
+ surface.setup(reinterpret_cast<pixel_t*>(buffer), (uint32_t)w, (uint32_t)w, (uint32_t)h, sizeof(uint32_t), cs);
clear();
diff --git a/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.h b/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.h
index 689ef2d3e5e..5dd256b4e5e 100644
--- a/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.h
+++ b/thirdparty/thorvg/src/loaders/external_png/tvgPngLoader.h
@@ -26,14 +26,13 @@
#include <png.h>
#include "tvgLoader.h"
-class PngLoader : public ImageLoader
+struct PngLoader : BitmapLoader
{
-public:
PngLoader();
~PngLoader();
- bool open(const char* path) override;
- bool open(const char* data, uint32_t size, const char* rpath, bool copy) override;
+ Result open(const char* path, const LoaderOps& ops) override;
+ Result open(const char* data, uint32_t size, const LoaderOps& ops) override;
bool read() override;
private:
diff --git a/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.cpp b/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.cpp
index 10fc6c80e84..29ddfa38a05 100644
--- a/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.cpp
+++ b/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.cpp
@@ -32,15 +32,22 @@
void WebpLoader::run(unsigned tid)
{
- //TODO: acquire the current colorspace format & pre-multiplied alpha image.
- surface.buf8 = WebPDecodeBGRA(data, size, nullptr, nullptr);
- surface.stride = (uint32_t)w;
- surface.w = (uint32_t)w;
- surface.h = (uint32_t)h;
- surface.channelSize = sizeof(uint32_t);
- surface.cs = ColorSpace::ARGB8888;
- surface.premultiplied = false;
+ WebPDecoderConfig config;
+ if (!WebPInitDecoderConfig(&config)) return;
+ ColorSpace cs;
+
+ // request premultiplied image data
+ if (BitmapLoader::cs == ColorSpace::ARGB8888 || BitmapLoader::cs == ColorSpace::ARGB8888S) {
+ config.output.colorspace = MODE_bgrA;
+ if (WebPDecode(data, size, &config) != VP8_STATUS_OK) return;
+ cs = surface.opaque ? ColorSpace::XRGB8888 : ColorSpace::ARGB8888;
+ } else {
+ config.output.colorspace = MODE_rgbA;
+ if (WebPDecode(data, size, &config) != VP8_STATUS_OK) return;
+ cs = surface.opaque ? ColorSpace::XBGR8888 : ColorSpace::ABGR8888;
+ }
+ surface.setup((pixel_t*)config.output.u.RGBA.rgba, (uint32_t)w, (uint32_t)w, (uint32_t)h, sizeof(uint32_t), cs);
}
@@ -48,66 +55,57 @@ void WebpLoader::run(unsigned tid)
/* External Class Implementation */
/************************************************************************/
-WebpLoader::WebpLoader() : ImageLoader(FileType::Webp)
-{
-}
-
-
WebpLoader::~WebpLoader()
{
done();
- if (freeData) tvg::free(data);
+ if (owner != Ownership::Borrow) tvg::free(data);
data = nullptr;
size = 0;
- freeData = false;
+ owner = Ownership::Borrow;
WebPFree(surface.buf8);
}
-
-bool WebpLoader::open(const char* path)
+Result WebpLoader::open(const char* path, const LoaderOps& ops)
{
#ifdef THORVG_FILE_IO_SUPPORT
- if (!(data = (unsigned char*)LoadModule::open(path, size))) return false;
-
- int width, height;
- if (!WebPGetInfo(data, size, &width, &height)) return false;
- w = static_cast<float>(width);
- h = static_cast<float>(height);
- freeData = true;
- return true;
+ if (!(data = (unsigned char*)Loader::open(path, size))) return Result::InvalidArguments;
+ owner = Ownership::Transfer;
+
+ WebPBitstreamFeatures features;
+ if (WebPGetFeatures(data, size, &features)) return Result::InvalidArguments;
+ w = static_cast<float>(features.width);
+ h = static_cast<float>(features.height);
+ surface.opaque = !features.has_alpha;
+ return Result::Success;
#else
- return false;
+ return Result::NonSupport;
#endif
}
-
-bool WebpLoader::open(const char* data, uint32_t size, TVG_UNUSED const char* rpath, bool copy)
+Result WebpLoader::open(const char* data, uint32_t size, const LoaderOps& ops)
{
- if (copy) {
+ if (ops.owner == Ownership::Copy) {
this->data = tvg::malloc<unsigned char>(size);
- if (!this->data) return false;
memcpy((unsigned char *)this->data, data, size);
- freeData = true;
} else {
this->data = (unsigned char *) data;
- freeData = false;
}
+ owner = ops.owner;
- int width, height;
- if (!WebPGetInfo(this->data, size, &width, &height)) return false;
-
- w = static_cast<float>(width);
- h = static_cast<float>(height);
- surface.cs = ColorSpace::ARGB8888;
+ WebPBitstreamFeatures features;
+ if (WebPGetFeatures(this->data, size, &features)) return Result::InvalidArguments;
+ w = static_cast<float>(features.width);
+ h = static_cast<float>(features.height);
+ surface.opaque = !features.has_alpha;
this->size = size;
- return true;
+ return Result::Success;
}
bool WebpLoader::read()
{
- if (!LoadModule::read()) return true;
+ if (!Loader::read()) return true;
if (!data || w == 0 || h == 0) return false;
@@ -121,5 +119,5 @@ RenderSurface* WebpLoader::bitmap()
{
this->done();
- return ImageLoader::bitmap();
+ return BitmapLoader::bitmap();
}
diff --git a/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.h b/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.h
index fc647388009..e8909efc930 100644
--- a/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.h
+++ b/thirdparty/thorvg/src/loaders/external_webp/tvgWebpLoader.h
@@ -26,14 +26,13 @@
#include "tvgLoader.h"
#include "tvgTaskScheduler.h"
-class WebpLoader : public ImageLoader, public Task
+struct WebpLoader : BitmapLoader, Task
{
-public:
- WebpLoader();
+ WebpLoader() : BitmapLoader(FileType::Webp) {}
~WebpLoader();
- bool open(const char* path) override;
- bool open(const char* data, uint32_t size, const char* rpath, bool copy) override;
+ Result open(const char* path, const LoaderOps& ops) override;
+ Result open(const char* data, uint32_t size, const LoaderOps& ops) override;
bool read() override;
RenderSurface* bitmap() override;
@@ -43,7 +42,6 @@ private:
unsigned char* data = nullptr;
uint32_t size = 0;
- bool freeData = false;
};
#endif //_TVG_WEBP_LOADER_H_
diff --git a/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.cpp b/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.cpp
index 0e50bc3694b..64e006aefd4 100644
--- a/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.cpp
+++ b/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.cpp
@@ -23,50 +23,35 @@
#include "tvgLoader.h"
#include "tvgRawLoader.h"
-
-RawLoader::RawLoader() : ImageLoader(FileType::Raw)
-{
-}
-
-
RawLoader::~RawLoader()
{
- if (copy) tvg::free(surface.buf32);
+ if (owner != Ownership::Borrow) tvg::free(surface.buf32);
}
-
-bool RawLoader::open(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, bool copy)
+bool RawLoader::open(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, Ownership owner)
{
- if (!LoadModule::read()) return true;
+ if (!Loader::read()) return true;
if (!data || w == 0 || h == 0) return false;
this->w = (float)w;
this->h = (float)h;
- this->copy = copy;
+ this->owner = owner;
- if (copy) {
+ if (owner == Ownership::Copy) {
surface.buf32 = tvg::malloc<uint32_t>(sizeof(uint32_t) * w * h);
- if (!surface.buf32) return false;
memcpy((void*)surface.buf32, data, sizeof(uint32_t) * w * h);
+ } else {
+ surface.buf32 = const_cast<uint32_t*>(data);
}
- else surface.buf32 = const_cast<uint32_t*>(data);
-
- //setup the surface
- surface.stride = w;
- surface.w = w;
- surface.h = h;
- surface.cs = cs;
- surface.channelSize = sizeof(uint32_t);
- surface.premultiplied = (cs == ColorSpace::ABGR8888 || cs == ColorSpace::ARGB8888) ? true : false;
+ surface.setup(surface.buf32, w, w, h, sizeof(uint32_t), cs);
return true;
}
-
bool RawLoader::read()
{
- LoadModule::read();
+ Loader::read();
return true;
}
diff --git a/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.h b/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.h
index 87f08ad8b1b..15f22631e3e 100644
--- a/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.h
+++ b/thirdparty/thorvg/src/loaders/raw/tvgRawLoader.h
@@ -23,16 +23,13 @@
#ifndef _TVG_RAW_LOADER_H_
#define _TVG_RAW_LOADER_H_
-class RawLoader : public ImageLoader
+struct RawLoader : BitmapLoader
{
-public:
- bool copy = false;
-
- RawLoader();
+ RawLoader() : BitmapLoader(FileType::Raw) {}
~RawLoader();
- using LoadModule::open;
- bool open(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, bool copy);
+ using Loader::open;
+ bool open(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, Ownership owner);
bool read() override;
};
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgBuilder.cpp b/thirdparty/thorvg/src/loaders/svg/tvgSvgBuilder.cpp
new file mode 100644
index 00000000000..10249956c27
--- /dev/null
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgBuilder.cpp
@@ -0,0 +1,1521 @@
+/*
+ * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
+
+ * 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 "tvgMath.h" /* to include math.h before cstring */
+#include "tvgShape.h"
+#include "tvgCompressor.h"
+#include "tvgFill.h"
+#include "tvgStr.h"
+#include "tvgShape.h"
+#include "tvgSvgCommon.h"
+#include "tvgSvgBuilder.h"
+#include "tvgSvgPath.h"
+#include "tvgSvgUtil.h"
+
+/************************************************************************/
+/* Internal Class Implementation */
+/************************************************************************/
+
+static bool _appendClipShape(SvgParserContext& ctx, SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath, const Matrix* transform);
+static bool _applyClip(SvgParserContext& ctx, Paint* paint, Paint* content, const SvgNode* node, const SvgNode* clipNode, const Box& vBox, const string& svgPath, Paint** result);
+static Scene* _sceneBuildHelper(SvgParserContext& ctx, const SvgNode* node, const Box& vBox, const string& svgPath, bool mask, int depth);
+static Paint* _applyPatternProperty(SvgParserContext& ctx, Shape* vg, SvgNode* node, SvgNode* patternNode, const Box& vBox, const string& svgPath);
+
+static inline bool _isGroupType(SvgNodeType type)
+{
+ if (type == SvgNodeType::Doc || type == SvgNodeType::G || type == SvgNodeType::Use || type == SvgNodeType::ClipPath || type == SvgNodeType::Symbol || type == SvgNodeType::Filter) return true;
+ return false;
+}
+
+
+//According to: https://www.w3.org/TR/SVG11/coords.html#ObjectBoundingBoxUnits (the last paragraph)
+//a stroke width should be ignored for bounding box calculations
+static Box _bounds(Paint* paint)
+{
+ float x, y, w, h;
+ paint->bounds(&x, &y, &w, &h);
+ return {x, y, w, h};
+}
+
+static Box _objectBoundingBox(const Box& ratio, const Box& bounds)
+{
+ return {bounds.x + ratio.x * bounds.w, bounds.y + ratio.y * bounds.h, ratio.w * bounds.w, ratio.h * bounds.h};
+}
+
+static inline bool _validBox(const Box& b)
+{
+ return b.w > 0.0f && b.h > 0.0f;
+}
+
+static void _transformMultiply(const Matrix* mBBox, Matrix* gradTransf)
+{
+ gradTransf->e13 = gradTransf->e13 * mBBox->e11 + mBBox->e13;
+ gradTransf->e12 *= mBBox->e11;
+ gradTransf->e11 *= mBBox->e11;
+
+ gradTransf->e23 = gradTransf->e23 * mBBox->e22 + mBBox->e23;
+ gradTransf->e22 *= mBBox->e22;
+ gradTransf->e21 *= mBBox->e22;
+}
+
+static LinearGradient* _applyLinearGradientProperty(SvgStyleGradient* g, const Box& vBox, const Box& viewport, int opacity)
+{
+ Fill::ColorStop* stops;
+ auto fillGrad = LinearGradient::gen();
+ auto isTransform = (g->transform ? true : false);
+ auto& finalTransform = fillGrad->transform();
+ if (isTransform) finalTransform = *g->transform;
+
+ if (g->userSpace) {
+ fillGrad->linear(g->linear.x1 * (g->linear.isX1Percentage ? vBox.w : viewport.w),
+ g->linear.y1 * (g->linear.isY1Percentage ? vBox.h : viewport.h),
+ g->linear.x2 * (g->linear.isX2Percentage ? vBox.w : viewport.w),
+ g->linear.y2 * (g->linear.isY2Percentage ? vBox.h : viewport.h));
+ } else {
+ Matrix m = {vBox.w, 0, vBox.x, 0, vBox.h, vBox.y, 0, 0, 1};
+ if (isTransform) _transformMultiply(&m, &finalTransform);
+ else finalTransform = m;
+ fillGrad->linear(g->linear.x1, g->linear.y1, g->linear.x2, g->linear.y2);
+ }
+ fillGrad->spread(g->spread);
+
+ //Update the stops
+ if (g->stops.count == 0) return fillGrad;
+
+ stops = tvg::malloc<Fill::ColorStop>(g->stops.count * sizeof(Fill::ColorStop));
+ auto prevOffset = 0.0f;
+ for (uint32_t i = 0; i < g->stops.count; ++i) {
+ auto colorStop = &g->stops[i];
+ //Use premultiplied color
+ stops[i].r = colorStop->r;
+ stops[i].g = colorStop->g;
+ stops[i].b = colorStop->b;
+ stops[i].a = static_cast<uint8_t>((colorStop->a * opacity) / 255);
+ stops[i].offset = colorStop->offset;
+ //check the offset corner cases - refer to: https://svgwg.org/svg2-draft/pservers.html#StopNotes
+ if (colorStop->offset < prevOffset) stops[i].offset = prevOffset;
+ else if (colorStop->offset > 1) stops[i].offset = 1;
+ prevOffset = stops[i].offset;
+ }
+ fillGrad->colorStops(stops, g->stops.count);
+ tvg::free(stops);
+ return fillGrad;
+}
+
+static RadialGradient* _applyRadialGradientProperty(SvgStyleGradient* g, const Box& vBox, const Box& viewport, int opacity)
+{
+ Fill::ColorStop *stops;
+ auto fillGrad = RadialGradient::gen();
+ auto isTransform = (g->transform ? true : false);
+ auto& finalTransform = fillGrad->transform();
+ if (isTransform) finalTransform = *g->transform;
+
+ if (g->userSpace) {
+ //The radius scaling is done according to the Units section:
+ //https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
+ auto diag = sqrtf(powf(vBox.w, 2.0f) + powf(vBox.h, 2.0f)) / sqrtf(2.0f);
+ auto viewportDiag = sqrtf(powf(viewport.w, 2.0f) + powf(viewport.h, 2.0f)) / sqrtf(2.0f);
+ fillGrad->radial(g->radial.cx * (g->radial.isCxPercentage ? vBox.w : viewport.w),
+ g->radial.cy * (g->radial.isCyPercentage ? vBox.h : viewport.h),
+ g->radial.r * (g->radial.isRPercentage ? diag : viewportDiag),
+ g->radial.fx * (g->radial.isFxPercentage ? vBox.w : viewport.w),
+ g->radial.fy * (g->radial.isFyPercentage ? vBox.h : viewport.h),
+ g->radial.fr * (g->radial.isFrPercentage ? diag : viewportDiag));
+ } else {
+ Matrix m = {vBox.w, 0, vBox.x, 0, vBox.h, vBox.y, 0, 0, 1};
+ if (isTransform) _transformMultiply(&m, &finalTransform);
+ else finalTransform = m;
+ fillGrad->radial(g->radial.cx, g->radial.cy, g->radial.r, g->radial.fx, g->radial.fy, g->radial.fr);
+ }
+ fillGrad->spread(g->spread);
+
+ //Update the stops
+ if (g->stops.count == 0) return fillGrad;
+
+ stops = tvg::malloc<Fill::ColorStop>(g->stops.count * sizeof(Fill::ColorStop));
+ auto prevOffset = 0.0f;
+ for (uint32_t i = 0; i < g->stops.count; ++i) {
+ auto colorStop = &g->stops[i];
+ //Use premultiplied color
+ stops[i].r = colorStop->r;
+ stops[i].g = colorStop->g;
+ stops[i].b = colorStop->b;
+ stops[i].a = static_cast<uint8_t>((colorStop->a * opacity) / 255);
+ stops[i].offset = colorStop->offset;
+ //check the offset corner cases - refer to: https://svgwg.org/svg2-draft/pservers.html#StopNotes
+ if (colorStop->offset < prevOffset) stops[i].offset = prevOffset;
+ else if (colorStop->offset > 1) stops[i].offset = 1;
+ prevOffset = stops[i].offset;
+ }
+ fillGrad->colorStops(stops, g->stops.count);
+ tvg::free(stops);
+ return fillGrad;
+}
+
+
+static void _appendRect(Shape* shape, float x, float y, float w, float h, float rx, float ry)
+{
+ auto halfW = w * 0.5f;
+ auto halfH = h * 0.5f;
+
+ //clamping cornerRadius by minimum size
+ if (rx > halfW) rx = halfW;
+ if (ry > halfH) ry = halfH;
+
+ if (rx == 0 && ry == 0) {
+ to<ShapeImpl>(shape)->grow(5, 4);
+ shape->moveTo(x, y);
+ shape->lineTo(x + w, y);
+ shape->lineTo(x + w, y + h);
+ shape->lineTo(x, y + h);
+ shape->close();
+ } else {
+ auto hrx = rx * PATH_KAPPA;
+ auto hry = ry * PATH_KAPPA;
+
+ to<ShapeImpl>(shape)->grow(10, 17);
+ shape->moveTo(x + rx, y);
+ shape->lineTo(x + w - rx, y);
+ shape->cubicTo(x + w - rx + hrx, y, x + w, y + ry - hry, x + w, y + ry);
+ shape->lineTo(x + w, y + h - ry);
+ shape->cubicTo(x + w, y + h - ry + hry, x + w - rx + hrx, y + h, x + w - rx, y + h);
+ shape->lineTo(x + rx, y + h);
+ shape->cubicTo(x + rx - hrx, y + h, x, y + h - ry + hry, x, y + h - ry);
+ shape->lineTo(x, y + ry);
+ shape->cubicTo(x, y + ry - hry, x + rx - hrx, y, x + rx, y);
+ shape->close();
+ }
+}
+
+
+static void _appendCircle(Shape* shape, float cx, float cy, float rx, float ry)
+{
+ // Resolve unspecified or invalid radii from the other axis (SVG 2).
+ if (rx < 0.0f) rx = ry;
+ else if (ry < 0.0f) ry = rx;
+ if (rx <= 0.0f || ry <= 0.0f) return;
+
+ auto rxKappa = rx * PATH_KAPPA;
+ auto ryKappa = ry * PATH_KAPPA;
+
+ to<ShapeImpl>(shape)->grow(6, 13);
+ shape->moveTo(cx + rx, cy);
+ shape->cubicTo(cx + rx, cy + ryKappa, cx + rxKappa, cy + ry, cx, cy + ry);
+ shape->cubicTo(cx - rxKappa, cy + ry, cx - rx, cy + ryKappa, cx - rx, cy);
+ shape->cubicTo(cx - rx, cy - ryKappa, cx - rxKappa, cy - ry, cx, cy - ry);
+ shape->cubicTo(cx + rxKappa, cy - ry, cx + rx, cy - ryKappa, cx + rx, cy);
+ shape->close();
+}
+
+static bool _appendClipChild(SvgParserContext& ctx, SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath, Paint** clipped)
+{
+ Matrix finalTransform;
+ const Matrix* transform = nullptr;
+
+ //The SVG standard allows only for 'use' nodes that point directly to a basic shape.
+ if (node->type == SvgNodeType::Use) {
+ if (node->child.count != 1) {
+ *clipped = nullptr;
+ return false;
+ }
+ auto child = *(node->child.data);
+ finalTransform = tvg::identity();
+ if (node->transform) finalTransform = *node->transform;
+ if (node->node.use.x != 0.0f || node->node.use.y != 0.0f) {
+ finalTransform *= {1, 0, node->node.use.x, 0, 1, node->node.use.y, 0, 0, 1};
+ }
+ if (child->transform) finalTransform *= *child->transform;
+
+ transform = tvg::identity((const Matrix*)(&finalTransform)) ? nullptr : &finalTransform;
+ node = child;
+ }
+
+ if (!_appendClipShape(ctx, node, shape, vBox, svgPath, transform)) {
+ *clipped = nullptr;
+ return false;
+ }
+
+ // Apply Clip Chaining
+ if (auto clipNode = node->style->clipPath.node) {
+ if (node->style->clipPath.applying) {
+ TVGLOG("SVG", "Multiple composition tried! Check out circular dependency?");
+ *clipped = nullptr;
+ return false;
+ }
+ return _applyClip(ctx, shape, shape, node, clipNode, vBox, svgPath, clipped);
+ }
+
+ *clipped = shape;
+ return true;
+}
+
+static Matrix _useTransform(const SvgNode* node)
+{
+ auto m = tvg::identity();
+ if (node->transform) m = *node->transform;
+ if (node->node.use.x != 0.0f || node->node.use.y != 0.0f) {
+ m *= {1, 0, node->node.use.x, 0, 1, node->node.use.y, 0, 0, 1};
+ }
+ return m;
+}
+
+static Matrix _compositionTransform(Paint* content, const SvgNode* node, const SvgNode* compNode, SvgNodeType type)
+{
+ auto m = tvg::identity();
+ auto userSpace = (type == SvgNodeType::Mask) ? compNode->node.mask.maskContentUserSpace : compNode->node.clip.userSpace;
+ //The initial mask transformation ignored according to the SVG standard.
+ if (node->type == SvgNodeType::Use) {
+ if (type != SvgNodeType::Mask || !userSpace) m = _useTransform(node);
+ } else if (node->transform && type != SvgNodeType::Mask) {
+ m = *node->transform;
+ }
+ if (compNode->transform) {
+ m *= *compNode->transform;
+ }
+ if (!userSpace) {
+ auto bbox = Box{};
+ if (node->type == SvgNodeType::Use) {
+ auto useTransform = _useTransform(node);
+ Matrix inv;
+ auto prevTransform = content->transform();
+ if (inverse(&useTransform, &inv)) content->transform(inv * prevTransform);
+ bbox = _bounds(content);
+ content->transform(prevTransform);
+ } else {
+ bbox = _bounds(content);
+ }
+ m *= {bbox.w, 0, bbox.x, 0, bbox.h, bbox.y, 0, 0, 1};
+ }
+ return m;
+}
+
+static bool _clipperUnion(SvgParserContext& ctx, Paint* content, const SvgNode* node, const SvgNode* clipNode, const Box& vBox, const string& svgPath, Paint** region)
+{
+ node->style->clipPath.applying = true;
+
+ Paint* unionRegion = nullptr;
+ Scene* scene = nullptr;
+ ARRAY_FOREACH(p, clipNode->child) {
+ auto child = Shape::gen();
+ Paint* clipped = nullptr;
+ if (!_appendClipChild(ctx, *p, child, vBox, svgPath, &clipped)) {
+ Paint::rel(child);
+ continue;
+ }
+ child->fill(255, 255, 255, 255);
+ if (!unionRegion) unionRegion = clipped;
+ else {
+ if (!scene) {
+ scene = Scene::gen();
+ scene->add(unionRegion);
+ unionRegion = scene;
+ }
+ scene->add(clipped);
+ }
+ }
+
+ node->style->clipPath.applying = false;
+
+ if (!unionRegion) {
+ *region = nullptr;
+ return false;
+ }
+
+ unionRegion->transform(_compositionTransform(content, node, clipNode, SvgNodeType::ClipPath));
+ *region = unionRegion;
+ return true;
+}
+
+static bool _applyClip(SvgParserContext& ctx, Paint* paint, Paint* content, const SvgNode* node, const SvgNode* clipNode, const Box& vBox, const string& svgPath, Paint** result)
+{
+ Paint* region = nullptr;
+ if (!_clipperUnion(ctx, content, node, clipNode, vBox, svgPath, &region)) {
+ *result = nullptr;
+ return false;
+ }
+
+ paint->mask(region, MaskMethod::Alpha);
+
+ *result = paint;
+ if (auto innerClipNode = clipNode->style->clipPath.node) {
+ if (!innerClipNode->style->clipPath.applying) {
+ innerClipNode->style->clipPath.applying = true;
+ auto scene = Scene::gen();
+ scene->add(paint);
+ if (!_applyClip(ctx, scene, content, node, innerClipNode, vBox, svgPath, result)) {
+ scene->opacity(0);
+ *result = scene;
+ }
+ innerClipNode->style->clipPath.applying = false;
+ }
+ }
+ return true;
+}
+
+static Scene* _applyMask(SvgParserContext& ctx, Paint* content, Scene* target, const SvgNode* node, const SvgNode* maskNode, const Box& vBox, const string& svgPath, bool wrap)
+{
+ node->style->mask.applying = true;
+
+ Scene* result = target;
+ if (auto mask = _sceneBuildHelper(ctx, maskNode, vBox, svgPath, true, 0)) {
+ auto& maskData = maskNode->node.mask;
+ auto nodeTransform = (node->type == SvgNodeType::Use) ? _useTransform(node) : (node->transform ? *node->transform : tvg::identity());
+ if (!maskData.maskContentUserSpace) {
+ Matrix finalTransform = _compositionTransform(content, node, maskNode, SvgNodeType::Mask);
+ mask->transform(finalTransform);
+ } else if (!tvg::identity((const Matrix*)(&nodeTransform))) {
+ mask->transform(nodeTransform);
+ }
+
+ auto bbox = _bounds(content);
+ auto clipper = Shape::gen();
+ if (maskData.userSpace) {
+ clipper->appendRect(maskData.box.x, maskData.box.y, maskData.box.w, maskData.box.h);
+ if (!tvg::identity((const Matrix*)(&nodeTransform))) clipper->transform(nodeTransform);
+ } else {
+ auto box = _objectBoundingBox(maskData.box, bbox);
+ clipper->appendRect(box.x, box.y, box.w, box.h);
+ }
+ mask->clip(clipper);
+
+ if (wrap) {
+ auto scene = Scene::gen();
+ scene->add(target);
+ result = scene;
+ }
+ result->mask(mask, maskData.type == SvgMaskType::Luminance ? MaskMethod::Luma : MaskMethod::Alpha);
+ }
+
+ node->style->mask.applying = false;
+ return result;
+}
+
+static Paint* _applyBlend(Paint* paint, const SvgNode* node)
+{
+ if (paint && (node->style->flags & SvgStyleFlags::BlendMode)) {
+ paint->blend(node->style->blendMode);
+ }
+ return paint;
+}
+
+
+static Paint* _applyComposition(SvgParserContext& ctx, Paint* paint, const SvgNode* node, const Box& vBox, const string& svgPath)
+{
+ if (node->style->clipPath.applying || node->style->mask.applying) {
+ TVGLOG("SVG", "Multiple composition tried! Check out circular dependency?");
+ return paint;
+ }
+
+ auto clipNode = node->style->clipPath.node;
+ auto maskNode = node->style->mask.node;
+
+ if (!clipNode && !maskNode) return paint;
+ if ((clipNode && clipNode->child.empty()) || (maskNode && maskNode->child.empty())) {
+ Paint::rel(paint);
+ return nullptr;
+ }
+
+ auto scene = Scene::gen();
+ scene->add(paint);
+
+ if (clipNode) {
+ Paint* clipped = nullptr;
+ if (!_applyClip(ctx, scene, paint, node, clipNode, vBox, svgPath, &clipped)) {
+ Paint::rel(scene);
+ return nullptr;
+ }
+ scene = static_cast<Scene*>(clipped);
+ }
+
+ if (maskNode) scene = _applyMask(ctx, paint, scene, node, maskNode, vBox, svgPath, clipNode != nullptr);
+
+ return scene;
+}
+
+static Paint* _applyFilter(SvgParserContext& ctx, Paint* paint, const SvgNode* node, const Box& vBox, const string& svgPath)
+{
+ auto filterNode = node->style->filter.node;
+ if (!filterNode || filterNode->child.count == 0) return paint;
+
+ auto& filter = filterNode->node.filter;
+ auto scene = Scene::gen();
+ auto bbox = _bounds(paint);
+ auto clipBox = filter.filterUserSpace ? filter.box : _objectBoundingBox(filter.box, bbox);
+ auto primitiveUserSpace = filter.primitiveUserSpace;
+ auto sx = paint->transform().e11;
+ auto sy = paint->transform().e22;
+
+ auto child = filterNode->child.data;
+ for (uint32_t i = 0; i < filterNode->child.count; ++i, ++child) {
+ if ((*child)->type == SvgNodeType::GaussianBlur) {
+ auto& gauss = (*child)->node.gaussianBlur;
+
+ auto direction = gauss.stdDevX > 0.0f ? (gauss.stdDevY > 0.0f ? 0 : 1) : (gauss.stdDevY > 0.0f ? 2 : -1);
+ if (direction == -1) continue;
+
+ auto stdDevX = gauss.stdDevX;
+ auto stdDevY = gauss.stdDevY;
+ if (gauss.hasBox) {
+ auto gaussBox = gauss.box;
+ auto isPercent = gauss.isPercentage;
+ if (primitiveUserSpace) {
+ if (isPercent[0]) gaussBox.x *= ctx.parser->global.w;
+ if (isPercent[1]) gaussBox.y *= ctx.parser->global.h;
+ if (isPercent[2]) gaussBox.w *= ctx.parser->global.w;
+ if (isPercent[3]) gaussBox.h *= ctx.parser->global.h;
+ } else {
+ stdDevX *= bbox.w;
+ stdDevY *= bbox.h;
+ if (isPercent[0]) gaussBox.x = bbox.x + gauss.box.x * bbox.w;
+ if (isPercent[1]) gaussBox.y = bbox.y + gauss.box.y * bbox.h;
+ if (isPercent[2]) gaussBox.w *= bbox.w;
+ if (isPercent[3]) gaussBox.h *= bbox.h;
+ }
+ clipBox.intersect(gaussBox);
+ } else if (!primitiveUserSpace) {
+ stdDevX *= bbox.w;
+ stdDevY *= bbox.h;
+ }
+ scene->add(SceneEffect::GaussianBlur, (double)(1.25f * (direction == 2 ? stdDevY * sy : stdDevX * sx)), direction, gauss.edgeModeWrap, 55);
+ }
+ }
+
+ scene->add(paint);
+
+ auto clip = Shape::gen();
+ clip->appendRect(clipBox.x, clipBox.y, clipBox.w, clipBox.h);
+ scene->clip(clip);
+
+ return scene;
+}
+
+static void _applyStroke(SvgStyleProperty* style, Shape* vg, const Box& vBox, const Box& viewport)
+{
+ vg->strokeWidth(style->stroke.width);
+ vg->strokeCap(style->stroke.cap);
+ vg->strokeJoin(style->stroke.join);
+ vg->strokeMiterlimit(style->stroke.miterlimit);
+ vg->strokeDash(style->stroke.dash.array.data, style->stroke.dash.array.count, style->stroke.dash.offset);
+
+ if (style->stroke.paint.none) {
+ vg->strokeWidth(0.0f);
+ } else if (style->stroke.paint.gradient) {
+ auto bBox = style->stroke.paint.gradient->userSpace ? vBox : _bounds(vg);
+ if (style->stroke.paint.gradient->type == SvgGradientType::Linear) {
+ vg->strokeFill(_applyLinearGradientProperty(style->stroke.paint.gradient, bBox, viewport, style->stroke.opacity));
+ } else if (style->stroke.paint.gradient->type == SvgGradientType::Radial) {
+ vg->strokeFill(_applyRadialGradientProperty(style->stroke.paint.gradient, bBox, viewport, style->stroke.opacity));
+ }
+ } else if (style->stroke.paint.url) {
+ TVGLOG("SVG", "The stroke's url not supported.");
+ } else if (style->stroke.paint.curColor) {
+ vg->strokeFill(style->color.r, style->color.g, style->color.b, MULTIPLY(style->stroke.opacity, style->color.a));
+ } else {
+ vg->strokeFill(style->stroke.paint.color.r, style->stroke.paint.color.g, style->stroke.paint.color.b, MULTIPLY(style->stroke.opacity, style->stroke.paint.color.a));
+ }
+}
+
+static Paint* _applyProperty(SvgParserContext& ctx, SvgNode* node, Shape* vg, const Box& vBox, const string& svgPath, bool clip)
+{
+ SvgStyleProperty* style = node->style;
+
+ //Clip transformation is applied directly to the path in the _appendClipShape function
+ if (node->type == SvgNodeType::Doc || !node->style->display) return vg;
+
+ //If fill property is nullptr then do nothing
+ if (style->fill.paint.none) {
+ //Do nothing
+ } else if (style->fill.paint.gradient) {
+ auto bBox = style->fill.paint.gradient->userSpace ? vBox : _bounds(vg);
+ if (style->fill.paint.gradient->type == SvgGradientType::Linear) {
+ vg->fill(_applyLinearGradientProperty(style->fill.paint.gradient, bBox, ctx.parser->global, style->fill.opacity));
+ } else if (style->fill.paint.gradient->type == SvgGradientType::Radial) {
+ vg->fill(_applyRadialGradientProperty(style->fill.paint.gradient, bBox, ctx.parser->global, style->fill.opacity));
+ }
+ } else if (style->fill.paint.pattern) {
+ if (auto patternPaint = _applyPatternProperty(ctx, vg, node, style->fill.paint.pattern, vBox, svgPath)) {
+ vg->fillRule(style->fill.fillRule);
+ vg->order(!style->paintOrder);
+ _applyStroke(style, vg, vBox, ctx.parser->global);
+ auto patternScene = Scene::gen();
+ patternScene->add(patternPaint);
+ patternScene->add(vg);
+ patternScene->opacity(style->opacity);
+ if (node->transform && !clip) patternScene->transform(*node->transform);
+ auto p = _applyFilter(ctx, patternScene, node, vBox, svgPath);
+ p = _applyComposition(ctx, p, node, vBox, svgPath);
+ return _applyBlend(p, node);
+ }
+ } else if (style->fill.paint.url) {
+ TVGLOG("SVG", "The fill's url not supported.");
+ } else if (style->fill.paint.curColor) {
+ //Apply the current style color
+ vg->fill(style->color.r, style->color.g, style->color.b, MULTIPLY(style->fill.opacity, style->color.a));
+ } else {
+ //Apply the fill color
+ vg->fill(style->fill.paint.color.r, style->fill.paint.color.g, style->fill.paint.color.b, MULTIPLY(style->fill.opacity, style->fill.paint.color.a));
+ }
+
+ vg->fillRule(style->fill.fillRule);
+ vg->order(!style->paintOrder);
+ vg->opacity(style->opacity);
+
+ if (node->type == SvgNodeType::G || node->type == SvgNodeType::Use) {
+ if (style->flags & SvgStyleFlags::BlendMode) vg->blend(style->blendMode);
+ return vg;
+ }
+
+ _applyStroke(style, vg, vBox, ctx.parser->global);
+
+ //apply transform after the local space shape bbox for gradient acquisition
+ if (node->transform && !clip) vg->transform(*node->transform);
+
+ auto p = _applyFilter(ctx, vg, node, vBox, svgPath);
+ p = _applyComposition(ctx, p, node, vBox, svgPath);
+ return _applyBlend(p, node);
+}
+
+
+static bool _recognizeShape(SvgNode* node, Shape* shape)
+{
+ switch (node->type) {
+ case SvgNodeType::Path: {
+ if (node->node.path.path) {
+ if (!svgPathToShape(node->node.path.path, to<ShapeImpl>(shape)->rs.path)) {
+ TVGERR("SVG", "Invalid path information.");
+ return false;
+ }
+ }
+ break;
+ }
+ case SvgNodeType::Ellipse: {
+ _appendCircle(shape, node->node.ellipse.cx, node->node.ellipse.cy, node->node.ellipse.rx, node->node.ellipse.ry);
+ break;
+ }
+ case SvgNodeType::Polygon: {
+ if (node->node.polygon.pts.count < 2) break;
+ auto pts = node->node.polygon.pts.begin();
+ shape->moveTo(pts[0], pts[1]);
+ for (pts += 2; pts < node->node.polygon.pts.end(); pts += 2) {
+ shape->lineTo(pts[0], pts[1]);
+ }
+ shape->close();
+ break;
+ }
+ case SvgNodeType::Polyline: {
+ if (node->node.polyline.pts.count < 2) break;
+ auto pts = node->node.polyline.pts.begin();
+ shape->moveTo(pts[0], pts[1]);
+ for (pts += 2; pts < node->node.polyline.pts.end(); pts += 2) {
+ shape->lineTo(pts[0], pts[1]);
+ }
+ break;
+ }
+ case SvgNodeType::Circle: {
+ _appendCircle(shape, node->node.circle.cx, node->node.circle.cy, node->node.circle.r, node->node.circle.r);
+ break;
+ }
+ case SvgNodeType::Rect: {
+ _appendRect(shape, node->node.rect.x, node->node.rect.y, node->node.rect.w, node->node.rect.h, node->node.rect.rx, node->node.rect.ry);
+ break;
+ }
+ case SvgNodeType::Line: {
+ shape->moveTo(node->node.line.x1, node->node.line.y1);
+ shape->lineTo(node->node.line.x2, node->node.line.y2);
+ break;
+ }
+ default: {
+ return false;
+ }
+ }
+ return true;
+}
+
+static Paint* _shapeBuildHelper(SvgParserContext& ctx, SvgNode* node, const Box& vBox, const string& svgPath)
+{
+ auto shape = Shape::gen();
+ if (!_recognizeShape(node, shape)) return nullptr;
+ return _applyProperty(ctx, node, shape, vBox, svgPath, false);
+}
+
+static bool _appendClipShape(SvgParserContext& ctx, SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath, const Matrix* transform)
+{
+ uint32_t currentPtsCnt;
+ shape->path(nullptr, nullptr, nullptr, &currentPtsCnt);
+
+ if (!_recognizeShape(node, shape)) return false;
+
+ //The 'transform' matrix has higher priority than the node->transform, since it already contains it
+ auto m = transform ? transform : (node->transform ? node->transform : nullptr);
+
+ if (m) {
+ const Point *pts;
+ uint32_t ptsCnt;
+ shape->path(nullptr, nullptr, &pts, &ptsCnt);
+ auto p = const_cast<Point*>(pts) + currentPtsCnt;
+ while (currentPtsCnt++ < ptsCnt) {
+ *p *= *m;
+ ++p;
+ }
+ }
+
+ return true;
+}
+
+
+enum class imageMimeTypeEncoding
+{
+ base64 = 0x1,
+ utf8 = 0x2
+};
+
+
+constexpr imageMimeTypeEncoding operator|(imageMimeTypeEncoding a, imageMimeTypeEncoding b) {
+ return static_cast<imageMimeTypeEncoding>(static_cast<int>(a) | static_cast<int>(b));
+}
+
+
+constexpr bool operator&(imageMimeTypeEncoding a, imageMimeTypeEncoding b) {
+ return (static_cast<int>(a) & static_cast<int>(b));
+}
+
+
+static constexpr struct
+{
+ const char* name;
+ int sz;
+ imageMimeTypeEncoding encoding;
+} imageMimeTypes[] = {
+ {"jpeg", sizeof("jpeg"), imageMimeTypeEncoding::base64},
+ {"png", sizeof("png"), imageMimeTypeEncoding::base64},
+ {"webp", sizeof("webp"), imageMimeTypeEncoding::base64},
+ {"svg+xml", sizeof("svg+xml"), imageMimeTypeEncoding::base64 | imageMimeTypeEncoding::utf8},
+};
+
+
+static bool _isValidImageMimeTypeAndEncoding(const char** href, const char** mimetype, imageMimeTypeEncoding* encoding) {
+ if (strncasecmp(*href, "image/", sizeof("image/") - 1)) return false; // not allowed mime type
+ *href += sizeof("image/") - 1;
+
+ //RFC2397 data:[<mediatype>][;base64],<data>
+ //mediatype := [ type "/" subtype ] *( ";" parameter )
+ //parameter := attribute "=" value
+ for (unsigned int i = 0; i < sizeof(imageMimeTypes) / sizeof(imageMimeTypes[0]); i++) {
+ if (strncasecmp(*href, imageMimeTypes[i].name, imageMimeTypes[i].sz - 1)) continue;
+ *href += imageMimeTypes[i].sz - 1;
+ *mimetype = imageMimeTypes[i].name;
+
+ while (**href && **href != ',') {
+ while (**href && **href != ';') ++(*href);
+ if (!**href) return false;
+ ++(*href);
+
+ if (imageMimeTypes[i].encoding & imageMimeTypeEncoding::base64) {
+ if (!strncasecmp(*href, "base64,", sizeof("base64,") - 1)) {
+ *href += sizeof("base64,") - 1;
+ *encoding = imageMimeTypeEncoding::base64;
+ return true; //valid base64
+ }
+ }
+ if (imageMimeTypes[i].encoding & imageMimeTypeEncoding::utf8) {
+ if (!strncasecmp(*href, "utf8,", sizeof("utf8,") - 1)) {
+ *href += sizeof("utf8,") - 1;
+ *encoding = imageMimeTypeEncoding::utf8;
+ return true; //valid utf8
+ }
+ }
+ }
+ //no encoding defined
+ if (**href == ',' && (imageMimeTypes[i].encoding & imageMimeTypeEncoding::utf8)) {
+ ++(*href);
+ *encoding = imageMimeTypeEncoding::utf8;
+ return true; //allow no encoding defined if utf8 expected
+ }
+ return false;
+ }
+ return false;
+}
+
+#include "tvgTaskScheduler.h"
+
+static Paint* _imageBuildHelper(SvgParserContext& ctx, SvgNode* node, const Box& vBox, const string& svgPath)
+{
+ if (!node->node.image.href || !strlen(node->node.image.href)) return nullptr;
+
+ auto picture = Picture::gen();
+
+ const char* href = node->node.image.href;
+ if (!strncmp(href, "data:", sizeof("data:") - 1)) {
+ href += sizeof("data:") - 1;
+ const char* mimetype;
+ imageMimeTypeEncoding encoding;
+ if (!_isValidImageMimeTypeAndEncoding(&href, &mimetype, &encoding)) return nullptr; //not allowed mime type or encoding
+ char *decoded = nullptr;
+ if (encoding == imageMimeTypeEncoding::base64) {
+ auto size = b64Decode(href, strlen(href), &decoded);
+ if (picture->load(decoded, size, mimetype) != Result::Success) {
+ tvg::free(decoded);
+ return nullptr;
+ }
+ } else {
+ auto size = svgUtilURLDecode(href, &decoded);
+ if (picture->load(decoded, size, mimetype) != Result::Success) {
+ tvg::free(decoded);
+ return nullptr;
+ }
+ }
+ ctx.images.push(decoded);
+ } else {
+ if (!strncmp(href, "file://", sizeof("file://") - 1)) href += sizeof("file://") - 1;
+ //TODO: protect against recursive svg image loading
+ //Temporarily disable embedded svg:
+ const char *dot = strrchr(href, '.');
+ if (dot && STR_AS(dot, ".svg")) {
+ TVGLOG("SVG", "Embedded svg file is disabled.");
+ return nullptr;
+ }
+ string imagePath = href;
+ if (strncmp(href, "/", 1)) {
+ auto last = svgPath.find_last_of("/");
+ imagePath = svgPath.substr(0, (last == string::npos ? 0 : last + 1)) + imagePath;
+ }
+ if (picture->load(imagePath.c_str()) != Result::Success) {
+ return nullptr;
+ }
+ }
+
+ float w, h;
+ Matrix m;
+ if (picture->size(&w, &h) == Result::Success && w > 0 && h > 0) {
+ auto sx = node->node.image.w / w;
+ auto sy = node->node.image.h / h;
+ m = {sx, 0, node->node.image.x, 0, sy, node->node.image.y, 0, 0, 1};
+ } else {
+ m = tvg::identity();
+ }
+ if (node->transform) m = *node->transform * m;
+ picture->transform(m);
+
+ auto p = _applyFilter(ctx, picture, node, vBox, svgPath);
+ p = _applyComposition(ctx, p, node, vBox, svgPath);
+ return _applyBlend(p, node);
+}
+
+
+static Matrix _calculateAspectRatioMatrix(AspectRatioAlign align, AspectRatioMeetOrSlice meetOrSlice, float width, float height, const Box& box)
+{
+ auto sx = width / box.w;
+ auto sy = height / box.h;
+ auto tvx = box.x * sx;
+ auto tvy = box.y * sy;
+
+ if (align == AspectRatioAlign::None) return {sx, 0, -tvx, 0, sy, -tvy, 0, 0, 1};
+
+ //Scale
+ if (meetOrSlice == AspectRatioMeetOrSlice::Meet) {
+ if (sx < sy) sy = sx;
+ else sx = sy;
+ } else {
+ if (sx < sy) sx = sy;
+ else sy = sx;
+ }
+
+ //Align
+ tvx = box.x * sx;
+ tvy = box.y * sy;
+ auto tvw = box.w * sx;
+ auto tvh = box.h * sy;
+
+ switch (align) {
+ case AspectRatioAlign::XMinYMin: {
+ break;
+ }
+ case AspectRatioAlign::XMidYMin: {
+ tvx -= (width - tvw) * 0.5f;
+ break;
+ }
+ case AspectRatioAlign::XMaxYMin: {
+ tvx -= width - tvw;
+ break;
+ }
+ case AspectRatioAlign::XMinYMid: {
+ tvy -= (height - tvh) * 0.5f;
+ break;
+ }
+ case AspectRatioAlign::XMidYMid: {
+ tvx -= (width - tvw) * 0.5f;
+ tvy -= (height - tvh) * 0.5f;
+ break;
+ }
+ case AspectRatioAlign::XMaxYMid: {
+ tvx -= width - tvw;
+ tvy -= (height - tvh) * 0.5f;
+ break;
+ }
+ case AspectRatioAlign::XMinYMax: {
+ tvy -= height - tvh;
+ break;
+ }
+ case AspectRatioAlign::XMidYMax: {
+ tvx -= (width - tvw) * 0.5f;
+ tvy -= height - tvh;
+ break;
+ }
+ case AspectRatioAlign::XMaxYMax: {
+ tvx -= width - tvw;
+ tvy -= height - tvh;
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+
+ return {sx, 0, -tvx, 0, sy, -tvy, 0, 0, 1};
+}
+
+static Matrix _symbolTransform(const SvgNode* node, const Box& vBox)
+{
+ auto& symbol = node->node.use.symbol->node.symbol;
+ auto width = (symbol.hasWidth ? symbol.w : vBox.w);
+ if (node->node.use.isWidthSet) width = node->node.use.w;
+ auto height = (symbol.hasHeight ? symbol.h : vBox.h);
+ if (node->node.use.isHeightSet) height = node->node.use.h;
+ auto vw = (symbol.hasViewBox ? symbol.vw : width);
+ auto vh = (symbol.hasViewBox ? symbol.vh : height);
+
+ auto mViewBox = tvg::identity();
+ if ((!tvg::equal(width, vw) || !tvg::equal(height, vh)) && vw > 0 && vh > 0) {
+ Box box = {symbol.vx, symbol.vy, vw, vh};
+ mViewBox = _calculateAspectRatioMatrix(symbol.align, symbol.meetOrSlice, width, height, box);
+ } else if (!tvg::zero(symbol.vx) || !tvg::zero(symbol.vy)) {
+ mViewBox = {1, 0, -symbol.vx, 0, 1, -symbol.vy, 0, 0, 1};
+ }
+
+ // mSceneTransform = mUseTransform * mSymbolTransform * mViewBox
+ Matrix mSceneTransform = mViewBox;
+ if (node->node.use.symbol->transform) {
+ mSceneTransform = *node->node.use.symbol->transform * mViewBox;
+ }
+ return _useTransform(node) * mSceneTransform;
+}
+
+static Scene* _useBuildHelper(SvgParserContext& ctx, const SvgNode* node, const Box& vBox, const string& svgPath, int depth)
+{
+ auto scene = _sceneBuildHelper(ctx, node, vBox, svgPath, false, depth + 1);
+
+ if (node->node.use.symbol) {
+ if (!node->node.use.symbol->node.symbol.overflowVisible) {
+ auto& symbol = node->node.use.symbol->node.symbol;
+ auto width = (symbol.hasWidth ? symbol.w : vBox.w);
+ if (node->node.use.isWidthSet) width = node->node.use.w;
+ auto height = (symbol.hasHeight ? symbol.h : vBox.h);
+ if (node->node.use.isHeightSet) height = node->node.use.h;
+
+ auto viewBoxClip = Shape::gen();
+ viewBoxClip->appendRect(0, 0, width, height);
+
+ // mClipTransform = mUseTransform * mSymbolTransform
+ Matrix mClipTransform = _useTransform(node);
+ if (node->node.use.symbol->transform) {
+ mClipTransform = mClipTransform * *node->node.use.symbol->transform;
+ }
+ viewBoxClip->transform(mClipTransform);
+
+ auto clippingLayer = Scene::gen();
+ clippingLayer->clip(viewBoxClip);
+ clippingLayer->add(scene);
+ return clippingLayer;
+ }
+ return scene;
+ }
+
+ return scene;
+}
+
+static void _applyTextFill(SvgStyleProperty* style, Text* text, const SvgTextNode& textNode, const Box& vBox, const Box& viewport)
+{
+ // If fill property is nullptr then do nothing
+ if (style->fill.paint.none) {
+ //Do nothing
+ } else if (style->fill.paint.gradient) {
+ auto bBox = style->fill.paint.gradient->userSpace ? vBox : _bounds(text);
+ if (style->fill.paint.gradient->type == SvgGradientType::Linear) {
+ text->fill(_applyLinearGradientProperty(style->fill.paint.gradient, bBox, viewport, style->fill.opacity));
+ } else if (style->fill.paint.gradient->type == SvgGradientType::Radial) {
+ text->fill(_applyRadialGradientProperty(style->fill.paint.gradient, bBox, viewport, style->fill.opacity));
+ }
+ } else if (style->fill.paint.url) {
+ //TODO: Apply the color pointed by url
+ TVGLOG("SVG", "The fill's url not supported.");
+ } else {
+ const auto& color = style->fill.paint.curColor ? style->color : style->fill.paint.color;
+ text->fill(color.r, color.g, color.b);
+ if (style->fontWeight >= SvgFontWeight::Weight600) text->outline(textNode.fontSize * 0.03f, color.r, color.g, color.b);
+ text->opacity(style->fill.opacity);
+ }
+}
+
+
+static char* _processText(const char* text, SvgXmlSpace space)
+{
+ if (!text) return nullptr;
+
+ auto len = strlen(text);
+ auto processed = (char*)tvg::malloc(len + 1);
+ auto dst = processed;
+ auto src = text;
+
+ if (space == SvgXmlSpace::Preserve) {
+ while (*src) {
+ if (*src == '\n' || *src == '\t' || *src == '\r') *dst++ = ' ';
+ else *dst++ = *src;
+ src++;
+ }
+ *dst = '\0';
+ } else {
+ auto spaceFound = false;
+ src = svgUtilSkipWhiteSpace(src, nullptr);
+
+ while (*src) {
+ if (isspace((unsigned char)*src)) {
+ if (!spaceFound) {
+ *dst++ = ' ';
+ spaceFound = true;
+ }
+ } else {
+ *dst++ = *src;
+ spaceFound = false;
+ }
+ src++;
+ }
+ dst = (char*)svgUtilUnskipWhiteSpace(dst, processed);
+ *dst = '\0';
+ }
+ return processed;
+}
+
+static SvgBaseline _effectiveBaseline(const SvgStyleProperty* style)
+{
+ if (style->alignmentBaseline != SvgBaseline::Auto) return style->alignmentBaseline;
+ return style->dominantBaseline;
+}
+
+static void _applyTextBaseline(Text* text, SvgBaseline baseline, Matrix& transform)
+{
+ if (baseline == SvgBaseline::Auto || baseline == SvgBaseline::Alphabetic) return;
+
+ TextMetrics tm;
+ if (text->metrics(tm) != Result::Success) return; // ascent > 0, descent < 0
+
+ auto shift = 0.0f;
+ // baseline geometry: https://www.w3.org/TR/css-inline-3/#baseline-types
+ // hanging/mathematical are synthesized from the ascent when the font provides no baseline table,
+ // see https://www.w3.org/TR/css-inline-3/#baseline-synthesis-fonts
+ switch (baseline) {
+ case SvgBaseline::BeforeEdge: shift = tm.ascent; break;
+ case SvgBaseline::AfterEdge: shift = tm.descent; break;
+ case SvgBaseline::Central: shift = 0.5f * (tm.ascent + tm.descent); break;
+ case SvgBaseline::Middle: { // half the x-height (top extent of 'x')
+ GlyphMetrics gm;
+ if (text->metrics("x", gm) == Result::Success && gm.max.y > 0.0f) shift = 0.5f * gm.max.y;
+ else shift = 0.27f * tm.ascent; // fallback when the 'x' glyph is missing
+ break;
+ }
+ case SvgBaseline::Hanging: shift = 0.8f * tm.ascent; break;
+ case SvgBaseline::Mathematical: shift = 0.5f * tm.ascent; break;
+ default: return;
+ }
+
+ translateR(&transform, {0.0f, shift});
+ text->transform(transform);
+}
+
+static Text* _buildText(const SvgTextNode* textNode, SvgXmlSpace xmlSpace, const Matrix* transform, SvgBaseline baseline)
+{
+ if (!textNode->text) return nullptr;
+
+ auto text = Text::gen();
+
+ //TODO: handle def values of font and size as used in a system?
+ auto size = textNode->fontSize * 0.75f; //1 pt = 1/72; 1 in = 96 px; -> 72/96 = 0.75
+ if (text->font(textNode->fontFamily) != Result::Success) {
+ text->font(nullptr); //fallback to any available font
+ }
+ text->size(size);
+
+ auto processedText = _processText(textNode->text, xmlSpace);
+ text->text(processedText);
+ tvg::free(processedText);
+
+ TextMetrics tm;
+ text->metrics(tm);
+ auto textTransform = transform ? *transform : tvg::identity();
+ translateR(&textTransform, {textNode->x + textNode->dx, textNode->y + textNode->dy - tm.ascent});
+ text->transform(textTransform);
+
+ _applyTextBaseline(text, baseline, textTransform);
+
+ return text;
+}
+
+static float _applySpacing(Text* text, float letterSpacing, float wordSpacing)
+{
+ if (letterSpacing == 0.0f && wordSpacing == 0.0f) return 1.0f;
+
+ auto utf8 = text->text();
+ auto advance = 0.0f;
+ uint32_t gaps = 0;
+ uint32_t spaces = 0;
+ GlyphMetrics gm;
+ while (utf8 && *utf8) {
+ auto space = *utf8 == ' ';
+ if (text->metrics(utf8, gm, &utf8) != Result::Success) return 1.0f;
+ if (utf8 && *utf8) {
+ advance += gm.advance;
+ ++gaps;
+ if (space) ++spaces;
+ }
+ }
+ if (advance <= 0.0f) return 1.0f;
+
+ // Text::spacing() scales advances, so match the total offset using measured gaps.
+ auto scale = 1.0f + (letterSpacing * gaps + wordSpacing * spaces) / advance;
+ if (scale < 0.0f) scale = 0.0f;
+ text->spacing(scale, 1.0f);
+ return scale;
+}
+
+static void _updatePos(Text* text, const SvgTextNode& textNode, float anchor, float spacingScale, Point& textPos)
+{
+ auto advance = 0.0f;
+ if (auto utf8 = text->text()) {
+ GlyphMetrics gm;
+ while (utf8 && *utf8) {
+ if (text->metrics(utf8, gm, &utf8) != Result::Success) break;
+ advance += gm.advance;
+ }
+ }
+ // Text::spacing() scales every glyph advance, so scale the measured
+ // advance the same way to stay in sync with the rendered output.
+ textPos.x = textNode.x + textNode.dx + (1.0f - anchor) * advance * spacingScale;
+ textPos.y = textNode.y + textNode.dy;
+}
+
+static bool _hasPositionedTspan(const SvgNode* node, int depth)
+{
+ if (depth > 2192) {
+ TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
+ return true;
+ }
+ ARRAY_FOREACH(p, node->child)
+ {
+ if ((*p)->type != SvgNodeType::Tspan) continue;
+ auto& textNode = (*p)->node.text;
+ if (textNode.text) return true;
+ if (_hasPositionedTspan(*p, depth + 1)) return true;
+ }
+ return false;
+}
+
+static void _buildTspanScene(SvgParserContext& ctx, const SvgNode* node, Scene* scene, const Box& vBox, const string& svgPath, int depth, Point& textPos)
+{
+ if (depth > 2192) {
+ TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
+ return;
+ }
+ ARRAY_FOREACH(p, node->child)
+ {
+ auto child = *p;
+ if (child->type != SvgNodeType::Tspan) continue;
+
+ auto textNode = child->node.text;
+ if (textNode.text) {
+ auto xmlSpace = child->xmlSpace;
+ for (auto n = child->parent; n; n = n->parent) {
+ if (textNode.fontSize <= 0.0f) textNode.fontSize = n->node.text.fontSize;
+ if (!textNode.fontFamily) textNode.fontFamily = n->node.text.fontFamily;
+ if (xmlSpace == SvgXmlSpace::None) xmlSpace = n->xmlSpace;
+ if (n->type == SvgNodeType::Text) break;
+ }
+ if (xmlSpace == SvgXmlSpace::None) xmlSpace = SvgXmlSpace::Default;
+
+ if (textNode.x == FLT_MAX) textNode.x = textPos.x;
+ if (textNode.y == FLT_MAX) textNode.y = textPos.y;
+
+ auto text = _buildText(&textNode, xmlSpace, nullptr, _effectiveBaseline(child->style));
+ if (text) {
+ text->align(child->style->textAnchor, 0.0f);
+ auto spacingScale = _applySpacing(text, child->style->letterSpacing, child->style->wordSpacing);
+ _updatePos(text, textNode, child->style->textAnchor, spacingScale, textPos);
+ _applyTextFill(child->style, text, textNode, vBox, ctx.parser->global);
+ auto paint = _applyFilter(ctx, text, child, vBox, svgPath);
+ paint = _applyComposition(ctx, paint, child, vBox, svgPath);
+ paint = _applyBlend(paint, child);
+ scene->add(paint);
+ }
+ }
+ _buildTspanScene(ctx, child, scene, vBox, svgPath, depth + 1, textPos);
+ }
+}
+
+static Paint* _textBuildHelper(SvgParserContext& ctx, const SvgNode* node, const Box& vBox, const string& svgPath)
+{
+ auto textNode = &node->node.text;
+
+ // Handle xml:space
+ auto xmlSpace = node->xmlSpace;
+ for (auto n = node->parent; xmlSpace == SvgXmlSpace::None && n; n = n->parent)
+ xmlSpace = n->xmlSpace;
+ if (xmlSpace == SvgXmlSpace::None) xmlSpace = SvgXmlSpace::Default;
+
+ if (!_hasPositionedTspan(node, 0)) {
+ auto text = _buildText(textNode, xmlSpace, node->transform, _effectiveBaseline(node->style));
+ if (!text) return nullptr;
+ text->align(node->style->textAnchor, 0.0f);
+ _applySpacing(text, node->style->letterSpacing, node->style->wordSpacing);
+ _applyTextFill(node->style, text, *textNode, vBox, ctx.parser->global);
+ auto p = _applyFilter(ctx, text, node, vBox, svgPath);
+ p = _applyComposition(ctx, p, node, vBox, svgPath);
+ return _applyBlend(p, node);
+ }
+
+ auto scene = Scene::gen();
+ if (node->transform) scene->transform(*node->transform);
+
+ Point textPos = {textNode->x, textNode->y};
+
+ if (auto text = _buildText(textNode, xmlSpace, nullptr, _effectiveBaseline(node->style))) {
+ text->align(node->style->textAnchor, 0.0f);
+ auto spacingScale = _applySpacing(text, node->style->letterSpacing, node->style->wordSpacing);
+ _updatePos(text, *textNode, node->style->textAnchor, spacingScale, textPos);
+ _applyTextFill(node->style, text, *textNode, vBox, ctx.parser->global);
+ scene->add(text);
+ }
+
+ _buildTspanScene(ctx, node, scene, vBox, svgPath, 0, textPos);
+
+ auto p = _applyFilter(ctx, scene, node, vBox, svgPath);
+ p = _applyComposition(ctx, p, node, vBox, svgPath);
+ return _applyBlend(p, node);
+}
+
+static Scene* _sceneBuildHelper(SvgParserContext& ctx, const SvgNode* node, const Box& vBox, const string& svgPath, bool mask, int depth)
+{
+ /* Exception handling: Prevent invalid SVG data input.
+ The size is the arbitrary value, we need an experimental size. */
+ if (depth > 2192) {
+ TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
+ return nullptr;
+ }
+
+ if (!_isGroupType(node->type) && !mask) return nullptr;
+
+ auto scene = Scene::gen();
+ // For a Symbol node, the viewBox transformation has to be applied first - see _symbolTransform()
+ if (!mask && node->type != SvgNodeType::Symbol) {
+ if (node->type == SvgNodeType::Use) {
+ scene->transform(node->node.use.symbol ? _symbolTransform(node, vBox) : _useTransform(node));
+ } else if (node->transform) {
+ scene->transform(*node->transform);
+ }
+ }
+ if (!node->style->display || node->style->opacity == 0) return scene;
+
+ ARRAY_FOREACH(p, node->child) {
+ auto child = *p;
+ Paint* paint = nullptr;
+ if (child->type == SvgNodeType::ClipPath || child->type == SvgNodeType::Filter || child->type == SvgNodeType::Pattern) continue;
+ if (_isGroupType(child->type)) {
+ if (child->type == SvgNodeType::Use) paint = _useBuildHelper(ctx, child, vBox, svgPath, depth + 1);
+ else if (!(child->type == SvgNodeType::Symbol && node->type != SvgNodeType::Use)) paint = _sceneBuildHelper(ctx, child, vBox, svgPath, false, depth + 1);
+ } else {
+ if (child->type == SvgNodeType::Image) paint = _imageBuildHelper(ctx, child, vBox, svgPath);
+ else if (child->type == SvgNodeType::Text) paint = _textBuildHelper(ctx, child, vBox, svgPath);
+ else if (child->type != SvgNodeType::Mask) paint = _shapeBuildHelper(ctx, child, vBox, svgPath);
+ }
+ if (paint) {
+ // TODO: enable this only when accessible is enabled at thorvg v2 (for backward compat)
+ if (child->id) {
+ paint->id = djb2Encode(child->id);
+ if (ctx.accessible) ctx.access.push({paint->id, paint, tvg::duplicate(child->id)});
+ }
+ scene->add(paint);
+ }
+ }
+ scene->opacity(node->style->opacity);
+
+ return (Scene*)_applyBlend(_applyComposition(ctx, _applyFilter(ctx, scene, node, vBox, svgPath), node, vBox, svgPath), node);
+}
+
+static Paint* _buildPatternChild(SvgParserContext& ctx, SvgNode* child, const Box& vBox, const string& svgPath)
+{
+ if (child->type == SvgNodeType::ClipPath || child->type == SvgNodeType::Filter || child->type == SvgNodeType::Pattern) return nullptr;
+ if (_isGroupType(child->type)) {
+ if (child->type == SvgNodeType::Use) return _useBuildHelper(ctx, child, vBox, svgPath, 0);
+ if (child->type != SvgNodeType::Symbol) return _sceneBuildHelper(ctx, child, vBox, svgPath, false, 0);
+ return nullptr;
+ }
+ if (child->type == SvgNodeType::Image) return _imageBuildHelper(ctx, child, vBox, svgPath);
+ if (child->type == SvgNodeType::Text) return _textBuildHelper(ctx, child, vBox, svgPath);
+ if (child->type == SvgNodeType::Mask) return nullptr;
+ return _shapeBuildHelper(ctx, child, vBox, svgPath);
+}
+
+static Paint* _buildBaseTile(SvgParserContext& ctx, SvgNode* patternNode, const Box& vBox, const string& svgPath)
+{
+ Paint* paint = nullptr;
+ Scene* tileScene = nullptr;
+ ARRAY_FOREACH(p, patternNode->child) {
+ auto child = _buildPatternChild(ctx, *p, vBox, svgPath);
+ if (!child) continue;
+ if (!paint && !tileScene) {
+ paint = child;
+ continue;
+ }
+ if (!tileScene) {
+ tileScene = Scene::gen();
+ tileScene->add(paint);
+ paint = nullptr;
+ }
+ tileScene->add(child);
+ }
+ if (tileScene) return tileScene;
+ return paint;
+}
+
+static bool _patternCellRect(const SvgPatternNode& pat, const Box& bbox, Box& cell)
+{
+ if (pat.patternUserSpace) {
+ cell = pat.box;
+ } else {
+ cell.x = bbox.x + pat.box.x * bbox.w;
+ cell.y = bbox.y + pat.box.y * bbox.h;
+ cell.w = pat.box.w * bbox.w;
+ cell.h = pat.box.h * bbox.h;
+ }
+ return _validBox(cell);
+}
+
+static Matrix _patternContentTransform(const SvgPatternNode& pat, const Box& bbox, const Box& cell)
+{
+ if (pat.hasViewBox) {
+ auto sx = cell.w / pat.vbox.w;
+ auto sy = cell.h / pat.vbox.h;
+ return {sx, 0, -pat.vbox.x * sx, 0, sy, -pat.vbox.y * sy, 0, 0, 1};
+ }
+ if (!pat.contentUserSpace) return {bbox.w, 0, 0, 0, bbox.h, 0, 0, 0, 1};
+ return tvg::identity();
+}
+
+static Box _transformBounds(const Box& bounds, const Matrix& matrix)
+{
+ auto lt = Point{bounds.x, bounds.y} * matrix;
+ auto lb = Point{bounds.x, bounds.y + bounds.h} * matrix;
+ auto rt = Point{bounds.x + bounds.w, bounds.y} * matrix;
+ auto rb = Point{bounds.x + bounds.w, bounds.y + bounds.h} * matrix;
+
+ auto min = tvg::min(tvg::min(lt, lb), tvg::min(rt, rb));
+ auto max = tvg::max(tvg::max(lt, lb), tvg::max(rt, rb));
+
+ return {min.x, min.y, max.x - min.x, max.y - min.y};
+}
+
+static void _patternTileGrid(const Box& cell, const Box& bbox, const Matrix* transform, float& startX, float& startY, int& cols, int& rows)
+{
+ auto box = bbox;
+ Matrix inv;
+ if (transform && tvg::inverse(transform, &inv)) box = _transformBounds(bbox, inv);
+
+ startX = cell.x + floorf((box.x - cell.x) / cell.w) * cell.w;
+ startY = cell.y + floorf((box.y - cell.y) / cell.h) * cell.h;
+ cols = (int)ceilf((box.x + box.w - startX) / cell.w);
+ rows = (int)ceilf((box.y + box.h - startY) / cell.h);
+}
+
+static Paint* _applyPatternProperty(SvgParserContext& ctx, Shape* vg, SvgNode* node, SvgNode* patternNode, const Box& vBox, const string& svgPath)
+{
+ if (!patternNode || patternNode->child.empty()) return nullptr;
+ auto& pat = patternNode->node.pattern;
+
+ if (pat.applying) {
+ TVGLOG("SVG", "Circular pattern reference detected; skipped.");
+ return nullptr;
+ }
+
+ auto bbox = _bounds(vg);
+ if (!_validBox(bbox)) return nullptr;
+
+ Box cell;
+ if (!_patternCellRect(pat, bbox, cell)) return nullptr;
+
+ float startX, startY;
+ int cols, rows;
+ _patternTileGrid(cell, bbox, pat.transform, startX, startY, cols, rows);
+
+ auto contentTransform = _patternContentTransform(pat, bbox, cell);
+
+ pat.applying = true;
+
+ auto base = _buildBaseTile(ctx, patternNode, vBox, svgPath);
+ auto tilesScene = Scene::gen();
+ if (base) {
+ for (int r = 0; r < rows; ++r) {
+ for (int c = 0; c < cols; ++c) {
+ auto copy = base->duplicate();
+ if (!copy) continue;
+ Matrix tileTransform = Matrix{1, 0, startX + c * cell.w, 0, 1, startY + r * cell.h, 0, 0, 1} * contentTransform;
+ if (pat.transform) tileTransform = *pat.transform * tileTransform;
+ copy->transform(tileTransform * copy->transform());
+ tilesScene->add(copy);
+ }
+ }
+ Paint::rel(base);
+ }
+
+ auto clipper = Shape::gen();
+ if (!_recognizeShape(node, clipper)) {
+ pat.applying = false;
+ Paint::rel(tilesScene);
+ Paint::rel(clipper);
+ return nullptr;
+ }
+ tilesScene->clip(clipper);
+
+ pat.applying = false;
+ return tilesScene;
+}
+
+static void _updateInvalidViewSize(Scene* scene, Box& vBox, float& w, float& h, SvgViewFlag viewFlag)
+{
+ auto useW = (viewFlag & SvgViewFlag::Width);
+ auto useH = (viewFlag & SvgViewFlag::Height);
+ auto bbox = _bounds(scene);
+
+ if (!useW && !useH) {
+ vBox = bbox;
+ } else {
+ vBox.w = useW ? w : bbox.w;
+ vBox.h = useH ? h : bbox.h;
+ }
+
+ //the size would have 1x1 or percentage values.
+ if (!useW) w *= vBox.w;
+ if (!useH) h *= vBox.h;
+}
+
+
+static void _loadFonts(Array<FontFace>& fonts)
+{
+ if (fonts.empty()) return;
+
+ constexpr size_t MAX_SCAN = 40;
+ constexpr size_t KEY_LEN = 10; // "ttf;base64" / "otf;base64"
+
+ ARRAY_FOREACH(p, fonts) {
+ if (!p->name) continue;
+
+ size_t shift = 0;
+ const char* type = nullptr;
+ auto limit = (p->srcLen < MAX_SCAN) ? p->srcLen : MAX_SCAN;
+
+ for (size_t i = 0; i + KEY_LEN <= limit; ++i) {
+ if (!memcmp(p->src + i, "ttf;base64", KEY_LEN)) {
+ shift = i + KEY_LEN + 1; // skip ","
+ type = "ttf";
+ break;
+ }
+ if (!memcmp(p->src + i, "otf;base64", KEY_LEN)) {
+ shift = i + KEY_LEN + 1;
+ type = "otf";
+ break;
+ }
+ }
+ if (type) {
+ auto size = b64Decode(p->src + shift, p->srcLen - shift, &p->decoded);
+ Text::load(p->name, p->decoded, size, type);
+ }
+ }
+}
+
+static bool _hasUserSpaceGradients(SvgParserContext& ctx)
+{
+ ARRAY_FOREACH(p, ctx.gradients) {
+ if ((*p)->userSpace) return true;
+ }
+ if (ctx.def) {
+ ARRAY_FOREACH(p, ctx.def->node.defs.gradients) {
+ if ((*p)->userSpace) return true;
+ }
+ }
+ return false;
+}
+
+
+/************************************************************************/
+/* External Class Implementation */
+/************************************************************************/
+
+Scene* svgSceneBuild(SvgParserContext& ctx, Box vBox, float w, float h, AspectRatioAlign align, AspectRatioMeetOrSlice meetOrSlice, const string& svgPath, SvgViewFlag viewFlag)
+{
+ //TODO: aspect ratio is valid only if viewBox was set
+
+ if (!ctx.doc || (ctx.doc->type != SvgNodeType::Doc)) return nullptr;
+
+ _loadFonts(ctx.fonts);
+
+ auto docNode = _sceneBuildHelper(ctx, ctx.doc, vBox, svgPath, false, 0);
+
+ if (!(viewFlag & SvgViewFlag::Viewbox)) {
+ auto prevW = vBox.w, prevH = vBox.h;
+ _updateInvalidViewSize(docNode, vBox, w, h, viewFlag);
+ if ((!tvg::equal(vBox.w, prevW) || !tvg::equal(vBox.h, prevH)) && _hasUserSpaceGradients(ctx)) {
+ Paint::rel(docNode);
+ ARRAY_FOREACH(p, ctx.images) tvg::free(*p);
+ ctx.images.clear();
+ docNode = _sceneBuildHelper(ctx, ctx.doc, vBox, svgPath, false, 0);
+ }
+ }
+
+ if (!tvg::equal(w, vBox.w) || !tvg::equal(h, vBox.h)) {
+ Matrix m = _calculateAspectRatioMatrix(align, meetOrSlice, w, h, vBox);
+ docNode->transform(m);
+ } else if (!tvg::zero(vBox.x) || !tvg::zero(vBox.y)) {
+ docNode->translate(-vBox.x, -vBox.y);
+ }
+
+ auto viewBoxClip = Shape::gen();
+ viewBoxClip->appendRect(0, 0, w, h);
+
+ auto clippingLayer = Scene::gen();
+ clippingLayer->clip(viewBoxClip);
+ clippingLayer->add(docNode);
+
+ ctx.doc->node.doc.vbox = vBox;
+ ctx.doc->node.doc.w = w;
+ ctx.doc->node.doc.h = h;
+
+ auto root = Scene::gen();
+ root->add(clippingLayer);
+
+ return root;
+}
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgSceneBuilder.h b/thirdparty/thorvg/src/loaders/svg/tvgSvgBuilder.h
similarity index 87%
rename from thirdparty/thorvg/src/loaders/svg/tvgSvgSceneBuilder.h
rename to thirdparty/thorvg/src/loaders/svg/tvgSvgBuilder.h
index 17d08a14c1f..2ad8dc3c1dd 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgSceneBuilder.h
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgBuilder.h
@@ -25,6 +25,6 @@
#include "tvgCommon.h"
-Scene* svgSceneBuild(SvgLoaderData& loaderData, Box vBox, float w, float h, AspectRatioAlign align, AspectRatioMeetOrSlice meetOrSlice, const string& svgPath, SvgViewFlag viewFlag);
+Scene* svgSceneBuild(SvgParserContext& ctx, Box vBox, float w, float h, AspectRatioAlign align, AspectRatioMeetOrSlice meetOrSlice, const string& svgPath, SvgViewFlag viewFlag);
#endif //_TVG_SVG_SCENE_BUILDER_H_
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgLoaderCommon.h b/thirdparty/thorvg/src/loaders/svg/tvgSvgCommon.h
similarity index 80%
rename from thirdparty/thorvg/src/loaders/svg/tvgSvgLoaderCommon.h
rename to thirdparty/thorvg/src/loaders/svg/tvgSvgCommon.h
index 4ecddde7b12..2f254f37423 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgLoaderCommon.h
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgCommon.h
@@ -27,8 +27,7 @@
#include "tvgArray.h"
#include "tvgInlist.h"
#include "tvgColor.h"
-
-using SvgColor = tvg::RGB;
+#include "tvgAccessor.h"
#define STR_AS(A, B) !strcmp((A), (B))
@@ -57,7 +56,7 @@ struct SvgNode;
struct SvgStyleGradient;
//NOTE: Please update simpleXmlNodeTypeToString() as well.
-enum class SvgNodeType
+enum struct SvgNodeType : uint16_t
{
Doc,
G,
@@ -83,25 +82,13 @@ enum class SvgNodeType
Symbol,
Filter,
GaussianBlur,
+ Pattern,
Unknown
};
-/*
-// TODO - remove?
-enum class SvgLengthType
-{
- Percent,
- Px,
- Pc,
- Pt,
- Mm,
- Cm,
- In,
-};
-*/
-
-enum class SvgFillFlags
+enum struct SvgFillFlags : uint8_t
{
+ None = 0x0,
Paint = 0x01,
Opacity = 0x02,
Gradient = 0x04,
@@ -124,7 +111,7 @@ constexpr void operator|=(SvgFillFlags& a, const SvgFillFlags b)
a = SvgFillFlags(int(a) | int(b));
}
-enum class SvgStrokeFlags
+enum struct SvgStrokeFlags : uint16_t
{
Paint = 0x1,
Opacity = 0x2,
@@ -153,14 +140,15 @@ constexpr void operator|=(SvgStrokeFlags& a, const SvgStrokeFlags b)
a = SvgStrokeFlags(int(a) | int(b));
}
-enum class SvgGradientType
+enum struct SvgGradientType : uint8_t
{
Linear,
Radial
};
-enum class SvgStyleFlags
+enum struct SvgStyleFlags
{
+ None = 0x0,
Color = 0x01,
Fill = 0x02,
FillRule = 0x04,
@@ -180,7 +168,14 @@ enum class SvgStyleFlags
PaintOrder = 0x10000,
StrokeMiterlimit = 0x20000,
StrokeDashOffset = 0x40000,
- Filter = 0x80000
+ Filter = 0x80000,
+ BlendMode = 0x100000,
+ TextAnchor = 0x200000,
+ AlignmentBaseline = 0x400000,
+ DominantBaseline = 0x800000,
+ FontWeight = 0x1000000,
+ LetterSpacing = 0x2000000,
+ WordSpacing = 0x4000000
};
constexpr bool operator&(SvgStyleFlags a, SvgStyleFlags b)
@@ -198,7 +193,7 @@ constexpr void operator|=(SvgStyleFlags& a, const SvgStyleFlags b)
a = SvgStyleFlags(int(a) | int(b));
}
-enum class SvgStopStyleFlags
+enum struct SvgStopStyleFlags : uint8_t
{
StopDefault = 0x0,
StopOpacity = 0x01,
@@ -215,7 +210,7 @@ constexpr SvgStopStyleFlags operator|(SvgStopStyleFlags a, SvgStopStyleFlags b)
return SvgStopStyleFlags(int(a) | int(b));
}
-enum class SvgGradientFlags
+enum struct SvgGradientFlags : uint16_t
{
None = 0x0,
GradientUnits = 0x1,
@@ -242,13 +237,13 @@ constexpr SvgGradientFlags operator |(SvgGradientFlags a, SvgGradientFlags b)
return SvgGradientFlags(int(a) | int(b));
}
-enum class SvgMaskType
+enum struct SvgMaskType : uint8_t
{
Luminance = 0,
Alpha
};
-enum class SvgXmlSpace
+enum struct SvgXmlSpace : uint8_t
{
None,
Default,
@@ -256,21 +251,21 @@ enum class SvgXmlSpace
};
//Length type to recalculate %, pt, pc, mm, cm etc
-enum class SvgParserLengthType
+enum struct SvgParserLengthType : uint8_t
{
Vertical,
Horizontal,
Diagonal,
- //In case of, for example, radius of radial gradient
+ // In case of, for example, radius of radial gradient
Other
};
-enum class SvgViewFlag
+enum struct SvgViewFlag : uint8_t
{
None = 0x0,
- Width = 0x01, //viewPort width
- Height = 0x02, //viewPort height
- Viewbox = 0x04, //viewBox x,y,w,h - used only if all 4 are correctly set
+ Width = 0x01, // viewPort width
+ Height = 0x02, // viewPort height
+ Viewbox = 0x04, // viewBox x,y,w,h - used only if all 4 are correctly set
WidthInPercent = 0x08,
HeightInPercent = 0x10
};
@@ -290,7 +285,7 @@ constexpr SvgViewFlag operator ^(SvgViewFlag a, SvgViewFlag b)
return SvgViewFlag(int(a) ^ int(b));
}
-enum class AspectRatioAlign
+enum struct AspectRatioAlign : uint16_t
{
None,
XMinYMin,
@@ -304,7 +299,7 @@ enum class AspectRatioAlign
XMaxYMax
};
-enum class AspectRatioMeetOrSlice
+enum struct AspectRatioMeetOrSlice : uint8_t
{
Meet,
Slice
@@ -314,11 +309,11 @@ struct SvgDocNode
{
float w, h; //unit: point or in percentage see: SvgViewFlag
Box vbox;
- SvgViewFlag viewFlag;
SvgNode* defs;
SvgNode* style;
AspectRatioAlign align;
AspectRatioMeetOrSlice meetOrSlice;
+ SvgViewFlag viewFlag;
};
struct SvgGNode
@@ -345,9 +340,9 @@ struct SvgSymbolNode
struct SvgUseNode
{
float x, y, w, h;
+ SvgNode* symbol;
bool isWidthSet;
bool isHeightSet;
- SvgNode* symbol;
};
struct SvgEllipseNode
@@ -394,8 +389,11 @@ struct SvgClipNode
struct SvgMaskNode
{
+ Box box;
+ bool isPercentage[4];
SvgMaskType type;
bool userSpace;
+ bool maskContentUserSpace;
};
struct SvgCssStyleNode
@@ -407,6 +405,7 @@ struct SvgTextNode
char* text;
char* fontFamily;
float x, y;
+ float dx, dy;
float fontSize;
};
@@ -427,6 +426,18 @@ struct SvgFilterNode
bool primitiveUserSpace;
};
+struct SvgPatternNode
+{
+ Box box;
+ Box vbox;
+ Matrix* transform;
+ bool isPercentage[4];
+ bool patternUserSpace;
+ bool contentUserSpace;
+ bool hasViewBox;
+ bool applying;
+};
+
struct SvgLinearGradient
{
float x1, y1, x2, y2;
@@ -457,8 +468,9 @@ struct SvgComposite
struct SvgPaint
{
SvgStyleGradient* gradient;
+ SvgNode* pattern;
char *url;
- SvgColor color;
+ tvg::RGBA color;
bool none;
bool curColor;
};
@@ -471,23 +483,23 @@ struct SvgDash
struct SvgStyleGradient
{
- SvgGradientType type;
char* id;
char* ref;
- FillSpread spread;
- SvgRadialGradient* radial;
- SvgLinearGradient* linear;
+ union {
+ SvgRadialGradient radial;
+ SvgLinearGradient linear;
+ };
Matrix* transform;
Array<Fill::ColorStop> stops;
SvgGradientFlags flags;
+ SvgGradientType type;
+ FillSpread spread;
bool userSpace;
void clear()
{
stops.reset();
tvg::free(transform);
- tvg::free(radial);
- tvg::free(linear);
tvg::free(ref);
tvg::free(id);
}
@@ -495,9 +507,9 @@ struct SvgStyleGradient
struct SvgStyleFill
{
- SvgFillFlags flags;
SvgPaint paint;
int opacity;
+ SvgFillFlags flags;
FillRule fillRule;
};
@@ -509,10 +521,10 @@ struct SvgStyleStroke
float scale;
float width;
float centered;
- StrokeCap cap;
- StrokeJoin join;
float miterlimit;
SvgDash dash;
+ StrokeCap cap;
+ StrokeJoin join;
};
struct SvgFilter
@@ -521,6 +533,35 @@ struct SvgFilter
SvgNode* node;
};
+enum class SvgBaseline : uint8_t
+{
+ Auto = 0,
+ Alphabetic,
+ BeforeEdge,
+ AfterEdge,
+ Central,
+ Middle,
+ Hanging,
+ Mathematical
+};
+
+enum class SvgFontWeight : int16_t
+{
+ Invalid = 0,
+ Inherit = -1,
+ Bolder = -2,
+ Lighter = -3,
+ Weight100 = 100,
+ Weight200 = 200,
+ Weight300 = 300,
+ Normal = 400,
+ Weight500 = 500,
+ Weight600 = 600,
+ Bold = 700,
+ Weight800 = 800,
+ Weight900 = 900
+};
+
struct SvgStyleProperty
{
SvgStyleFill fill;
@@ -529,13 +570,22 @@ struct SvgStyleProperty
SvgComposite mask;
SvgFilter filter;
int opacity;
- SvgColor color;
+ tvg::RGBA color;
char* cssClass;
+ float textAnchor; // 0=start, 0.5=middle, 1=end
+ SvgBaseline alignmentBaseline;
+ SvgBaseline dominantBaseline;
+ SvgFontWeight fontWeight;
+ float letterSpacing;
+ float wordSpacing;
SvgStyleFlags flags;
SvgStyleFlags flagsImportance; //indicates the importance of the flag - if set, higher priority is applied (https://drafts.csswg.org/css-cascade-4/#importance)
bool curColorSet;
bool paintOrder; //true if default (fill, stroke), false otherwise
bool display;
+ bool letterSpacingRelative;
+ bool wordSpacingRelative;
+ BlendMethod blendMode;
};
struct SvgNode
@@ -566,6 +616,7 @@ struct SvgNode
SvgTextNode text;
SvgFilterNode filter;
SvgGaussianBlurNode gaussianBlur;
+ SvgPatternNode pattern;
} node;
SvgXmlSpace xmlSpace = SvgXmlSpace::None;
~SvgNode();
@@ -575,9 +626,9 @@ struct SvgParser
{
SvgNode* node;
SvgStyleGradient* styleGrad;
+ Box global;
Fill::ColorStop gradStop;
SvgStopStyleFlags flags;
- Box global;
struct
{
bool parsedFx;
@@ -601,30 +652,36 @@ struct FontFace
char* decoded = nullptr;
};
-enum class OpenedTagType : uint8_t
+enum struct OpenedTagType : uint8_t
{
Other = 0,
Style,
Text
};
-struct SvgLoaderData
+struct SvgParserContext
{
- Array<SvgNode*> stack;
+ SvgParser* parser = nullptr;
SvgNode* doc = nullptr;
SvgNode* def = nullptr; //also used to store nested graphic nodes
SvgNode* cssStyle = nullptr;
+ SvgNode* currentGraphicsNode = nullptr;
+ Inlist<SvgNodeIdPair> cloneNodes;
+ Array<SvgNode*> stack;
Array<SvgStyleGradient*> gradients;
Array<SvgStyleGradient*> gradientStack; //For stops
- SvgParser* svgParse = nullptr;
- Inlist<SvgNodeIdPair> cloneNodes;
Array<SvgNodeIdPair> nodesToStyle;
Array<char*> images; //embedded images
Array<FontFace> fonts;
- int level = 0;
- bool result = false;
+
+ // TODO: We can remove map and directly use the name instead of id in ThorVG v2
+ // TODO: Maybe we can replace this with std::map. Currently, ArrayList seems fast enough.
+ Array<AccessorEntity> access;
+
OpenedTagType openedTag = OpenedTagType::Other;
- SvgNode* currentGraphicsNode = nullptr;
+ bool accessible; // allow the Accessor to retain the SVG node names
+
+ void clear(bool all);
};
#endif
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.cpp b/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.cpp
index 17eccc4ae52..99340128d87 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.cpp
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.cpp
@@ -139,6 +139,44 @@ static void _copyStyle(SvgStyleProperty* to, const SvgStyleProperty* from, bool
to->flags |= SvgStyleFlags::Opacity;
if (from->flagsImportance & SvgStyleFlags::Opacity) to->flagsImportance |= SvgStyleFlags::Opacity;
}
+ if (((from->flags & SvgStyleFlags::BlendMode) && (overwrite || !(to->flags & SvgStyleFlags::BlendMode))) ||
+ _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::BlendMode)) {
+ to->blendMode = from->blendMode;
+ to->flags |= SvgStyleFlags::BlendMode;
+ if (from->flagsImportance & SvgStyleFlags::BlendMode) to->flagsImportance |= SvgStyleFlags::BlendMode;
+ }
+ if (((from->flags & SvgStyleFlags::TextAnchor) && (overwrite || !(to->flags & SvgStyleFlags::TextAnchor))) || _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::TextAnchor)) {
+ to->textAnchor = from->textAnchor;
+ to->flags |= SvgStyleFlags::TextAnchor;
+ if (from->flagsImportance & SvgStyleFlags::TextAnchor) to->flagsImportance |= SvgStyleFlags::TextAnchor;
+ }
+ if (((from->flags & SvgStyleFlags::AlignmentBaseline) && (overwrite || !(to->flags & SvgStyleFlags::AlignmentBaseline))) || _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::AlignmentBaseline)) {
+ to->alignmentBaseline = from->alignmentBaseline;
+ to->flags |= SvgStyleFlags::AlignmentBaseline;
+ if (from->flagsImportance & SvgStyleFlags::AlignmentBaseline) to->flagsImportance |= SvgStyleFlags::AlignmentBaseline;
+ }
+ if (((from->flags & SvgStyleFlags::DominantBaseline) && (overwrite || !(to->flags & SvgStyleFlags::DominantBaseline))) || _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::DominantBaseline)) {
+ to->dominantBaseline = from->dominantBaseline;
+ to->flags |= SvgStyleFlags::DominantBaseline;
+ if (from->flagsImportance & SvgStyleFlags::DominantBaseline) to->flagsImportance |= SvgStyleFlags::DominantBaseline;
+ }
+ if (((from->flags & SvgStyleFlags::FontWeight) && (overwrite || !(to->flags & SvgStyleFlags::FontWeight))) || _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::FontWeight)) {
+ to->fontWeight = from->fontWeight;
+ to->flags |= SvgStyleFlags::FontWeight;
+ if (from->flagsImportance & SvgStyleFlags::FontWeight) to->flagsImportance |= SvgStyleFlags::FontWeight;
+ }
+ if (((from->flags & SvgStyleFlags::LetterSpacing) && (overwrite || !(to->flags & SvgStyleFlags::LetterSpacing))) || _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::LetterSpacing)) {
+ to->letterSpacing = from->letterSpacing;
+ to->letterSpacingRelative = from->letterSpacingRelative;
+ to->flags |= SvgStyleFlags::LetterSpacing;
+ if (from->flagsImportance & SvgStyleFlags::LetterSpacing) to->flagsImportance |= SvgStyleFlags::LetterSpacing;
+ }
+ if (((from->flags & SvgStyleFlags::WordSpacing) && (overwrite || !(to->flags & SvgStyleFlags::WordSpacing))) || _isImportanceApplicable(to->flagsImportance, from->flagsImportance, SvgStyleFlags::WordSpacing)) {
+ to->wordSpacing = from->wordSpacing;
+ to->wordSpacingRelative = from->wordSpacingRelative;
+ to->flags |= SvgStyleFlags::WordSpacing;
+ if (from->flagsImportance & SvgStyleFlags::WordSpacing) to->flagsImportance |= SvgStyleFlags::WordSpacing;
+ }
}
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.h b/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.h
index e0cbf27f1eb..5dc9b052075 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.h
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgCssStyle.h
@@ -23,7 +23,7 @@
#ifndef _TVG_SVG_CSS_STYLE_H_
#define _TVG_SVG_CSS_STYLE_H_
-#include "tvgSvgLoaderCommon.h"
+#include "tvgSvgCommon.h"
SvgNode* cssFindStyleNode(const SvgNode* style, const char* title, SvgNodeType type);
SvgNode* cssFindStyleNode(const SvgNode* style, const char* title);
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.cpp b/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.cpp
index 5e70c33a684..26bd05d3da3 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.cpp
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.cpp
@@ -26,7 +26,7 @@
#include "tvgLoader.h"
#include "tvgXmlParser.h"
#include "tvgSvgLoader.h"
-#include "tvgSvgSceneBuilder.h"
+#include "tvgSvgBuilder.h"
#include "tvgSvgCssStyle.h"
#include "tvgSvgUtil.h"
@@ -43,13 +43,27 @@
#define PX_PER_PT 1.333333f //1 pt = 1/72 in -> PX_PER_IN/72
#define PX_PER_MM 3.779528f //1 in = 25.4 mm -> PX_PER_IN/25.4
#define PX_PER_CM 37.79528f //1 in = 2.54 cm -> PX_PER_IN/2.54
+// TODO: support the def font and size as used in a system?
+#define DEFAULT_FONT_SIZE 10.0f
typedef bool (*parseAttributes)(const char* buf, unsigned bufLength, xmlAttributeCb func, const void* data);
-typedef SvgNode* (*FactoryMethod)(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func);
-typedef SvgStyleGradient* (*GradientFactoryMethod)(SvgLoaderData* loader, const char* buf, unsigned bufLength);
+typedef SvgNode* (*FactoryMethod)(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func);
+typedef SvgStyleGradient* (*GradientFactoryMethod)(SvgParserContext* ctx, const char* buf, unsigned bufLength);
static bool _parseStyleAttr(void* data, const char* key, const char* value);
static bool _parseStyleAttr(void* data, const char* key, const char* value, bool style);
+static constexpr struct {
+ const char* tag;
+ SvgParserLengthType type;
+ int sz;
+ size_t offset;
+} boxTags[] = {
+ {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(Box, x)},
+ {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(Box, y)},
+ {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(Box, w)},
+ {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(Box, h)}
+};
+
static void _copyId(char** to, const char* from)
{
tvg::free(*to);
@@ -120,54 +134,71 @@ static void _parseAspectRatio(const char** content, AspectRatioAlign* align, Asp
}
}
+static float _findEmBaseFontSize(const SvgNode* from)
+{
+ for (auto n = from; n; n = n->parent) {
+ if ((n->type == SvgNodeType::Text || n->type == SvgNodeType::Tspan) && n->node.text.fontSize > 0.0f) return n->node.text.fontSize;
+ }
+ return DEFAULT_FONT_SIZE;
+}
+
+static float _unitScale(const char* str, float emBase)
+{
+ if (strstr(str, "em")) return emBase;
+ if (strstr(str, "ex")) return emBase * 0.5f;
+ if (strstr(str, "cm")) return PX_PER_CM;
+ if (strstr(str, "mm")) return PX_PER_MM;
+ if (strstr(str, "pt")) return PX_PER_PT;
+ if (strstr(str, "pc")) return PX_PER_PC;
+ if (strstr(str, "in")) return PX_PER_IN;
+ return 1.0f;
+}
+
+static bool _isPercentage(const char* end)
+{
+ end = svgUtilSkipWhiteSpace(end, nullptr);
+ return *end == '%';
+}
// According to https://www.w3.org/TR/SVG/coords.html#Units
-static float _toFloat(const SvgParser* svgParse, const char* str, SvgParserLengthType type)
+static float _toFloat(const SvgParser* parser, const char* str, SvgParserLengthType type)
{
- float parsedValue = toFloat(str, nullptr);
+ char* end = nullptr;
+ auto parsedValue = toFloat(str, &end);
- if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
- else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
- else if (strstr(str, "pt")) parsedValue *= PX_PER_PT;
- else if (strstr(str, "pc")) parsedValue *= PX_PER_PC;
- else if (strstr(str, "in")) parsedValue *= PX_PER_IN;
- else if (strstr(str, "%")) {
- if (type == SvgParserLengthType::Vertical) parsedValue = (parsedValue / 100.0f) * svgParse->global.h;
- else if (type == SvgParserLengthType::Horizontal) parsedValue = (parsedValue / 100.0f) * svgParse->global.w;
- else if (type == SvgParserLengthType::Diagonal) parsedValue = (sqrtf(powf(svgParse->global.w, 2) + powf(svgParse->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
- else //if other than it's radius
- {
- float max = svgParse->global.w;
- if (max < svgParse->global.h)
- max = svgParse->global.h;
- parsedValue = (parsedValue / 100.0f) * max;
- }
+ if (_isPercentage(end)) {
+ if (type == SvgParserLengthType::Vertical) return (parsedValue / 100.0f) * parser->global.h;
+ if (type == SvgParserLengthType::Horizontal) return (parsedValue / 100.0f) * parser->global.w;
+ if (type == SvgParserLengthType::Diagonal) return (sqrtf(powf(parser->global.w, 2) + powf(parser->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
+ auto max = parser->global.w;
+ if (max < parser->global.h) max = parser->global.h;
+ return (parsedValue / 100.0f) * max;
}
- //TODO: Implement 'em', 'ex' attributes
-
- return parsedValue;
+ return parsedValue * _unitScale(str, _findEmBaseFontSize(parser ? parser->node : nullptr));
}
-
-static float _gradientToFloat(const SvgParser* svgParse, const char* str, bool& isPercentage)
+static float _toFontSize(const SvgParser* parser, const char* str)
{
char* end = nullptr;
+ auto parsedValue = toFloat(str, &end);
+ if (parsedValue < 0.0f) parsedValue = 0.0f;
+
+ auto base = _findEmBaseFontSize(parser && parser->node ? parser->node->parent : nullptr);
+ if (_isPercentage(end)) return (parsedValue / 100.0f) * base;
+ return parsedValue * _unitScale(str, base);
+}
+static float _gradientToFloat(const SvgParser* parser, const char* str, bool& isPercentage)
+{
+ char* end = nullptr;
auto parsedValue = toFloat(str, &end);
- isPercentage = false;
- if (strstr(str, "%")) {
- parsedValue = parsedValue / 100.0f;
+ if (_isPercentage(end)) {
isPercentage = true;
+ return parsedValue / 100.0f;
}
- else if (strstr(str, "cm")) parsedValue *= PX_PER_CM;
- else if (strstr(str, "mm")) parsedValue *= PX_PER_MM;
- else if (strstr(str, "pt")) parsedValue *= PX_PER_PT;
- else if (strstr(str, "pc")) parsedValue *= PX_PER_PC;
- else if (strstr(str, "in")) parsedValue *= PX_PER_IN;
- //TODO: Implement 'em', 'ex' attributes
-
- return parsedValue;
+ isPercentage = false;
+ return parsedValue * _unitScale(str, _findEmBaseFontSize(parser ? parser->node : nullptr));
}
@@ -202,6 +233,32 @@ static int _toOpacity(const char* str)
return 255;
}
+static SvgFontWeight _toFontWeight(const char* str)
+{
+ if (STR_AS(str, "normal")) return SvgFontWeight::Normal;
+ if (STR_AS(str, "bold")) return SvgFontWeight::Bold;
+ if (STR_AS(str, "inherit")) return SvgFontWeight::Inherit;
+ if (STR_AS(str, "bolder")) return SvgFontWeight::Bolder;
+ if (STR_AS(str, "lighter")) return SvgFontWeight::Lighter;
+
+ char* end = nullptr;
+ auto weight = strtol(str, &end, 10);
+ end = (char*)svgUtilSkipWhiteSpace(end, nullptr);
+ if (*end) return SvgFontWeight::Invalid;
+
+ switch (weight) {
+ case 100: return SvgFontWeight::Weight100;
+ case 200: return SvgFontWeight::Weight200;
+ case 300: return SvgFontWeight::Weight300;
+ case 400: return SvgFontWeight::Normal;
+ case 500: return SvgFontWeight::Weight500;
+ case 600: return SvgFontWeight::Weight600;
+ case 700: return SvgFontWeight::Bold;
+ case 800: return SvgFontWeight::Weight800;
+ case 900: return SvgFontWeight::Weight900;
+ default: return SvgFontWeight::Invalid;
+ }
+}
static SvgMaskType _toMaskType(const char* str)
{
@@ -306,14 +363,43 @@ static constexpr struct
_PARSE_TAG(FillRule, fillRule, FillRule, fillRuleTags, FillRule::NonZero)
+/* parse the blend mode applied to an element.
+ * https://www.w3.org/TR/compositing-1/#mix-blend-mode
+ */
+static constexpr struct
+{
+ BlendMethod blendMode;
+ const char* tag;
+} blendModeTags[] = {
+ { BlendMethod::Multiply, "multiply" },
+ { BlendMethod::Screen, "screen" },
+ { BlendMethod::Overlay, "overlay" },
+ { BlendMethod::Darken, "darken" },
+ { BlendMethod::Lighten, "lighten" },
+ { BlendMethod::ColorDodge, "color-dodge" },
+ { BlendMethod::ColorBurn, "color-burn" },
+ { BlendMethod::HardLight, "hard-light" },
+ { BlendMethod::SoftLight, "soft-light" },
+ { BlendMethod::Difference, "difference" },
+ { BlendMethod::Exclusion, "exclusion" },
+ { BlendMethod::Hue, "hue" },
+ { BlendMethod::Saturation, "saturation" },
+ { BlendMethod::Color, "color" },
+ { BlendMethod::Luminosity, "luminosity" }
+};
+
+
+_PARSE_TAG(BlendMethod, blendMode, BlendMode, blendModeTags, BlendMethod::Normal)
+
+
/* parse the dash pattern used during stroking a path.
* Value: none | <dasharray> | inherit
* Initial: none
* https://www.w3.org/TR/SVG/painting.html
*/
-static void _parseDashArray(SvgLoaderData* loader, const char *str, SvgDash* dash)
+static bool _parseDashArray(SvgParserContext* ctx, const char* str, SvgDash* dash)
{
- if (!strncmp(str, "none", 4)) return;
+ if (STR_AS(str, "none")) return true;
char *end = nullptr;
@@ -323,17 +409,18 @@ static void _parseDashArray(SvgLoaderData* loader, const char *str, SvgDash* das
if (str == end) break;
if (parsedValue < 0.0f) {
dash->array.reset();
- return;
+ return false;
}
if (*end == '%') {
++end;
//Refers to the diagonal length of the viewport.
//https://www.w3.org/TR/SVG2/coords.html#Units
- parsedValue = (sqrtf(powf(loader->svgParse->global.w, 2) + powf(loader->svgParse->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
+ parsedValue = (sqrtf(powf(ctx->parser->global.w, 2) + powf(ctx->parser->global.h, 2)) / sqrtf(2.0f)) * (parsedValue / 100.0f);
}
dash->array.push(parsedValue);
str = end;
}
+ return !dash->array.empty();
}
@@ -401,209 +488,226 @@ static unsigned char _parseColor(const char* value, char** end)
}
+// sorted by name
static constexpr struct
{
const char* name;
- unsigned int value;
+ tvg::RGB value;
} colors[] = {
- { "aliceblue", 0xfff0f8ff },
- { "antiquewhite", 0xfffaebd7 },
- { "aqua", 0xff00ffff },
- { "aquamarine", 0xff7fffd4 },
- { "azure", 0xfff0ffff },
- { "beige", 0xfff5f5dc },
- { "bisque", 0xffffe4c4 },
- { "black", 0xff000000 },
- { "blanchedalmond", 0xffffebcd },
- { "blue", 0xff0000ff },
- { "blueviolet", 0xff8a2be2 },
- { "brown", 0xffa52a2a },
- { "burlywood", 0xffdeb887 },
- { "cadetblue", 0xff5f9ea0 },
- { "chartreuse", 0xff7fff00 },
- { "chocolate", 0xffd2691e },
- { "coral", 0xffff7f50 },
- { "cornflowerblue", 0xff6495ed },
- { "cornsilk", 0xfffff8dc },
- { "crimson", 0xffdc143c },
- { "cyan", 0xff00ffff },
- { "darkblue", 0xff00008b },
- { "darkcyan", 0xff008b8b },
- { "darkgoldenrod", 0xffb8860b },
- { "darkgray", 0xffa9a9a9 },
- { "darkgrey", 0xffa9a9a9 },
- { "darkgreen", 0xff006400 },
- { "darkkhaki", 0xffbdb76b },
- { "darkmagenta", 0xff8b008b },
- { "darkolivegreen", 0xff556b2f },
- { "darkorange", 0xffff8c00 },
- { "darkorchid", 0xff9932cc },
- { "darkred", 0xff8b0000 },
- { "darksalmon", 0xffe9967a },
- { "darkseagreen", 0xff8fbc8f },
- { "darkslateblue", 0xff483d8b },
- { "darkslategray", 0xff2f4f4f },
- { "darkslategrey", 0xff2f4f4f },
- { "darkturquoise", 0xff00ced1 },
- { "darkviolet", 0xff9400d3 },
- { "deeppink", 0xffff1493 },
- { "deepskyblue", 0xff00bfff },
- { "dimgray", 0xff696969 },
- { "dimgrey", 0xff696969 },
- { "dodgerblue", 0xff1e90ff },
- { "firebrick", 0xffb22222 },
- { "floralwhite", 0xfffffaf0 },
- { "forestgreen", 0xff228b22 },
- { "fuchsia", 0xffff00ff },
- { "gainsboro", 0xffdcdcdc },
- { "ghostwhite", 0xfff8f8ff },
- { "gold", 0xffffd700 },
- { "goldenrod", 0xffdaa520 },
- { "gray", 0xff808080 },
- { "grey", 0xff808080 },
- { "green", 0xff008000 },
- { "greenyellow", 0xffadff2f },
- { "honeydew", 0xfff0fff0 },
- { "hotpink", 0xffff69b4 },
- { "indianred", 0xffcd5c5c },
- { "indigo", 0xff4b0082 },
- { "ivory", 0xfffffff0 },
- { "khaki", 0xfff0e68c },
- { "lavender", 0xffe6e6fa },
- { "lavenderblush", 0xfffff0f5 },
- { "lawngreen", 0xff7cfc00 },
- { "lemonchiffon", 0xfffffacd },
- { "lightblue", 0xffadd8e6 },
- { "lightcoral", 0xfff08080 },
- { "lightcyan", 0xffe0ffff },
- { "lightgoldenrodyellow", 0xfffafad2 },
- { "lightgray", 0xffd3d3d3 },
- { "lightgrey", 0xffd3d3d3 },
- { "lightgreen", 0xff90ee90 },
- { "lightpink", 0xffffb6c1 },
- { "lightsalmon", 0xffffa07a },
- { "lightseagreen", 0xff20b2aa },
- { "lightskyblue", 0xff87cefa },
- { "lightslategray", 0xff778899 },
- { "lightslategrey", 0xff778899 },
- { "lightsteelblue", 0xffb0c4de },
- { "lightyellow", 0xffffffe0 },
- { "lime", 0xff00ff00 },
- { "limegreen", 0xff32cd32 },
- { "linen", 0xfffaf0e6 },
- { "magenta", 0xffff00ff },
- { "maroon", 0xff800000 },
- { "mediumaquamarine", 0xff66cdaa },
- { "mediumblue", 0xff0000cd },
- { "mediumorchid", 0xffba55d3 },
- { "mediumpurple", 0xff9370d8 },
- { "mediumseagreen", 0xff3cb371 },
- { "mediumslateblue", 0xff7b68ee },
- { "mediumspringgreen", 0xff00fa9a },
- { "mediumturquoise", 0xff48d1cc },
- { "mediumvioletred", 0xffc71585 },
- { "midnightblue", 0xff191970 },
- { "mintcream", 0xfff5fffa },
- { "mistyrose", 0xffffe4e1 },
- { "moccasin", 0xffffe4b5 },
- { "navajowhite", 0xffffdead },
- { "navy", 0xff000080 },
- { "oldlace", 0xfffdf5e6 },
- { "olive", 0xff808000 },
- { "olivedrab", 0xff6b8e23 },
- { "orange", 0xffffa500 },
- { "orangered", 0xffff4500 },
- { "orchid", 0xffda70d6 },
- { "palegoldenrod", 0xffeee8aa },
- { "palegreen", 0xff98fb98 },
- { "paleturquoise", 0xffafeeee },
- { "palevioletred", 0xffd87093 },
- { "papayawhip", 0xffffefd5 },
- { "peachpuff", 0xffffdab9 },
- { "peru", 0xffcd853f },
- { "pink", 0xffffc0cb },
- { "plum", 0xffdda0dd },
- { "powderblue", 0xffb0e0e6 },
- { "purple", 0xff800080 },
- { "red", 0xffff0000 },
- { "rosybrown", 0xffbc8f8f },
- { "royalblue", 0xff4169e1 },
- { "saddlebrown", 0xff8b4513 },
- { "salmon", 0xfffa8072 },
- { "sandybrown", 0xfff4a460 },
- { "seagreen", 0xff2e8b57 },
- { "seashell", 0xfffff5ee },
- { "sienna", 0xffa0522d },
- { "silver", 0xffc0c0c0 },
- { "skyblue", 0xff87ceeb },
- { "slateblue", 0xff6a5acd },
- { "slategray", 0xff708090 },
- { "slategrey", 0xff708090 },
- { "snow", 0xfffffafa },
- { "springgreen", 0xff00ff7f },
- { "steelblue", 0xff4682b4 },
- { "tan", 0xffd2b48c },
- { "teal", 0xff008080 },
- { "thistle", 0xffd8bfd8 },
- { "tomato", 0xffff6347 },
- { "turquoise", 0xff40e0d0 },
- { "violet", 0xffee82ee },
- { "wheat", 0xfff5deb3 },
- { "white", 0xffffffff },
- { "whitesmoke", 0xfff5f5f5 },
- { "yellow", 0xffffff00 },
- { "yellowgreen", 0xff9acd32 }
+ {"aliceblue", {0xf0, 0xf8, 0xff}},
+ {"antiquewhite", {0xfa, 0xeb, 0xd7}},
+ {"aqua", {0x00, 0xff, 0xff}},
+ {"aquamarine", {0x7f, 0xff, 0xd4}},
+ {"azure", {0xf0, 0xff, 0xff}},
+ {"beige", {0xf5, 0xf5, 0xdc}},
+ {"bisque", {0xff, 0xe4, 0xc4}},
+ {"black", {0x00, 0x00, 0x00}},
+ {"blanchedalmond", {0xff, 0xeb, 0xcd}},
+ {"blue", {0x00, 0x00, 0xff}},
+ {"blueviolet", {0x8a, 0x2b, 0xe2}},
+ {"brown", {0xa5, 0x2a, 0x2a}},
+ {"burlywood", {0xde, 0xb8, 0x87}},
+ {"cadetblue", {0x5f, 0x9e, 0xa0}},
+ {"chartreuse", {0x7f, 0xff, 0x00}},
+ {"chocolate", {0xd2, 0x69, 0x1e}},
+ {"coral", {0xff, 0x7f, 0x50}},
+ {"cornflowerblue", {0x64, 0x95, 0xed}},
+ {"cornsilk", {0xff, 0xf8, 0xdc}},
+ {"crimson", {0xdc, 0x14, 0x3c}},
+ {"cyan", {0x00, 0xff, 0xff}},
+ {"darkblue", {0x00, 0x00, 0x8b}},
+ {"darkcyan", {0x00, 0x8b, 0x8b}},
+ {"darkgoldenrod", {0xb8, 0x86, 0x0b}},
+ {"darkgray", {0xa9, 0xa9, 0xa9}},
+ {"darkgreen", {0x00, 0x64, 0x00}},
+ {"darkgrey", {0xa9, 0xa9, 0xa9}},
+ {"darkkhaki", {0xbd, 0xb7, 0x6b}},
+ {"darkmagenta", {0x8b, 0x00, 0x8b}},
+ {"darkolivegreen", {0x55, 0x6b, 0x2f}},
+ {"darkorange", {0xff, 0x8c, 0x00}},
+ {"darkorchid", {0x99, 0x32, 0xcc}},
+ {"darkred", {0x8b, 0x00, 0x00}},
+ {"darksalmon", {0xe9, 0x96, 0x7a}},
+ {"darkseagreen", {0x8f, 0xbc, 0x8f}},
+ {"darkslateblue", {0x48, 0x3d, 0x8b}},
+ {"darkslategray", {0x2f, 0x4f, 0x4f}},
+ {"darkslategrey", {0x2f, 0x4f, 0x4f}},
+ {"darkturquoise", {0x00, 0xce, 0xd1}},
+ {"darkviolet", {0x94, 0x00, 0xd3}},
+ {"deeppink", {0xff, 0x14, 0x93}},
+ {"deepskyblue", {0x00, 0xbf, 0xff}},
+ {"dimgray", {0x69, 0x69, 0x69}},
+ {"dimgrey", {0x69, 0x69, 0x69}},
+ {"dodgerblue", {0x1e, 0x90, 0xff}},
+ {"firebrick", {0xb2, 0x22, 0x22}},
+ {"floralwhite", {0xff, 0xfa, 0xf0}},
+ {"forestgreen", {0x22, 0x8b, 0x22}},
+ {"fuchsia", {0xff, 0x00, 0xff}},
+ {"gainsboro", {0xdc, 0xdc, 0xdc}},
+ {"ghostwhite", {0xf8, 0xf8, 0xff}},
+ {"gold", {0xff, 0xd7, 0x00}},
+ {"goldenrod", {0xda, 0xa5, 0x20}},
+ {"gray", {0x80, 0x80, 0x80}},
+ {"green", {0x00, 0x80, 0x00}},
+ {"greenyellow", {0xad, 0xff, 0x2f}},
+ {"grey", {0x80, 0x80, 0x80}},
+ {"honeydew", {0xf0, 0xff, 0xf0}},
+ {"hotpink", {0xff, 0x69, 0xb4}},
+ {"indianred", {0xcd, 0x5c, 0x5c}},
+ {"indigo", {0x4b, 0x00, 0x82}},
+ {"ivory", {0xff, 0xff, 0xf0}},
+ {"khaki", {0xf0, 0xe6, 0x8c}},
+ {"lavender", {0xe6, 0xe6, 0xfa}},
+ {"lavenderblush", {0xff, 0xf0, 0xf5}},
+ {"lawngreen", {0x7c, 0xfc, 0x00}},
+ {"lemonchiffon", {0xff, 0xfa, 0xcd}},
+ {"lightblue", {0xad, 0xd8, 0xe6}},
+ {"lightcoral", {0xf0, 0x80, 0x80}},
+ {"lightcyan", {0xe0, 0xff, 0xff}},
+ {"lightgoldenrodyellow", {0xfa, 0xfa, 0xd2}},
+ {"lightgray", {0xd3, 0xd3, 0xd3}},
+ {"lightgreen", {0x90, 0xee, 0x90}},
+ {"lightgrey", {0xd3, 0xd3, 0xd3}},
+ {"lightpink", {0xff, 0xb6, 0xc1}},
+ {"lightsalmon", {0xff, 0xa0, 0x7a}},
+ {"lightseagreen", {0x20, 0xb2, 0xaa}},
+ {"lightskyblue", {0x87, 0xce, 0xfa}},
+ {"lightslategray", {0x77, 0x88, 0x99}},
+ {"lightslategrey", {0x77, 0x88, 0x99}},
+ {"lightsteelblue", {0xb0, 0xc4, 0xde}},
+ {"lightyellow", {0xff, 0xff, 0xe0}},
+ {"lime", {0x00, 0xff, 0x00}},
+ {"limegreen", {0x32, 0xcd, 0x32}},
+ {"linen", {0xfa, 0xf0, 0xe6}},
+ {"magenta", {0xff, 0x00, 0xff}},
+ {"maroon", {0x80, 0x00, 0x00}},
+ {"mediumaquamarine", {0x66, 0xcd, 0xaa}},
+ {"mediumblue", {0x00, 0x00, 0xcd}},
+ {"mediumorchid", {0xba, 0x55, 0xd3}},
+ {"mediumpurple", {0x93, 0x70, 0xdb}},
+ {"mediumseagreen", {0x3c, 0xb3, 0x71}},
+ {"mediumslateblue", {0x7b, 0x68, 0xee}},
+ {"mediumspringgreen", {0x00, 0xfa, 0x9a}},
+ {"mediumturquoise", {0x48, 0xd1, 0xcc}},
+ {"mediumvioletred", {0xc7, 0x15, 0x85}},
+ {"midnightblue", {0x19, 0x19, 0x70}},
+ {"mintcream", {0xf5, 0xff, 0xfa}},
+ {"mistyrose", {0xff, 0xe4, 0xe1}},
+ {"moccasin", {0xff, 0xe4, 0xb5}},
+ {"navajowhite", {0xff, 0xde, 0xad}},
+ {"navy", {0x00, 0x00, 0x80}},
+ {"oldlace", {0xfd, 0xf5, 0xe6}},
+ {"olive", {0x80, 0x80, 0x00}},
+ {"olivedrab", {0x6b, 0x8e, 0x23}},
+ {"orange", {0xff, 0xa5, 0x00}},
+ {"orangered", {0xff, 0x45, 0x00}},
+ {"orchid", {0xda, 0x70, 0xd6}},
+ {"palegoldenrod", {0xee, 0xe8, 0xaa}},
+ {"palegreen", {0x98, 0xfb, 0x98}},
+ {"paleturquoise", {0xaf, 0xee, 0xee}},
+ {"palevioletred", {0xdb, 0x70, 0x93}},
+ {"papayawhip", {0xff, 0xef, 0xd5}},
+ {"peachpuff", {0xff, 0xda, 0xb9}},
+ {"peru", {0xcd, 0x85, 0x3f}},
+ {"pink", {0xff, 0xc0, 0xcb}},
+ {"plum", {0xdd, 0xa0, 0xdd}},
+ {"powderblue", {0xb0, 0xe0, 0xe6}},
+ {"purple", {0x80, 0x00, 0x80}},
+ {"red", {0xff, 0x00, 0x00}},
+ {"rosybrown", {0xbc, 0x8f, 0x8f}},
+ {"royalblue", {0x41, 0x69, 0xe1}},
+ {"saddlebrown", {0x8b, 0x45, 0x13}},
+ {"salmon", {0xfa, 0x80, 0x72}},
+ {"sandybrown", {0xf4, 0xa4, 0x60}},
+ {"seagreen", {0x2e, 0x8b, 0x57}},
+ {"seashell", {0xff, 0xf5, 0xee}},
+ {"sienna", {0xa0, 0x52, 0x2d}},
+ {"silver", {0xc0, 0xc0, 0xc0}},
+ {"skyblue", {0x87, 0xce, 0xeb}},
+ {"slateblue", {0x6a, 0x5a, 0xcd}},
+ {"slategray", {0x70, 0x80, 0x90}},
+ {"slategrey", {0x70, 0x80, 0x90}},
+ {"snow", {0xff, 0xfa, 0xfa}},
+ {"springgreen", {0x00, 0xff, 0x7f}},
+ {"steelblue", {0x46, 0x82, 0xb4}},
+ {"tan", {0xd2, 0xb4, 0x8c}},
+ {"teal", {0x00, 0x80, 0x80}},
+ {"thistle", {0xd8, 0xbf, 0xd8}},
+ {"tomato", {0xff, 0x63, 0x47}},
+ {"turquoise", {0x40, 0xe0, 0xd0}},
+ {"violet", {0xee, 0x82, 0xee}},
+ {"wheat", {0xf5, 0xde, 0xb3}},
+ {"white", {0xff, 0xff, 0xff}},
+ {"whitesmoke", {0xf5, 0xf5, 0xf5}},
+ {"yellow", {0xff, 0xff, 0x00}},
+ {"yellowgreen", {0x9a, 0xcd, 0x32}}
};
+static bool _parseHexColor(const char* str, size_t len, uint8_t& r, uint8_t& g, uint8_t& b)
+{
+ if (len != 4 && len != 7) return false;
+
+ auto value = [](char c) {
+ if (c >= '0' && c <= '9') return c - '0';
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+ return -1;
+ };
+
+ int8_t hex[6];
+ auto count = len - 1;
+ for (size_t i = 0; i < count; ++i) {
+ hex[i] = value(str[i + 1]);
+ if (hex[i] < 0) return false;
+ }
+
+ if (len == 4) {
+ r = hex[0] * 17;
+ g = hex[1] * 17;
+ b = hex[2] * 17;
+ } else {
+ r = (hex[0] << 4) | hex[1];
+ g = (hex[2] << 4) | hex[3];
+ b = (hex[4] << 4) | hex[5];
+ }
+ return true;
+}
+
+static bool _parseColor(const char* str, bool alpha, uint8_t& r, uint8_t& g, uint8_t& b, uint8_t* a)
+{
+ char *red, *green, *blue;
+ auto tr = _parseColor(str + (alpha ? 5 : 4), &red);
+ if (!red || *red != ',') return false;
+ auto tg = _parseColor(red + 1, &green);
+ if (!green || *green != ',') return false;
+ auto tb = _parseColor(green + 1, &blue);
+
+ if (alpha) {
+ if (!blue || *blue != ',') return false;
+ char* end;
+ auto value = toFloat(blue + 1, &end);
+ end = (char*)svgUtilSkipWhiteSpace(end, nullptr);
+ if (!end || end[0] != ')' || end[1] != '\0' || value < 0.0f || value > 1.0f) return false;
+ if (a) *a = static_cast<uint8_t>(lrintf(value * 255.0f));
+ } else if (!blue || blue[0] != ')' || blue[1] != '\0') return false;
-static bool _toColor(const char* str, uint8_t& r, uint8_t&g, uint8_t& b, char** ref)
+ r = tr;
+ g = tg;
+ b = tb;
+
+ return true;
+}
+
+static bool _toColor(const char* str, uint8_t& r, uint8_t& g, uint8_t& b, uint8_t* a, char** ref = nullptr)
{
auto len = strlen(str);
- if (len == 4 && str[0] == '#') {
- //Case for "#456" should be interpreted as "#445566"
- if (isxdigit(str[1]) && isxdigit(str[2]) && isxdigit(str[3])) {
- char tmp[3] = { '\0', '\0', '\0' };
- tmp[0] = str[1];
- tmp[1] = str[1];
- r = strtol(tmp, nullptr, 16);
- tmp[0] = str[2];
- tmp[1] = str[2];
- g = strtol(tmp, nullptr, 16);
- tmp[0] = str[3];
- tmp[1] = str[3];
- b = strtol(tmp, nullptr, 16);
- }
- return true;
- } else if (len == 7 && str[0] == '#') {
- if (isxdigit(str[1]) && isxdigit(str[2]) && isxdigit(str[3]) && isxdigit(str[4]) && isxdigit(str[5]) && isxdigit(str[6])) {
- char tmp[3] = { '\0', '\0', '\0' };
- tmp[0] = str[1];
- tmp[1] = str[2];
- r = strtol(tmp, nullptr, 16);
- tmp[0] = str[3];
- tmp[1] = str[4];
- g = strtol(tmp, nullptr, 16);
- tmp[0] = str[5];
- tmp[1] = str[6];
- b = strtol(tmp, nullptr, 16);
- }
- return true;
- } else if (len >= 10 && (str[0] == 'r' || str[0] == 'R') && (str[1] == 'g' || str[1] == 'G') && (str[2] == 'b' || str[2] == 'B') && str[3] == '(' && str[len - 1] == ')') {
- char *red, *green, *blue;
- auto tr = _parseColor(str + 4, &red);
- if (red && *red == ',') {
- auto tg = _parseColor(red + 1, &green);
- if (green && *green == ',') {
- auto tb = _parseColor(green + 1, &blue);
- if (blue && blue[0] == ')' && blue[1] == '\0') {
- r = tr;
- g = tg;
- b = tb;
- }
- }
- }
- return true;
+ if (str[0] == '#') {
+ return _parseHexColor(str, len, r, g, b);
+ } else if (len >= 10 && !strncasecmp(str, "rgb(", 4) && str[len - 1] == ')') {
+ return _parseColor(str, false, r, g, b, a);
+ } else if (len >= 12 && !strncasecmp(str, "rgba(", 5) && str[len - 1] == ')') {
+ return _parseColor(str, true, r, g, b, a);
} else if (ref && len >= 3 && !strncmp(str, "url", 3)) {
tvg::free(*ref);
*ref = _idFromUrl((const char*)(str + 3));
@@ -627,21 +731,26 @@ static bool _toColor(const char* str, uint8_t& r, uint8_t&g, uint8_t& b, char**
hsl.l /= 100.0f;
brightness = svgUtilSkipWhiteSpace(brightness + 1, nullptr);
if (brightness && brightness[0] == ')' && brightness[1] == '\0') {
- hsl2rgb(hsl.h, tvg::clamp(hsl.s, 0.0f, 1.0f), tvg::clamp(hsl.l, 0.0f, 1.0f), r, g, b);
- return true;
+ svgUtilHslToRgb(hsl.h, tvg::clamp(hsl.s, 0.0f, 1.0f), tvg::clamp(hsl.l, 0.0f, 1.0f), r, g, b);
+ return true;
}
}
}
}
} else {
- //Handle named color
- for (unsigned int i = 0; i < (sizeof(colors) / sizeof(colors[0])); i++) {
- if (!strcasecmp(colors[i].name, str)) {
- r = ((uint8_t*)(&(colors[i].value)))[2];
- g = ((uint8_t*)(&(colors[i].value)))[1];
- b = ((uint8_t*)(&(colors[i].value)))[0];
+ // Handle named color (binary search) - colors[] must remain sorted
+ int low = 0, high = static_cast<int>(sizeof(colors) / sizeof(colors[0])) - 1;
+ while (low <= high) {
+ auto mid = (low + high) / 2;
+ auto cmp = strcasecmp(str, colors[mid].name);
+ if (cmp == 0) {
+ r = colors[mid].value.r;
+ g = colors[mid].value.g;
+ b = colors[mid].value.b;
return true;
}
+ if (cmp < 0) high = mid - 1;
+ else low = mid + 1;
}
}
return false;
@@ -801,19 +910,19 @@ error:
static bool _attrParseSvgNode(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- SvgNode* node = loader->svgParse->node;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ SvgNode* node = ctx->parser->node;
SvgDocNode* doc = &(node->node.doc);
if (STR_AS(key, "width")) {
- doc->w = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
+ doc->w = _toFloat(ctx->parser, value, SvgParserLengthType::Horizontal);
if (strstr(value, "%") && !(doc->viewFlag & SvgViewFlag::Viewbox)) {
doc->viewFlag = (doc->viewFlag | SvgViewFlag::WidthInPercent);
} else {
doc->viewFlag = (doc->viewFlag | SvgViewFlag::Width);
}
} else if (STR_AS(key, "height")) {
- doc->h = _toFloat(loader->svgParse, value, SvgParserLengthType::Vertical);
+ doc->h = _toFloat(ctx->parser, value, SvgParserLengthType::Vertical);
if (strstr(value, "%") && !(doc->viewFlag & SvgViewFlag::Viewbox)) {
doc->viewFlag = (doc->viewFlag | SvgViewFlag::HeightInPercent);
} else {
@@ -825,32 +934,32 @@ static bool _attrParseSvgNode(void* data, const char* key, const char* value)
if (_parseNumber(&value, nullptr, &doc->vbox.w)) {
if (_parseNumber(&value, nullptr, &doc->vbox.h)) {
doc->viewFlag = (doc->viewFlag | SvgViewFlag::Viewbox);
- loader->svgParse->global.h = doc->vbox.h;
+ ctx->parser->global.h = doc->vbox.h;
}
- loader->svgParse->global.w = doc->vbox.w;
+ ctx->parser->global.w = doc->vbox.w;
}
- loader->svgParse->global.y = doc->vbox.y;
+ ctx->parser->global.y = doc->vbox.y;
}
- loader->svgParse->global.x = doc->vbox.x;
+ ctx->parser->global.x = doc->vbox.x;
}
if ((doc->viewFlag & SvgViewFlag::Viewbox) && (doc->vbox.w < 0.0f || doc->vbox.h < 0.0f)) {
doc->viewFlag = (SvgViewFlag)((uint32_t)doc->viewFlag & ~(uint32_t)SvgViewFlag::Viewbox);
TVGLOG("SVG", "Negative values of the <viewBox> width and/or height - the attribute invalidated.");
}
if (!(doc->viewFlag & SvgViewFlag::Viewbox)) {
- loader->svgParse->global.x = loader->svgParse->global.y = 0.0f;
- loader->svgParse->global.w = loader->svgParse->global.h = 1.0f;
+ ctx->parser->global.x = ctx->parser->global.y = 0.0f;
+ ctx->parser->global.w = ctx->parser->global.h = 1.0f;
}
} else if (STR_AS(key, "preserveAspectRatio")) {
_parseAspectRatio(&value, &doc->align, &doc->meetOrSlice);
} else if (STR_AS(key, "style")) {
- return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
+ return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
#ifdef THORVG_LOG_ENABLED
} else if ((STR_AS(key, "x") || STR_AS(key, "y")) && fabsf(toFloat(value, nullptr)) > FLOAT_EPSILON) {
TVGLOG("SVG", "Unsupported attributes used [Elements type: Svg][Attribute: %s][Value: %s]", key, value);
#endif
} else {
- return _parseStyleAttr(loader, key, value, false);
+ return _parseStyleAttr(ctx, key, value, false);
}
return true;
}
@@ -869,74 +978,73 @@ static void _handlePaintAttr(SvgPaint* paint, const char* value)
paint->none = false;
return;
}
- if (_toColor(value, paint->color.r, paint->color.g, paint->color.b, &paint->url)) paint->none = false;
+ paint->color.a = 255;
+ if (_toColor(value, paint->color.r, paint->color.g, paint->color.b, &paint->color.a, &paint->url)) {
+ paint->none = false;
+ }
}
-
-static void _handleColorAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleColorAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto style = node->style;
- if (_toColor(value, style->color.r, style->color.g, style->color.b, nullptr)) {
+ style->color.a = 255;
+ if (_toColor(value, style->color.r, style->color.g, style->color.b, &style->color.a)) {
style->curColorSet = true;
}
}
-
-static void _handleFillAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleFillAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto style = node->style;
style->fill.flags = (style->fill.flags | SvgFillFlags::Paint);
_handlePaintAttr(&style->fill.paint, value);
}
-
-static void _handleStrokeAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto style = node->style;
style->stroke.flags = (style->stroke.flags | SvgStrokeFlags::Paint);
_handlePaintAttr(&style->stroke.paint, value);
}
-
-static void _handleStrokeOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeOpacityAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Opacity);
node->style->stroke.opacity = _toOpacity(value);
}
-static void _handleStrokeDashArrayAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeDashArrayAttr(SvgParserContext* ctx, SvgNode* node, const char* value)
{
- node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Dash);
- _parseDashArray(loader, value, &node->style->stroke.dash);
+ if (_parseDashArray(ctx, value, &node->style->stroke.dash)) {
+ node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Dash);
+ }
}
-static void _handleStrokeDashOffsetAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeDashOffsetAttr(SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::DashOffset);
- node->style->stroke.dash.offset = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
+ node->style->stroke.dash.offset = _toFloat(ctx->parser, value, SvgParserLengthType::Horizontal);
}
-static void _handleStrokeWidthAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeWidthAttr(SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Width);
- node->style->stroke.width = _toFloat(loader->svgParse, value, SvgParserLengthType::Diagonal);
+ node->style->stroke.width = _toFloat(ctx->parser, value, SvgParserLengthType::Diagonal);
}
-
-static void _handleStrokeLineCapAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeLineCapAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Cap);
node->style->stroke.cap = _toLineCap(value);
}
-
-static void _handleStrokeLineJoinAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeLineJoinAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->stroke.flags = (node->style->stroke.flags | SvgStrokeFlags::Join);
node->style->stroke.join = _toLineJoin(value);
}
-static void _handleStrokeMiterlimitAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleStrokeMiterlimitAttr(SvgParserContext* ctx, SvgNode* node, const char* value)
{
char* end = nullptr;
const float miterlimit = toFloat(value, &end);
@@ -952,34 +1060,30 @@ static void _handleStrokeMiterlimitAttr(SvgLoaderData* loader, SvgNode* node, co
node->style->stroke.miterlimit = miterlimit;
}
-static void _handleFillRuleAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleFillRuleAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->fill.flags = (node->style->fill.flags | SvgFillFlags::FillRule);
node->style->fill.fillRule = _toFillRule(value);
}
-
-static void _handleOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleOpacityAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->flags = (node->style->flags | SvgStyleFlags::Opacity);
node->style->opacity = _toOpacity(value);
}
-
-static void _handleFillOpacityAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleFillOpacityAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->fill.flags = (node->style->fill.flags | SvgFillFlags::Opacity);
node->style->fill.opacity = _toOpacity(value);
}
-
-static void _handleTransformAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleTransformAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->transform = _parseTransformationMatrix(value);
}
-
-static void _handleClipPathAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleClipPathAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto style = node->style;
int len = strlen(value);
@@ -989,8 +1093,7 @@ static void _handleClipPathAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node,
}
}
-
-static void _handleMaskAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleMaskAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto style = node->style;
int len = strlen(value);
@@ -1000,8 +1103,7 @@ static void _handleMaskAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, con
}
}
-
-static void _handleFilterAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleFilterAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto style = node->style;
int len = strlen(value);
@@ -1011,14 +1113,13 @@ static void _handleFilterAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, c
}
}
-
-static void _handleMaskTypeAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleMaskTypeAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
+ if (node->type != SvgNodeType::Mask) return;
node->node.mask.type = _toMaskType(value);
}
-
-static void _handleDisplayAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleDisplayAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
//TODO : The display attribute can have various values as well as "none".
// The default is "inline" which means visible and "none" means invisible.
@@ -1032,26 +1133,109 @@ static void _handleDisplayAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node,
static bool _cssApplyClass(SvgNode* node, const char* classString, SvgNode* styleRoot);
-static void _handlePaintOrderAttr(TVG_UNUSED SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handlePaintOrderAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
{
node->style->flags = (node->style->flags | SvgStyleFlags::PaintOrder);
node->style->paintOrder = _toPaintOrder(value);
}
+static void _handleMixBlendModeAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->blendMode = _toBlendMode(value);
+ node->style->flags |= SvgStyleFlags::BlendMode;
+}
+
+static void _handleTextAnchorAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->flags |= SvgStyleFlags::TextAnchor;
+ if (STR_AS(value, "middle")) node->style->textAnchor = 0.5f;
+ else if (STR_AS(value, "end")) node->style->textAnchor = 1.0f;
+ else node->style->textAnchor = 0.0f;
+}
+
+static void _handleFontWeightAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->fontWeight = _toFontWeight(value);
+ node->style->flags |= SvgStyleFlags::FontWeight;
+}
+
+static SvgBaseline _toBaseline(const char* str)
+{
+ if (STR_AS(str, "alphabetic")) return SvgBaseline::Alphabetic;
+ if (STR_AS(str, "before-edge") || STR_AS(str, "text-before-edge") || STR_AS(str, "text-top")) return SvgBaseline::BeforeEdge;
+ if (STR_AS(str, "after-edge") || STR_AS(str, "text-after-edge") || STR_AS(str, "ideographic") || STR_AS(str, "text-bottom")) return SvgBaseline::AfterEdge;
+ if (STR_AS(str, "central")) return SvgBaseline::Central;
+ if (STR_AS(str, "middle")) return SvgBaseline::Middle;
+ if (STR_AS(str, "hanging")) return SvgBaseline::Hanging;
+ if (STR_AS(str, "mathematical")) return SvgBaseline::Mathematical;
+ return SvgBaseline::Auto;
+}
+
+static void _handleAlignmentBaselineAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->flags |= SvgStyleFlags::AlignmentBaseline;
+ node->style->alignmentBaseline = _toBaseline(value);
+}
+
+static void _handleDominantBaselineAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->flags |= SvgStyleFlags::DominantBaseline;
+ node->style->dominantBaseline = _toBaseline(value);
+}
+
+//toFloat() consumes the "em" suffix, so detect font-relative units from the value's tail instead of its end pointer
+static bool _isFontRelativeUnit(const char* value)
+{
+ auto p = value + strlen(value);
+ while (p > value && isspace((unsigned char)p[-1])) --p;
+ auto end = p;
+ while (p > value && isalpha((unsigned char)p[-1])) --p;
+ if (end - p != 2) return false; //so that "rem" is not mistaken for "em"
+ return !strncmp(p, "em", 2) || !strncmp(p, "ex", 2);
+}
+
+static void _handleLetterSpacingAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->flags |= SvgStyleFlags::LetterSpacing;
+ node->style->letterSpacingRelative = false;
+ if (STR_AS(value, "normal")) {
+ node->style->letterSpacing = 0.0f;
+ return;
+ }
+ char* end = nullptr;
+ auto parsed = toFloat(value, &end);
+ auto percentage = _isPercentage(end);
+ node->style->letterSpacingRelative = percentage || _isFontRelativeUnit(value);
+ node->style->letterSpacing = parsed * (percentage ? 0.01f : _unitScale(value, 1.0f));
+}
-static void _handleCssClassAttr(SvgLoaderData* loader, SvgNode* node, const char* value)
+static void _handleWordSpacingAttr(TVG_UNUSED SvgParserContext* ctx, SvgNode* node, const char* value)
+{
+ node->style->flags |= SvgStyleFlags::WordSpacing;
+ node->style->wordSpacingRelative = false;
+ if (STR_AS(value, "normal")) {
+ node->style->wordSpacing = 0.0f;
+ return;
+ }
+ char* end = nullptr;
+ auto parsed = toFloat(value, &end);
+ auto percentage = _isPercentage(end);
+ node->style->wordSpacingRelative = percentage || _isFontRelativeUnit(value);
+ node->style->wordSpacing = parsed * (percentage ? 0.01f : _unitScale(value, 1.0f));
+}
+
+static void _handleCssClassAttr(SvgParserContext* ctx, SvgNode* node, const char* value)
{
auto cssClass = &node->style->cssClass;
_copyId(cssClass, value);
- if (!_cssApplyClass(node, *cssClass, loader->cssStyle)) {
- loader->nodesToStyle.push({node, *cssClass});
+ if (!_cssApplyClass(node, *cssClass, ctx->cssStyle)) {
+ ctx->nodesToStyle.push({node, *cssClass});
}
}
-
-typedef void (*styleMethod)(SvgLoaderData* loader, SvgNode* node, const char* value);
+typedef void (*styleMethod)(SvgParserContext* ctx, SvgNode* node, const char* value);
#define STYLE_DEF(Name, Name1, Flag) { #Name, sizeof(#Name), _handle##Name1##Attr, Flag }
@@ -1063,6 +1247,8 @@ static constexpr struct
styleMethod tagHandler;
SvgStyleFlags flag;
} styleTags[] = {
+// hyphenated names below are macro identifiers, not subtraction; keep them intact
+// clang-format off
STYLE_DEF(color, Color, SvgStyleFlags::Color),
STYLE_DEF(fill, Fill, SvgStyleFlags::Fill),
STYLE_DEF(fill-rule, FillRule, SvgStyleFlags::FillRule),
@@ -1082,9 +1268,16 @@ static constexpr struct
STYLE_DEF(mask-type, MaskType, SvgStyleFlags::MaskType),
STYLE_DEF(display, Display, SvgStyleFlags::Display),
STYLE_DEF(paint-order, PaintOrder, SvgStyleFlags::PaintOrder),
- STYLE_DEF(filter, Filter, SvgStyleFlags::Filter)
+ STYLE_DEF(filter, Filter, SvgStyleFlags::Filter),
+ STYLE_DEF(mix-blend-mode, MixBlendMode, SvgStyleFlags::BlendMode),
+ STYLE_DEF(text-anchor, TextAnchor, SvgStyleFlags::TextAnchor),
+ STYLE_DEF(alignment-baseline, AlignmentBaseline, SvgStyleFlags::AlignmentBaseline),
+ STYLE_DEF(dominant-baseline, DominantBaseline, SvgStyleFlags::DominantBaseline),
+ STYLE_DEF(font-weight, FontWeight, SvgStyleFlags::FontWeight),
+ STYLE_DEF(letter-spacing, LetterSpacing, SvgStyleFlags::LetterSpacing),
+ STYLE_DEF(word-spacing, WordSpacing, SvgStyleFlags::WordSpacing)
};
-
+// clang-format on
static SvgXmlSpace _toXmlSpace(const char* str)
{
@@ -1102,8 +1295,8 @@ static bool _parseStyleAttr(void* data, const char* key, const char* value, bool
key = svgUtilSkipWhiteSpace(key, nullptr);
value = svgUtilSkipWhiteSpace(value, nullptr);
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
if (!style && STR_AS(key, "xml:space")) {
node->xmlSpace = _toXmlSpace(value);
@@ -1122,16 +1315,33 @@ static bool _parseStyleAttr(void* data, const char* key, const char* value, bool
value = duplicate(value, size);
importance = true;
}
+ auto valid = true;
+ if (styleTags[i].flag == SvgStyleFlags::FontWeight) {
+ valid = _toFontWeight(value) != SvgFontWeight::Invalid;
+ } else if (styleTags[i].flag == SvgStyleFlags::DominantBaseline) {
+ // svg 1.1 keyword set only (https://www.w3.org/TR/SVG11/text.html#DominantBaselineProperty):
+ // browsers drop the css-level text-top/text-bottom (https://www.w3.org/TR/css-inline-3/#dominant-baseline-property)
+ if (STR_AS(value, "text-top") || STR_AS(value, "text-bottom")) valid = false;
+ else valid = _toBaseline(value) != SvgBaseline::Auto || STR_AS(value, "auto");
+ } else if (styleTags[i].flag == SvgStyleFlags::LetterSpacing || styleTags[i].flag == SvgStyleFlags::WordSpacing) {
+ char* end = nullptr;
+ toFloat(value, &end);
+ valid = end != value || STR_AS(value, "normal");
+ }
+ if (!valid) {
+ if (importance) tvg::free(const_cast<char*>(value));
+ return true;
+ }
if (style) {
if (importance || !(node->style->flagsImportance & styleTags[i].flag)) {
- styleTags[i].tagHandler(loader, node, value);
+ styleTags[i].tagHandler(ctx, node, value);
node->style->flags = (node->style->flags | styleTags[i].flag);
}
} else if (!(node->style->flags & styleTags[i].flag)) {
- styleTags[i].tagHandler(loader, node, value);
+ styleTags[i].tagHandler(ctx, node, value);
}
if (importance) {
- node->style->flagsImportance = (node->style->flags | styleTags[i].flag);
+ node->style->flagsImportance |= styleTags[i].flag;
tvg::free(const_cast<char*>(value));
}
return true;
@@ -1153,17 +1363,17 @@ static bool _parseStyleAttr(void* data, const char* key, const char* value)
*/
static bool _attrParseGNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
- if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
+ if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
else if (STR_AS(key, "transform")) node->transform = _parseTransformationMatrix(value);
else if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
@@ -1174,67 +1384,85 @@ static bool _attrParseGNode(void* data, const char* key, const char* value)
*/
static bool _attrParseClipPathNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto clip = &node->node.clip;
if (STR_AS(key, "style")) {
- return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
+ return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
} else if (STR_AS(key, "transform")) {
node->transform = _parseTransformationMatrix(value);
} else if (STR_AS(key, "id")) {
_copyId(&node->id, value);
} else if (STR_AS(key, "class")) {
- _handleCssClassAttr(loader, node, value);
+ _handleCssClassAttr(ctx, node, value);
} else if (STR_AS(key, "clipPathUnits")) {
if (STR_AS(value, "objectBoundingBox")) clip->userSpace = false;
} else {
- return _parseStyleAttr(loader, key, value, false);
+ return _parseStyleAttr(ctx, key, value, false);
}
return true;
}
+static void _recalcBox(const SvgParserContext* ctx, Box* box, bool (&isPercentage)[4])
+{
+ auto array = (unsigned char*)box;
+ for (unsigned int i = 0; i < sizeof(boxTags) / sizeof(boxTags[0]); i++) {
+ if (!isPercentage[i]) continue;
+ if (boxTags[i].type == SvgParserLengthType::Horizontal) *(float*)(array + boxTags[i].offset) *= ctx->parser->global.w;
+ else *(float*)(array + boxTags[i].offset) *= ctx->parser->global.h;
+ }
+}
+
+static bool _parseBox(const char* key, const char* value, Box* box, bool (&isPercentage)[4])
+{
+ auto array = (unsigned char*)box;
+ int sz = strlen(key);
+ for (unsigned int i = 0; i < sizeof(boxTags) / sizeof(boxTags[0]); i++) {
+ if (boxTags[i].sz - 1 == sz && !strncmp(boxTags[i].tag, key, sz)) {
+ *(float*)(array + boxTags[i].offset) = _gradientToFloat(nullptr, value, isPercentage[i]);
+ return true;
+ }
+ }
+ return false;
+}
static bool _attrParseMaskNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto mask = &node->node.mask;
- if (STR_AS(key, "style")) {
- return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- } else if (STR_AS(key, "transform")) {
- node->transform = _parseTransformationMatrix(value);
- } else if (STR_AS(key, "id")) {
- _copyId(&node->id, value);
- } else if (STR_AS(key, "class")) {
- _handleCssClassAttr(loader, node, value);
- } else if (STR_AS(key, "maskContentUnits")) {
- if (STR_AS(value, "objectBoundingBox")) mask->userSpace = false;
- } else if (STR_AS(key, "mask-type")) {
- mask->type = _toMaskType(value);
- } else {
- return _parseStyleAttr(loader, key, value, false);
- }
+ if (_parseBox(key, value, &mask->box, mask->isPercentage)) return true;
+
+ if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "transform")) node->transform = _parseTransformationMatrix(value);
+ else if (STR_AS(key, "id")) _copyId(&node->id, value);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else if (STR_AS(key, "maskUnits")) { if (STR_AS(value, "userSpaceOnUse")) mask->userSpace = true; }
+ else if (STR_AS(key, "maskContentUnits")) { if (STR_AS(value, "objectBoundingBox")) mask->maskContentUserSpace = false; }
+ else if (STR_AS(key, "mask-type")) mask->type = _toMaskType(value);
+ else return _parseStyleAttr(ctx, key, value, false);
+
return true;
}
static bool _attrParseCssStyleNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
if (STR_AS(key, "id")) _copyId(&node->id, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
static bool _attrParseSymbolNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto symbol = &node->node.symbol;
if (STR_AS(key, "viewBox")) {
@@ -1242,10 +1470,10 @@ static bool _attrParseSymbolNode(void* data, const char* key, const char* value)
if (!_parseNumber(&value, nullptr, &symbol->vw) || !_parseNumber(&value, nullptr, &symbol->vh)) return false;
symbol->hasViewBox = true;
} else if (STR_AS(key, "width")) {
- symbol->w = _toFloat(loader->svgParse, value, SvgParserLengthType::Horizontal);
+ symbol->w = _toFloat(ctx->parser, value, SvgParserLengthType::Horizontal);
symbol->hasWidth = true;
} else if (STR_AS(key, "height")) {
- symbol->h = _toFloat(loader->svgParse, value, SvgParserLengthType::Vertical);
+ symbol->h = _toFloat(ctx->parser, value, SvgParserLengthType::Vertical);
symbol->hasHeight = true;
} else if (STR_AS(key, "preserveAspectRatio")) {
_parseAspectRatio(&value, &symbol->align, &symbol->meetOrSlice);
@@ -1257,50 +1485,10 @@ static bool _attrParseSymbolNode(void* data, const char* key, const char* value)
return true;
}
-
-static constexpr struct
-{
- const char* tag;
- SvgParserLengthType type;
- int sz;
- size_t offset;
-} boxTags[] = {
- {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(Box, x)},
- {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(Box, y)},
- {"width", SvgParserLengthType::Horizontal, sizeof("width"), offsetof(Box, w)},
- {"height", SvgParserLengthType::Vertical, sizeof("height"), offsetof(Box, h)}
-};
-
-
-static bool _parseBox(const char* key, const char* value, Box* box, bool (&isPercentage)[4])
-{
- auto array = (unsigned char*)box;
- int sz = strlen(key);
- for (unsigned int i = 0; i < sizeof(boxTags) / sizeof(boxTags[0]); i++) {
- if (boxTags[i].sz - 1 == sz && !strncmp(boxTags[i].tag, key, sz)) {
- *(float*)(array + boxTags[i].offset) = _gradientToFloat(nullptr, value, isPercentage[i]);
- return true;
- }
- }
- return false;
-}
-
-
-static void _recalcBox(const SvgLoaderData* loader, Box* box, bool (&isPercentage)[4])
-{
- auto array = (unsigned char*)box;
- for (unsigned int i = 0; i < sizeof(boxTags) / sizeof(boxTags[0]); i++) {
- if (!isPercentage[i]) continue;
- if (boxTags[i].type == SvgParserLengthType::Horizontal) *(float*)(array + boxTags[i].offset) *= loader->svgParse->global.w;
- else *(float*)(array + boxTags[i].offset) *= loader->svgParse->global.h;
- }
-}
-
-
static bool _attrParseFilterNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto filter = &node->node.filter;
_parseBox(key, value, &filter->box, filter->isPercentage);
@@ -1338,8 +1526,8 @@ static void _parseGaussianBlurStdDeviation(const char** content, float* x, float
static bool _attrParseGaussianBlurNode(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- SvgNode* node = loader->svgParse->node;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ SvgNode* node = ctx->parser->node;
SvgGaussianBlurNode* gaussianBlur = &node->node.gaussianBlur;
if (_parseBox(key, value, &gaussianBlur->box, gaussianBlur->isPercentage)) gaussianBlur->hasBox = true;
@@ -1350,7 +1538,7 @@ static bool _attrParseGaussianBlurNode(void* data, const char* key, const char*
_parseGaussianBlurStdDeviation(&value, &gaussianBlur->stdDevX, &gaussianBlur->stdDevY);
} else if (STR_AS(key, "edgeMode")) {
if (STR_AS(value, "wrap")) gaussianBlur->edgeModeWrap = true;
- } else return _parseStyleAttr(loader, key, value, false);
+ } else return _parseStyleAttr(ctx, key, value, false);
return true;
}
@@ -1364,9 +1552,12 @@ static SvgNode* _createNode(SvgNode* parent, SvgNodeType type)
//Set the default values other than 0/false: https://www.w3.org/TR/SVGTiny12/painting.html#SpecifyingPaint
node->style->opacity = 255;
+ node->style->color.a = 255;
node->style->fill.opacity = 255;
+ node->style->fill.paint.color.a = 255;
node->style->fill.fillRule = FillRule::NonZero;
node->style->stroke.paint.none = true;
+ node->style->stroke.paint.color.a = 255;
node->style->stroke.opacity = 255;
node->style->stroke.width = 1;
node->style->stroke.cap = StrokeCap::Butt;
@@ -1375,6 +1566,7 @@ static SvgNode* _createNode(SvgNode* parent, SvgNodeType type)
node->style->stroke.scale = 1.0;
node->style->paintOrder = _toPaintOrder("fill stroke");
node->style->display = true;
+ node->style->fontWeight = SvgFontWeight::Normal;
node->parent = parent;
node->type = type;
node->xmlSpace = SvgXmlSpace::None;
@@ -1383,160 +1575,193 @@ static SvgNode* _createNode(SvgNode* parent, SvgNodeType type)
return node;
}
-
-static SvgNode* _createDefsNode(TVG_UNUSED SvgLoaderData* loader, TVG_UNUSED SvgNode* parent, const char* buf, unsigned bufLength, TVG_UNUSED parseAttributes func)
+static SvgNode* _createDefsNode(TVG_UNUSED SvgParserContext* ctx, TVG_UNUSED SvgNode* parent, const char* buf, unsigned bufLength, TVG_UNUSED parseAttributes func)
{
- if (loader->def && loader->doc->node.doc.defs) return loader->def;
- loader->def = loader->doc->node.doc.defs = _createNode(nullptr, SvgNodeType::Defs);
- return loader->def;
+ if (ctx->def && ctx->doc->node.doc.defs) return ctx->def;
+ ctx->def = ctx->doc->node.doc.defs = _createNode(nullptr, SvgNodeType::Defs);
+ return ctx->def;
}
-
-static SvgNode* _createGNode(TVG_UNUSED SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createGNode(TVG_UNUSED SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::G);
- func(buf, bufLength, _attrParseGNode, loader);
- return loader->svgParse->node;
+ ctx->parser->node = _createNode(parent, SvgNodeType::G);
+ func(buf, bufLength, _attrParseGNode, ctx);
+ return ctx->parser->node;
}
-
-static SvgNode* _createSvgNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createSvgNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Doc);
- auto doc = &loader->svgParse->node->node.doc;
+ ctx->parser->node = _createNode(parent, SvgNodeType::Doc);
+ auto doc = &ctx->parser->node->node.doc;
- loader->svgParse->global.w = 1.0f;
- loader->svgParse->global.h = 1.0f;
+ ctx->parser->global.w = 1.0f;
+ ctx->parser->global.h = 1.0f;
doc->align = AspectRatioAlign::XMidYMid;
doc->meetOrSlice = AspectRatioMeetOrSlice::Meet;
doc->viewFlag = SvgViewFlag::None;
- func(buf, bufLength, _attrParseSvgNode, loader);
+ func(buf, bufLength, _attrParseSvgNode, ctx);
if (!(doc->viewFlag & SvgViewFlag::Viewbox)) {
if (doc->viewFlag & SvgViewFlag::Width) {
- loader->svgParse->global.w = doc->w;
+ ctx->parser->global.w = doc->w;
}
if (doc->viewFlag & SvgViewFlag::Height) {
- loader->svgParse->global.h = doc->h;
+ ctx->parser->global.h = doc->h;
}
}
- return loader->svgParse->node;
+ return ctx->parser->node;
}
-
-static SvgNode* _createMaskNode(SvgLoaderData* loader, SvgNode* parent, TVG_UNUSED const char* buf, TVG_UNUSED unsigned bufLength, parseAttributes func)
+static SvgNode* _createMaskNode(SvgParserContext* ctx, SvgNode* parent, TVG_UNUSED const char* buf, TVG_UNUSED unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Mask);
- if (!loader->svgParse->node) return nullptr;
+ ctx->parser->node = _createNode(parent, SvgNodeType::Mask);
+ if (!ctx->parser->node) return nullptr;
- loader->svgParse->node->node.mask.userSpace = true;
- loader->svgParse->node->node.mask.type = SvgMaskType::Luminance;
+ auto& mask = ctx->parser->node->node.mask;
+ mask.maskContentUserSpace = true;
+ mask.type = SvgMaskType::Luminance;
+ // default region per https://www.w3.org/TR/SVG11/masking.html#MaskElement (x/y=-10%, width/height=120%)
+ mask.box = {-0.1f, -0.1f, 1.2f, 1.2f};
+ mask.isPercentage[0] = mask.isPercentage[1] = mask.isPercentage[2] = mask.isPercentage[3] = true;
+ func(buf, bufLength, _attrParseMaskNode, ctx);
+ if (mask.userSpace) _recalcBox(ctx, &mask.box, mask.isPercentage);
- func(buf, bufLength, _attrParseMaskNode, loader);
-
- return loader->svgParse->node;
+ return ctx->parser->node;
}
-
-static SvgNode* _createClipPathNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createClipPathNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::ClipPath);
- if (!loader->svgParse->node) return nullptr;
+ ctx->parser->node = _createNode(parent, SvgNodeType::ClipPath);
+ if (!ctx->parser->node) return nullptr;
- loader->svgParse->node->style->display = false;
- loader->svgParse->node->node.clip.userSpace = true;
+ ctx->parser->node->style->display = false;
+ ctx->parser->node->node.clip.userSpace = true;
- func(buf, bufLength, _attrParseClipPathNode, loader);
+ func(buf, bufLength, _attrParseClipPathNode, ctx);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
-
-static SvgNode* _createCssStyleNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createCssStyleNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::CssStyle);
- if (!loader->svgParse->node) return nullptr;
+ ctx->parser->node = _createNode(parent, SvgNodeType::CssStyle);
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParseCssStyleNode, loader);
+ func(buf, bufLength, _attrParseCssStyleNode, ctx);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
-
-static SvgNode* _createSymbolNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createSymbolNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Symbol);
- if (!loader->svgParse->node) return nullptr;
+ ctx->parser->node = _createNode(parent, SvgNodeType::Symbol);
+ if (!ctx->parser->node) return nullptr;
- loader->svgParse->node->node.symbol.align = AspectRatioAlign::XMidYMid;
- loader->svgParse->node->node.symbol.meetOrSlice = AspectRatioMeetOrSlice::Meet;
+ ctx->parser->node->node.symbol.align = AspectRatioAlign::XMidYMid;
+ ctx->parser->node->node.symbol.meetOrSlice = AspectRatioMeetOrSlice::Meet;
- func(buf, bufLength, _attrParseSymbolNode, loader);
+ func(buf, bufLength, _attrParseSymbolNode, ctx);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
-
-static SvgNode* _createGaussianBlurNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createGaussianBlurNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::GaussianBlur);
- if (!loader->svgParse->node) return nullptr;
+ ctx->parser->node = _createNode(parent, SvgNodeType::GaussianBlur);
+ if (!ctx->parser->node) return nullptr;
- loader->svgParse->node->style->display = false;
- loader->svgParse->node->node.gaussianBlur.box = {0.0f, 0.0f, 1.0f, 1.0f};
+ ctx->parser->node->style->display = false;
+ ctx->parser->node->node.gaussianBlur.box = {0.0f, 0.0f, 1.0f, 1.0f};
- func(buf, bufLength, _attrParseGaussianBlurNode, loader);
+ func(buf, bufLength, _attrParseGaussianBlurNode, ctx);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
-
-static SvgNode* _createFilterNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createFilterNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Filter);
- if (!loader->svgParse->node) return nullptr;
- SvgFilterNode& filter = loader->svgParse->node->node.filter;
+ ctx->parser->node = _createNode(parent, SvgNodeType::Filter);
+ if (!ctx->parser->node) return nullptr;
+ SvgFilterNode& filter = ctx->parser->node->node.filter;
- loader->svgParse->node->style->display = false;
+ ctx->parser->node->style->display = false;
filter.box = {-0.1f, -0.1f, 1.2f, 1.2f};
filter.primitiveUserSpace = true;
- func(buf, bufLength, _attrParseFilterNode, loader);
+ func(buf, bufLength, _attrParseFilterNode, ctx);
- if (filter.filterUserSpace) _recalcBox(loader, &filter.box, filter.isPercentage);
+ if (filter.filterUserSpace) _recalcBox(ctx, &filter.box, filter.isPercentage);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
+static bool _attrParsePatternNode(void* data, const char* key, const char* value)
+{
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
+ auto pattern = &node->node.pattern;
+
+ if (_parseBox(key, value, &pattern->box, pattern->isPercentage)) return true;
+
+ if (STR_AS(key, "id")) _copyId(&node->id, value);
+ else if (STR_AS(key, "patternUnits")) {
+ if (STR_AS(value, "userSpaceOnUse")) pattern->patternUserSpace = true;
+ } else if (STR_AS(key, "patternContentUnits")) {
+ if (STR_AS(value, "objectBoundingBox")) pattern->contentUserSpace = false;
+ } else if (STR_AS(key, "viewBox")) {
+ if (!_parseNumber(&value, nullptr, &pattern->vbox.x) || !_parseNumber(&value, nullptr, &pattern->vbox.y)) return false;
+ if (!_parseNumber(&value, nullptr, &pattern->vbox.w) || !_parseNumber(&value, nullptr, &pattern->vbox.h)) return false;
+ if (pattern->vbox.w > 0.0f && pattern->vbox.h > 0.0f) pattern->hasViewBox = true;
+ } else if (STR_AS(key, "patternTransform")) {
+ pattern->transform = _parseTransformationMatrix(value);
+ }
+ return true;
+}
+
+static SvgNode* _createPatternNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+{
+ ctx->parser->node = _createNode(parent, SvgNodeType::Pattern);
+ if (!ctx->parser->node) return nullptr;
+ SvgPatternNode& pattern = ctx->parser->node->node.pattern;
+
+ ctx->parser->node->style->display = false;
+ pattern.patternUserSpace = false;
+ pattern.contentUserSpace = true;
+
+ func(buf, bufLength, _attrParsePatternNode, ctx);
+
+ if (pattern.patternUserSpace) _recalcBox(ctx, &pattern.box, pattern.isPercentage);
+
+ return ctx->parser->node;
+}
static bool _attrParsePathNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto path = &node->node.path;
if (STR_AS(key, "d")) _copyId(&path->path, value); // Temporary: need to copy
- else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
+ else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
else if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
-
-static SvgNode* _createPathNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createPathNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Path);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Path);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParsePathNode, loader);
+ func(buf, bufLength, _attrParsePathNode, ctx);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
@@ -1558,8 +1783,8 @@ static constexpr struct
*/
static bool _attrParseCircleNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto circle = &node->node.circle;
unsigned char* array;
int sz = strlen(key);
@@ -1567,30 +1792,29 @@ static bool _attrParseCircleNode(void* data, const char* key, const char* value)
array = (unsigned char*)circle;
for (unsigned int i = 0; i < sizeof(circleTags) / sizeof(circleTags[0]); i++) {
if (circleTags[i].sz - 1 == sz && !strncmp(circleTags[i].tag, key, sz)) {
- *((float*)(array + circleTags[i].offset)) = _toFloat(loader->svgParse, value, circleTags[i].type);
+ *((float*)(array + circleTags[i].offset)) = _toFloat(ctx->parser, value, circleTags[i].type);
return true;
}
}
- if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
+ if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
else if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
-
-static SvgNode* _createCircleNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createCircleNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Circle);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Circle);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParseCircleNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParseCircleNode, ctx);
+ return ctx->parser->node;
}
@@ -1613,8 +1837,8 @@ static constexpr struct
*/
static bool _attrParseEllipseNode(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- SvgNode* node = loader->svgParse->node;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ SvgNode* node = ctx->parser->node;
SvgEllipseNode* ellipse = &(node->node.ellipse);
unsigned char* array;
int sz = strlen(key);
@@ -1622,30 +1846,32 @@ static bool _attrParseEllipseNode(void* data, const char* key, const char* value
array = (unsigned char*)ellipse;
for (unsigned int i = 0; i < sizeof(ellipseTags) / sizeof(ellipseTags[0]); i++) {
if (ellipseTags[i].sz - 1 == sz && !strncmp(ellipseTags[i].tag, key, sz)) {
- *((float*)(array + ellipseTags[i].offset)) = _toFloat(loader->svgParse, value, ellipseTags[i].type);
+ *((float*)(array + ellipseTags[i].offset)) = _toFloat(ctx->parser, value, ellipseTags[i].type);
return true;
}
}
if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
-
-static SvgNode* _createEllipseNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createEllipseNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Ellipse);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Ellipse);
+
+ if (!ctx->parser->node) return nullptr;
- if (!loader->svgParse->node) return nullptr;
+ // Unspecified radii default to 'auto(-1)'; resolved when building the path.
+ ctx->parser->node->node.ellipse.rx = ctx->parser->node->node.ellipse.ry = -1.0f;
- func(buf, bufLength, _attrParseEllipseNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParseEllipseNode, ctx);
+ return ctx->parser->node;
}
@@ -1665,44 +1891,42 @@ static bool _attrParsePolygonPoints(const char* str, SvgPolygonNode* polygon)
*/
static bool _attrParsePolygonNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
SvgPolygonNode* polygon = nullptr;
if (node->type == SvgNodeType::Polygon) polygon = &node->node.polygon;
else polygon = &node->node.polyline;
if (STR_AS(key, "points")) return _attrParsePolygonPoints(value, polygon);
- else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
+ else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
else if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
-
-static SvgNode* _createPolygonNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createPolygonNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Polygon);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Polygon);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParsePolygonNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParsePolygonNode, ctx);
+ return ctx->parser->node;
}
-
-static SvgNode* _createPolylineNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createPolylineNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Polyline);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Polyline);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParsePolygonNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParsePolygonNode, ctx);
+ return ctx->parser->node;
}
static constexpr struct
@@ -1726,8 +1950,8 @@ static constexpr struct
*/
static bool _attrParseRectNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto rect = &node->node.rect;
unsigned char* array;
bool ret = true;
@@ -1736,7 +1960,7 @@ static bool _attrParseRectNode(void* data, const char* key, const char* value)
array = (unsigned char*)rect;
for (unsigned int i = 0; i < sizeof(rectTags) / sizeof(rectTags[0]); i++) {
if (rectTags[i].sz - 1 == sz && !strncmp(rectTags[i].tag, key, sz)) {
- *((float*)(array + rectTags[i].offset)) = _toFloat(loader->svgParse, value, rectTags[i].type);
+ *((float*)(array + rectTags[i].offset)) = _toFloat(ctx->parser, value, rectTags[i].type);
//Case if only rx or ry is declared
if (!strncmp(rectTags[i].tag, "rx", sz)) rect->hasRx = true;
@@ -1749,25 +1973,24 @@ static bool _attrParseRectNode(void* data, const char* key, const char* value)
}
if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else if (STR_AS(key, "style")) ret = xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
- else ret = _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else if (STR_AS(key, "style")) ret = xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
+ else ret = _parseStyleAttr(ctx, key, value, false);
return ret;
}
-
-static SvgNode* _createRectNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createRectNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Rect);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Rect);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParseRectNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParseRectNode, ctx);
+ return ctx->parser->node;
}
@@ -1790,8 +2013,8 @@ static constexpr struct
*/
static bool _attrParseLineNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto line = &node->node.line;
unsigned char* array;
int sz = strlen(key);
@@ -1799,31 +2022,30 @@ static bool _attrParseLineNode(void* data, const char* key, const char* value)
array = (unsigned char*)line;
for (unsigned int i = 0; i < sizeof(lineTags) / sizeof(lineTags[0]); i++) {
if (lineTags[i].sz - 1 == sz && !strncmp(lineTags[i].tag, key, sz)) {
- *((float*)(array + lineTags[i].offset)) = _toFloat(loader->svgParse, value, lineTags[i].type);
+ *((float*)(array + lineTags[i].offset)) = _toFloat(ctx->parser, value, lineTags[i].type);
return true;
}
}
if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
-
-static SvgNode* _createLineNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createLineNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Line);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Line);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParseLineNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParseLineNode, ctx);
+ return ctx->parser->node;
}
@@ -1854,8 +2076,8 @@ static constexpr struct
*/
static bool _attrParseImageNode(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- SvgNode* node = loader->svgParse->node;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ SvgNode* node = ctx->parser->node;
SvgImageNode* image = &(node->node.image);
unsigned char* array;
int sz = strlen(key);
@@ -1863,7 +2085,7 @@ static bool _attrParseImageNode(void* data, const char* key, const char* value)
array = (unsigned char*)image;
for (unsigned int i = 0; i < sizeof(imageTags) / sizeof(imageTags[0]); i++) {
if (imageTags[i].sz - 1 == sz && !strncmp(imageTags[i].tag, key, sz)) {
- *((float*)(array + imageTags[i].offset)) = _toFloat(loader->svgParse, value, imageTags[i].type);
+ *((float*)(array + imageTags[i].offset)) = _toFloat(ctx->parser, value, imageTags[i].type);
return true;
}
}
@@ -1872,26 +2094,25 @@ static bool _attrParseImageNode(void* data, const char* key, const char* value)
if (value) tvg::free(image->href);
image->href = _idFromHref(value);
} else if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
else if (STR_AS(key, "transform")) node->transform = _parseTransformationMatrix(value);
- else return _parseStyleAttr(loader, key, value);
+ else return _parseStyleAttr(ctx, key, value);
return true;
}
-
-static SvgNode* _createImageNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createImageNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Image);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Image);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParseImageNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParseImageNode, ctx);
+ return ctx->parser->node;
}
@@ -1910,8 +2131,8 @@ static bool _attrParseFontFace(void* data, const char* key, const char* value)
key = svgUtilSkipWhiteSpace(key, nullptr);
value = svgUtilSkipWhiteSpace(value, nullptr);
- auto loader = (SvgLoaderData*)data;
- auto& font = loader->fonts.last();
+ auto ctx = (SvgParserContext*)data;
+ auto& font = ctx->fonts.last();
if (STR_AS(key, "font-family")) {
if (font.name) tvg::free(font.name);
@@ -1923,11 +2144,10 @@ static bool _attrParseFontFace(void* data, const char* key, const char* value)
return true;
}
-
-static void _createFontFace(SvgLoaderData* loader, const char* buf, unsigned bufLength, parseAttributes func)
+static void _createFontFace(SvgParserContext* ctx, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->fonts.push(FontFace());
- func(buf, bufLength, _attrParseFontFace, loader);
+ ctx->fonts.push(FontFace());
+ func(buf, bufLength, _attrParseFontFace, ctx);
}
@@ -2008,8 +2228,8 @@ static constexpr struct
static void _cloneNode(SvgNode* from, SvgNode* parent, int depth);
static bool _attrParseUseNode(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- SvgNode *defs, *nodeFrom, *node = loader->svgParse->node;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ SvgNode *defs, *nodeFrom, *node = ctx->parser->node;
char* id;
SvgUseNode* use = &(node->node.use);
@@ -2017,7 +2237,7 @@ static bool _attrParseUseNode(void* data, const char* key, const char* value)
unsigned char* array = (unsigned char*)use;
for (unsigned int i = 0; i < sizeof(useTags) / sizeof(useTags[0]); i++) {
if (useTags[i].sz - 1 == sz && !strncmp(useTags[i].tag, key, sz)) {
- *((float*)(array + useTags[i].offset)) = _toFloat(loader->svgParse, value, useTags[i].type);
+ *((float*)(array + useTags[i].offset)) = _toFloat(ctx->parser, value, useTags[i].type);
if (useTags[i].offset == offsetof(SvgUseNode, w)) use->isWidthSet = true;
else if (useTags[i].offset == offsetof(SvgUseNode, h)) use->isHeightSet = true;
@@ -2031,13 +2251,13 @@ static bool _attrParseUseNode(void* data, const char* key, const char* value)
defs = _getDefsNode(node);
nodeFrom = _findNodeById(defs, id);
if (nodeFrom) {
- if (!_findParentById(node, id, loader->doc)) {
+ if (!_findParentById(node, id, ctx->doc)) {
//Check if none of nodeFrom's children are in the cloneNodes list
auto postpone = false;
- INLIST_FOREACH(loader->cloneNodes, pair) {
+ INLIST_FOREACH(ctx->cloneNodes, pair) {
if (_checkPostponed(nodeFrom, pair->node, 1)) {
postpone = true;
- loader->cloneNodes.back(new(tvg::malloc<SvgNodeIdPair>(sizeof(SvgNodeIdPair))) SvgNodeIdPair(node, id));
+ ctx->cloneNodes.back(new (tvg::malloc<SvgNodeIdPair>(sizeof(SvgNodeIdPair))) SvgNodeIdPair(node, id));
break;
}
}
@@ -2055,7 +2275,7 @@ static bool _attrParseUseNode(void* data, const char* key, const char* value)
//some svg export software include <defs> element at the end of the file
//if so the 'from' element won't be found now and we have to repeat finding
//after the whole file is parsed
- loader->cloneNodes.back(new(tvg::malloc<SvgNodeIdPair>(sizeof(SvgNodeIdPair))) SvgNodeIdPair(node, id));
+ ctx->cloneNodes.back(new (tvg::malloc<SvgNodeIdPair>(sizeof(SvgNodeIdPair))) SvgNodeIdPair(node, id));
}
} else {
return _attrParseGNode(data, key, value);
@@ -2063,15 +2283,14 @@ static bool _attrParseUseNode(void* data, const char* key, const char* value)
return true;
}
-
-static SvgNode* _createUseNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createUseNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Use);
+ ctx->parser->node = _createNode(parent, SvgNodeType::Use);
- if (!loader->svgParse->node) return nullptr;
+ if (!ctx->parser->node) return nullptr;
- func(buf, bufLength, _attrParseUseNode, loader);
- return loader->svgParse->node;
+ func(buf, bufLength, _attrParseUseNode, ctx);
+ return ctx->parser->node;
}
@@ -2082,16 +2301,23 @@ static constexpr struct
int sz;
size_t offset;
} textTags[] = {
- {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgTextNode, x)},
- {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgTextNode, y)},
- {"font-size", SvgParserLengthType::Vertical, sizeof("font-size"), offsetof(SvgTextNode, fontSize)}
-};
+ {"x", SvgParserLengthType::Horizontal, sizeof("x"), offsetof(SvgTextNode, x)},
+ {"y", SvgParserLengthType::Vertical, sizeof("y"), offsetof(SvgTextNode, y)},
+ {"dx", SvgParserLengthType::Horizontal, sizeof("dx"), offsetof(SvgTextNode, dx)},
+ {"dy", SvgParserLengthType::Vertical, sizeof("dy"), offsetof(SvgTextNode, dy)}};
+static bool _attrPrescanTextFontSize(void* data, const char* key, const char* value)
+{
+ if (!STR_AS(key, "font-size")) return true;
+ auto ctx = (SvgParserContext*)data;
+ ctx->parser->node->node.text.fontSize = _toFontSize(ctx->parser, value);
+ return true;
+}
static bool _attrParseTextNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto node = loader->svgParse->node;
+ auto ctx = (SvgParserContext*)data;
+ auto node = ctx->parser->node;
auto text = &node->node.text;
unsigned char* array;
@@ -2100,37 +2326,50 @@ static bool _attrParseTextNode(void* data, const char* key, const char* value)
array = (unsigned char*)text;
for (unsigned int i = 0; i < sizeof(textTags) / sizeof(textTags[0]); i++) {
if (textTags[i].sz - 1 == sz && !strncmp(textTags[i].tag, key, sz)) {
- *((float*)(array + textTags[i].offset)) = _toFloat(loader->svgParse, value, textTags[i].type);
+ *((float*)(array + textTags[i].offset)) = _toFloat(ctx->parser, value, textTags[i].type);
return true;
}
}
- if (STR_AS(key, "font-family")) svgUtilReplace(&text->fontFamily, value);
- else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, loader);
- else if (STR_AS(key, "clip-path")) _handleClipPathAttr(loader, node, value);
- else if (STR_AS(key, "mask")) _handleMaskAttr(loader, node, value);
- else if (STR_AS(key, "filter")) _handleFilterAttr(loader, node, value);
+ if (STR_AS(key, "font-size")) text->fontSize = _toFontSize(ctx->parser, value);
+ else if (STR_AS(key, "font-family")) svgUtilReplace(&text->fontFamily, value);
+ else if (STR_AS(key, "style")) return xmlParseW3CAttribute(value, strlen(value), _parseStyleAttr, ctx);
+ else if (STR_AS(key, "clip-path")) _handleClipPathAttr(ctx, node, value);
+ else if (STR_AS(key, "mask")) _handleMaskAttr(ctx, node, value);
+ else if (STR_AS(key, "filter")) _handleFilterAttr(ctx, node, value);
else if (STR_AS(key, "id")) _copyId(&node->id, value);
- else if (STR_AS(key, "class")) _handleCssClassAttr(loader, node, value);
- else return _parseStyleAttr(loader, key, value, false);
+ else if (STR_AS(key, "class")) _handleCssClassAttr(ctx, node, value);
+ else return _parseStyleAttr(ctx, key, value, false);
return true;
}
-
-static SvgNode* _createTextNode(SvgLoaderData* loader, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+static SvgNode* _createTextNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
{
- loader->svgParse->node = _createNode(parent, SvgNodeType::Text);
- if (!loader->svgParse->node) return nullptr;
+ ctx->parser->node = _createNode(parent, SvgNodeType::Text);
+ if (!ctx->parser->node) return nullptr;
- //TODO: support the def font and size as used in a system?
- loader->svgParse->node->node.text.fontSize = 10.0f;
+ ctx->parser->node->node.text.fontSize = DEFAULT_FONT_SIZE;
- func(buf, bufLength, _attrParseTextNode, loader);
+ func(buf, bufLength, _attrPrescanTextFontSize, ctx);
+ func(buf, bufLength, _attrParseTextNode, ctx);
- return loader->svgParse->node;
+ return ctx->parser->node;
}
+static SvgNode* _createTspanNode(SvgParserContext* ctx, SvgNode* parent, const char* buf, unsigned bufLength, parseAttributes func)
+{
+ ctx->parser->node = _createNode(parent, SvgNodeType::Tspan);
+ if (!ctx->parser->node) return nullptr;
+
+ ctx->parser->node->node.text.x = FLT_MAX;
+ ctx->parser->node->node.text.y = FLT_MAX;
+
+ func(buf, bufLength, _attrPrescanTextFontSize, ctx);
+ func(buf, bufLength, _attrParseTextNode, ctx);
+
+ return ctx->parser->node;
+}
static constexpr struct
{
@@ -2148,9 +2387,7 @@ static constexpr struct
{"line", sizeof("line"), _createLineNode},
{"image", sizeof("image"), _createImageNode},
{"text", sizeof("text"), _createTextNode},
- {"feGaussianBlur", sizeof("feGaussianBlur"), _createGaussianBlurNode}
-};
-
+ {"feGaussianBlur", sizeof("feGaussianBlur"), _createGaussianBlurNode}};
static constexpr struct
{
@@ -2165,9 +2402,8 @@ static constexpr struct
{"clipPath", sizeof("clipPath"), _createClipPathNode},
{"style", sizeof("style"), _createCssStyleNode},
{"symbol", sizeof("symbol"), _createSymbolNode},
- {"filter", sizeof("filter"), _createFilterNode}
-};
-
+ {"filter", sizeof("filter"), _createFilterNode},
+ {"pattern", sizeof("pattern"), _createPatternNode}};
#define FIND_FACTORY(Short_Name, Tags_Array) \
static FactoryMethod \
@@ -2201,197 +2437,177 @@ FillSpread _parseSpreadValue(const char* value)
return spread;
}
-
-static void _handleRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
+static void _handleRadialCxAttr(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value)
{
- radial->cx = _gradientToFloat(loader->svgParse, value, radial->isCxPercentage);
- if (!loader->svgParse->gradient.parsedFx) {
+ radial->cx = _gradientToFloat(ctx->parser, value, radial->isCxPercentage);
+ if (!ctx->parser->gradient.parsedFx) {
radial->fx = radial->cx;
radial->isFxPercentage = radial->isCxPercentage;
}
}
-
-static void _handleRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
+static void _handleRadialCyAttr(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value)
{
- radial->cy = _gradientToFloat(loader->svgParse, value, radial->isCyPercentage);
- if (!loader->svgParse->gradient.parsedFy) {
+ radial->cy = _gradientToFloat(ctx->parser, value, radial->isCyPercentage);
+ if (!ctx->parser->gradient.parsedFy) {
radial->fy = radial->cy;
radial->isFyPercentage = radial->isCyPercentage;
}
}
-
-static void _handleRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
+static void _handleRadialFxAttr(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value)
{
- radial->fx = _gradientToFloat(loader->svgParse, value, radial->isFxPercentage);
- loader->svgParse->gradient.parsedFx = true;
+ radial->fx = _gradientToFloat(ctx->parser, value, radial->isFxPercentage);
+ ctx->parser->gradient.parsedFx = true;
}
-
-static void _handleRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
+static void _handleRadialFyAttr(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value)
{
- radial->fy = _gradientToFloat(loader->svgParse, value, radial->isFyPercentage);
- loader->svgParse->gradient.parsedFy = true;
+ radial->fy = _gradientToFloat(ctx->parser, value, radial->isFyPercentage);
+ ctx->parser->gradient.parsedFy = true;
}
-
-static void _handleRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
+static void _handleRadialFrAttr(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value)
{
- radial->fr = _gradientToFloat(loader->svgParse, value, radial->isFrPercentage);
+ radial->fr = _gradientToFloat(ctx->parser, value, radial->isFrPercentage);
}
-
-static void _handleRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value)
+static void _handleRadialRAttr(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value)
{
- radial->r = _gradientToFloat(loader->svgParse, value, radial->isRPercentage);
+ radial->r = _gradientToFloat(ctx->parser, value, radial->isRPercentage);
}
-
-static void _recalcRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcRadialCxAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
- if (userSpace && !radial->isCxPercentage) radial->cx = radial->cx / loader->svgParse->global.w;
+ if (userSpace && !radial->isCxPercentage) radial->cx = radial->cx / ctx->parser->global.w;
}
-
-static void _recalcRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcRadialCyAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
- if (userSpace && !radial->isCyPercentage) radial->cy = radial->cy / loader->svgParse->global.h;
+ if (userSpace && !radial->isCyPercentage) radial->cy = radial->cy / ctx->parser->global.h;
}
-
-static void _recalcRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcRadialFxAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
- if (userSpace && !radial->isFxPercentage) radial->fx = radial->fx / loader->svgParse->global.w;
+ if (userSpace && !radial->isFxPercentage) radial->fx = radial->fx / ctx->parser->global.w;
}
-
-static void _recalcRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcRadialFyAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
- if (userSpace && !radial->isFyPercentage) radial->fy = radial->fy / loader->svgParse->global.h;
+ if (userSpace && !radial->isFyPercentage) radial->fy = radial->fy / ctx->parser->global.h;
}
-
-static void _recalcRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcRadialFrAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
// scaling factor based on the Units paragraph from : https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
- if (userSpace && !radial->isFrPercentage) radial->fr = radial->fr / (sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0));
+ if (userSpace && !radial->isFrPercentage) radial->fr = radial->fr / (sqrtf(powf(ctx->parser->global.h, 2) + powf(ctx->parser->global.w, 2)) / sqrtf(2.0));
}
-
-static void _recalcRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcRadialRAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
// scaling factor based on the Units paragraph from : https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
- if (userSpace && !radial->isRPercentage) radial->r = radial->r / (sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0));
+ if (userSpace && !radial->isRPercentage) radial->r = radial->r / (sqrtf(powf(ctx->parser->global.h, 2) + powf(ctx->parser->global.w, 2)) / sqrtf(2.0));
}
-
-static void _recalcInheritedRadialCxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcInheritedRadialCxAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
if (!radial->isCxPercentage) {
- if (userSpace) radial->cx /= loader->svgParse->global.w;
- else radial->cx *= loader->svgParse->global.w;
+ if (userSpace) radial->cx /= ctx->parser->global.w;
+ else radial->cx *= ctx->parser->global.w;
}
}
-
-static void _recalcInheritedRadialCyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcInheritedRadialCyAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
if (!radial->isCyPercentage) {
- if (userSpace) radial->cy /= loader->svgParse->global.h;
- else radial->cy *= loader->svgParse->global.h;
+ if (userSpace) radial->cy /= ctx->parser->global.h;
+ else radial->cy *= ctx->parser->global.h;
}
}
-
-static void _recalcInheritedRadialFxAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcInheritedRadialFxAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
if (!radial->isFxPercentage) {
- if (userSpace) radial->fx /= loader->svgParse->global.w;
- else radial->fx *= loader->svgParse->global.w;
+ if (userSpace) radial->fx /= ctx->parser->global.w;
+ else radial->fx *= ctx->parser->global.w;
}
}
-
-static void _recalcInheritedRadialFyAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcInheritedRadialFyAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
if (!radial->isFyPercentage) {
- if (userSpace) radial->fy /= loader->svgParse->global.h;
- else radial->fy *= loader->svgParse->global.h;
+ if (userSpace) radial->fy /= ctx->parser->global.h;
+ else radial->fy *= ctx->parser->global.h;
}
}
-
-static void _recalcInheritedRadialFrAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcInheritedRadialFrAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
if (!radial->isFrPercentage) {
- if (userSpace) radial->fr /= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
- else radial->fr *= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
+ if (userSpace) radial->fr /= sqrtf(powf(ctx->parser->global.h, 2) + powf(ctx->parser->global.w, 2)) / sqrtf(2.0);
+ else radial->fr *= sqrtf(powf(ctx->parser->global.h, 2) + powf(ctx->parser->global.w, 2)) / sqrtf(2.0);
}
}
-
-static void _recalcInheritedRadialRAttr(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace)
+static void _recalcInheritedRadialRAttr(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace)
{
if (!radial->isRPercentage) {
- if (userSpace) radial->r /= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
- else radial->r *= sqrtf(powf(loader->svgParse->global.h, 2) + powf(loader->svgParse->global.w, 2)) / sqrtf(2.0);
+ if (userSpace) radial->r /= sqrtf(powf(ctx->parser->global.h, 2) + powf(ctx->parser->global.w, 2)) / sqrtf(2.0);
+ else radial->r *= sqrtf(powf(ctx->parser->global.h, 2) + powf(ctx->parser->global.w, 2)) / sqrtf(2.0);
}
}
static void _inheritRadialCxAttr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->radial->cx = from->radial->cx;
- to->radial->isCxPercentage = from->radial->isCxPercentage;
+ to->radial.cx = from->radial.cx;
+ to->radial.isCxPercentage = from->radial.isCxPercentage;
to->flags = (to->flags | SvgGradientFlags::Cx);
}
static void _inheritRadialCyAttr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->radial->cy = from->radial->cy;
- to->radial->isCyPercentage = from->radial->isCyPercentage;
+ to->radial.cy = from->radial.cy;
+ to->radial.isCyPercentage = from->radial.isCyPercentage;
to->flags = (to->flags | SvgGradientFlags::Cy);
}
static void _inheritRadialFxAttr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->radial->fx = from->radial->fx;
- to->radial->isFxPercentage = from->radial->isFxPercentage;
+ to->radial.fx = from->radial.fx;
+ to->radial.isFxPercentage = from->radial.isFxPercentage;
to->flags = (to->flags | SvgGradientFlags::Fx);
}
static void _inheritRadialFyAttr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->radial->fy = from->radial->fy;
- to->radial->isFyPercentage = from->radial->isFyPercentage;
+ to->radial.fy = from->radial.fy;
+ to->radial.isFyPercentage = from->radial.isFyPercentage;
to->flags = (to->flags | SvgGradientFlags::Fy);
}
static void _inheritRadialFrAttr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->radial->fr = from->radial->fr;
- to->radial->isFrPercentage = from->radial->isFrPercentage;
+ to->radial.fr = from->radial.fr;
+ to->radial.isFrPercentage = from->radial.isFrPercentage;
to->flags = (to->flags | SvgGradientFlags::Fr);
}
static void _inheritRadialRAttr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->radial->r = from->radial->r;
- to->radial->isRPercentage = from->radial->isRPercentage;
+ to->radial.r = from->radial.r;
+ to->radial.isRPercentage = from->radial.isRPercentage;
to->flags = (to->flags | SvgGradientFlags::R);
}
-
-typedef void (*radialMethod)(SvgLoaderData* loader, SvgRadialGradient* radial, const char* value);
+typedef void (*radialMethod)(SvgParserContext* ctx, SvgRadialGradient* radial, const char* value);
typedef void (*radialInheritMethod)(SvgStyleGradient* to, SvgStyleGradient* from);
-typedef void (*radialMethodRecalc)(SvgLoaderData* loader, SvgRadialGradient* radial, bool userSpace);
-
+typedef void (*radialMethodRecalc)(SvgParserContext* ctx, SvgRadialGradient* radial, bool userSpace);
#define RADIAL_DEF(Name, Name1, Flag) \
{ \
@@ -2420,14 +2636,13 @@ static constexpr struct
static bool _attrParseRadialGradientNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto grad = loader->svgParse->styleGrad;
- auto radial = grad->radial;
+ auto ctx = (SvgParserContext*)data;
+ auto grad = ctx->parser->styleGrad;
int sz = strlen(key);
for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
if (radialTags[i].sz - 1 == sz && !strncmp(radialTags[i].tag, key, sz)) {
- radialTags[i].tagHandler(loader, radial, value);
+ radialTags[i].tagHandler(ctx, &grad->radial, value);
grad->flags = (grad->flags | radialTags[i].flag);
return true;
}
@@ -2453,45 +2668,41 @@ static bool _attrParseRadialGradientNode(void* data, const char* key, const char
return true;
}
-
-static SvgStyleGradient* _createRadialGradient(SvgLoaderData* loader, const char* buf, unsigned bufLength)
+static SvgStyleGradient* _createRadialGradient(SvgParserContext* ctx, const char* buf, unsigned bufLength)
{
auto grad = tvg::calloc<SvgStyleGradient>(1, sizeof(SvgStyleGradient));
- loader->svgParse->styleGrad = grad;
+ ctx->parser->styleGrad = grad;
grad->flags = SvgGradientFlags::None;
grad->type = SvgGradientType::Radial;
- grad->radial = tvg::calloc<SvgRadialGradient>(1, sizeof(SvgRadialGradient));
// default values of gradient transformed into global percentage
- grad->radial->cx = 0.5f;
- grad->radial->cy = 0.5f;
- grad->radial->fx = 0.5f;
- grad->radial->fy = 0.5f;
- grad->radial->r = 0.5f;
- grad->radial->isCxPercentage = true;
- grad->radial->isCyPercentage = true;
- grad->radial->isFxPercentage = true;
- grad->radial->isFyPercentage = true;
- grad->radial->isRPercentage = true;
- grad->radial->isFrPercentage = true;
-
- loader->svgParse->gradient.parsedFx = false;
- loader->svgParse->gradient.parsedFy = false;
- xmlParseAttributes(buf, bufLength,
- _attrParseRadialGradientNode, loader);
+ grad->radial.cx = 0.5f;
+ grad->radial.cy = 0.5f;
+ grad->radial.fx = 0.5f;
+ grad->radial.fy = 0.5f;
+ grad->radial.r = 0.5f;
+ grad->radial.isCxPercentage = true;
+ grad->radial.isCyPercentage = true;
+ grad->radial.isFxPercentage = true;
+ grad->radial.isFyPercentage = true;
+ grad->radial.isRPercentage = true;
+ grad->radial.isFrPercentage = true;
+
+ ctx->parser->gradient.parsedFx = false;
+ ctx->parser->gradient.parsedFy = false;
+ xmlParseAttributes(buf, bufLength, _attrParseRadialGradientNode, ctx);
for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
- radialTags[i].tagRecalc(loader, grad->radial, grad->userSpace);
+ radialTags[i].tagRecalc(ctx, &grad->radial, grad->userSpace);
}
- return loader->svgParse->styleGrad;
+ return ctx->parser->styleGrad;
}
-
-static SvgColor* _findLatestColor(const SvgLoaderData* loader)
+static tvg::RGBA* _findLatestColor(const SvgParserContext* ctx)
{
- auto parent = loader->stack.count > 0 ? loader->stack.last() : loader->doc;
+ auto parent = ctx->stack.count > 0 ? ctx->stack.last() : ctx->doc;
while (parent != nullptr) {
if (parent->style->curColorSet) return &parent->style->color;
@@ -2503,21 +2714,21 @@ static SvgColor* _findLatestColor(const SvgLoaderData* loader)
static bool _attrParseStopsStyle(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- auto stop = &loader->svgParse->gradStop;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ auto stop = &ctx->parser->gradStop;
if (STR_AS(key, "stop-opacity")) {
stop->a = _toOpacity(value);
- loader->svgParse->flags = (loader->svgParse->flags | SvgStopStyleFlags::StopOpacity);
+ ctx->parser->flags = (ctx->parser->flags | SvgStopStyleFlags::StopOpacity);
} else if (STR_AS(key, "stop-color")) {
if (STR_AS(value, "currentColor")) {
- if (auto latestColor = _findLatestColor(loader)) {
+ if (auto latestColor = _findLatestColor(ctx)) {
stop->r = latestColor->r;
stop->g = latestColor->g;
stop->b = latestColor->b;
}
} else if (_toColor(value, stop->r, stop->g, stop->b, nullptr)) {
- loader->svgParse->flags = (loader->svgParse->flags | SvgStopStyleFlags::StopColor);
+ ctx->parser->flags = (ctx->parser->flags | SvgStopStyleFlags::StopColor);
}
} else {
return false;
@@ -2529,23 +2740,23 @@ static bool _attrParseStopsStyle(void* data, const char* key, const char* value)
static bool _attrParseStops(void* data, const char* key, const char* value)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
- auto stop = &loader->svgParse->gradStop;
+ SvgParserContext* ctx = (SvgParserContext*)data;
+ auto stop = &ctx->parser->gradStop;
if (STR_AS(key, "offset")) {
stop->offset = _toOffset(value);
} else if (STR_AS(key, "stop-opacity")) {
- if (!(loader->svgParse->flags & SvgStopStyleFlags::StopOpacity)) {
+ if (!(ctx->parser->flags & SvgStopStyleFlags::StopOpacity)) {
stop->a = _toOpacity(value);
}
} else if (STR_AS(key, "stop-color")) {
if (STR_AS(value, "currentColor")) {
- if (auto latestColor = _findLatestColor(loader)) {
+ if (auto latestColor = _findLatestColor(ctx)) {
stop->r = latestColor->r;
stop->g = latestColor->g;
stop->b = latestColor->b;
}
- } else if (!(loader->svgParse->flags & SvgStopStyleFlags::StopColor)) {
+ } else if (!(ctx->parser->flags & SvgStopStyleFlags::StopColor)) {
_toColor(value, stop->r, stop->g, stop->b, nullptr);
}
} else if (STR_AS(key, "style")) {
@@ -2557,127 +2768,113 @@ static bool _attrParseStops(void* data, const char* key, const char* value)
return true;
}
-
-static void _handleLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
+static void _handleLinearX1Attr(SvgParserContext* ctx, SvgLinearGradient* linear, const char* value)
{
- linear->x1 = _gradientToFloat(loader->svgParse, value, linear->isX1Percentage);
+ linear->x1 = _gradientToFloat(ctx->parser, value, linear->isX1Percentage);
}
-
-static void _handleLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
+static void _handleLinearY1Attr(SvgParserContext* ctx, SvgLinearGradient* linear, const char* value)
{
- linear->y1 = _gradientToFloat(loader->svgParse, value, linear->isY1Percentage);
+ linear->y1 = _gradientToFloat(ctx->parser, value, linear->isY1Percentage);
}
-
-static void _handleLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
+static void _handleLinearX2Attr(SvgParserContext* ctx, SvgLinearGradient* linear, const char* value)
{
- linear->x2 = _gradientToFloat(loader->svgParse, value, linear->isX2Percentage);
+ linear->x2 = _gradientToFloat(ctx->parser, value, linear->isX2Percentage);
}
-
-static void _handleLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value)
+static void _handleLinearY2Attr(SvgParserContext* ctx, SvgLinearGradient* linear, const char* value)
{
- linear->y2 = _gradientToFloat(loader->svgParse, value, linear->isY2Percentage);
+ linear->y2 = _gradientToFloat(ctx->parser, value, linear->isY2Percentage);
}
-
-static void _recalcLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcLinearX1Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
- if (userSpace && !linear->isX1Percentage) linear->x1 = linear->x1 / loader->svgParse->global.w;
+ if (userSpace && !linear->isX1Percentage) linear->x1 = linear->x1 / ctx->parser->global.w;
}
-
-static void _recalcLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcLinearY1Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
- if (userSpace && !linear->isY1Percentage) linear->y1 = linear->y1 / loader->svgParse->global.h;
+ if (userSpace && !linear->isY1Percentage) linear->y1 = linear->y1 / ctx->parser->global.h;
}
-
-static void _recalcLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcLinearX2Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
- if (userSpace && !linear->isX2Percentage) linear->x2 = linear->x2 / loader->svgParse->global.w;
+ if (userSpace && !linear->isX2Percentage) linear->x2 = linear->x2 / ctx->parser->global.w;
}
-
-static void _recalcLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcLinearY2Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
- if (userSpace && !linear->isY2Percentage) linear->y2 = linear->y2 / loader->svgParse->global.h;
+ if (userSpace && !linear->isY2Percentage) linear->y2 = linear->y2 / ctx->parser->global.h;
}
-
-static void _recalcInheritedLinearX1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcInheritedLinearX1Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
if (!linear->isX1Percentage) {
- if (userSpace) linear->x1 /= loader->svgParse->global.w;
- else linear->x1 *= loader->svgParse->global.w;
+ if (userSpace) linear->x1 /= ctx->parser->global.w;
+ else linear->x1 *= ctx->parser->global.w;
}
}
-
-static void _recalcInheritedLinearX2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcInheritedLinearX2Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
if (!linear->isX2Percentage) {
- if (userSpace) linear->x2 /= loader->svgParse->global.w;
- else linear->x2 *= loader->svgParse->global.w;
+ if (userSpace) linear->x2 /= ctx->parser->global.w;
+ else linear->x2 *= ctx->parser->global.w;
}
}
-
-static void _recalcInheritedLinearY1Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcInheritedLinearY1Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
if (!linear->isY1Percentage) {
- if (userSpace) linear->y1 /= loader->svgParse->global.h;
- else linear->y1 *= loader->svgParse->global.h;
+ if (userSpace) linear->y1 /= ctx->parser->global.h;
+ else linear->y1 *= ctx->parser->global.h;
}
}
-
-static void _recalcInheritedLinearY2Attr(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace)
+static void _recalcInheritedLinearY2Attr(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace)
{
if (!linear->isY2Percentage) {
- if (userSpace) linear->y2 /= loader->svgParse->global.h;
- else linear->y2 *= loader->svgParse->global.h;
+ if (userSpace) linear->y2 /= ctx->parser->global.h;
+ else linear->y2 *= ctx->parser->global.h;
}
}
static void _inheritLinearX1Attr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->linear->x1 = from->linear->x1;
- to->linear->isX1Percentage = from->linear->isX1Percentage;
+ to->linear.x1 = from->linear.x1;
+ to->linear.isX1Percentage = from->linear.isX1Percentage;
to->flags = (to->flags | SvgGradientFlags::X1);
}
static void _inheritLinearX2Attr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->linear->x2 = from->linear->x2;
- to->linear->isX2Percentage = from->linear->isX2Percentage;
+ to->linear.x2 = from->linear.x2;
+ to->linear.isX2Percentage = from->linear.isX2Percentage;
to->flags = (to->flags | SvgGradientFlags::X2);
}
static void _inheritLinearY1Attr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->linear->y1 = from->linear->y1;
- to->linear->isY1Percentage = from->linear->isY1Percentage;
+ to->linear.y1 = from->linear.y1;
+ to->linear.isY1Percentage = from->linear.isY1Percentage;
to->flags = (to->flags | SvgGradientFlags::Y1);
}
static void _inheritLinearY2Attr(SvgStyleGradient* to, SvgStyleGradient* from)
{
- to->linear->y2 = from->linear->y2;
- to->linear->isY2Percentage = from->linear->isY2Percentage;
+ to->linear.y2 = from->linear.y2;
+ to->linear.isY2Percentage = from->linear.isY2Percentage;
to->flags = (to->flags | SvgGradientFlags::Y2);
}
-
-typedef void (*Linear_Method)(SvgLoaderData* loader, SvgLinearGradient* linear, const char* value);
+typedef void (*Linear_Method)(SvgParserContext* ctx, SvgLinearGradient* linear, const char* value);
typedef void (*Linear_Inherit_Method)(SvgStyleGradient* to, SvgStyleGradient* from);
-typedef void (*Linear_Method_Recalc)(SvgLoaderData* loader, SvgLinearGradient* linear, bool userSpace);
-
+typedef void (*Linear_Method_Recalc)(SvgParserContext* ctx, SvgLinearGradient* linear, bool userSpace);
#define LINEAR_DEF(Name, Name1, Flag) \
{ \
@@ -2704,14 +2901,13 @@ static constexpr struct
static bool _attrParseLinearGradientNode(void* data, const char* key, const char* value)
{
- auto loader = (SvgLoaderData*)data;
- auto grad = loader->svgParse->styleGrad;
- auto linear = grad->linear;
+ auto ctx = (SvgParserContext*)data;
+ auto grad = ctx->parser->styleGrad;
int sz = strlen(key);
for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
if (linear_tags[i].sz - 1 == sz && !strncmp(linear_tags[i].tag, key, sz)) {
- linear_tags[i].tagHandler(loader, linear, value);
+ linear_tags[i].tagHandler(ctx, &grad->linear, value);
grad->flags = (grad->flags | linear_tags[i].flag);
return true;
}
@@ -2737,27 +2933,25 @@ static bool _attrParseLinearGradientNode(void* data, const char* key, const char
return true;
}
-
-static SvgStyleGradient* _createLinearGradient(SvgLoaderData* loader, const char* buf, unsigned bufLength)
+static SvgStyleGradient* _createLinearGradient(SvgParserContext* ctx, const char* buf, unsigned bufLength)
{
auto grad = tvg::calloc<SvgStyleGradient>(1, sizeof(SvgStyleGradient));
- loader->svgParse->styleGrad = grad;
+ ctx->parser->styleGrad = grad;
grad->flags = SvgGradientFlags::None;
grad->type = SvgGradientType::Linear;
- grad->linear = tvg::calloc<SvgLinearGradient>(1, sizeof(SvgLinearGradient));
// default value of x2 is 100% - transformed to the global percentage
- grad->linear->x2 = 1.0f;
- grad->linear->isX2Percentage = true;
+ grad->linear.x2 = 1.0f;
+ grad->linear.isX2Percentage = true;
- xmlParseAttributes(buf, bufLength, _attrParseLinearGradientNode, loader);
+ xmlParseAttributes(buf, bufLength, _attrParseLinearGradientNode, ctx);
for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
- linear_tags[i].tagRecalc(loader, grad->linear, grad->userSpace);
+ linear_tags[i].tagRecalc(ctx, &grad->linear, grad->userSpace);
}
- return loader->svgParse->styleGrad;
+ return ctx->parser->styleGrad;
}
@@ -2803,8 +2997,7 @@ static void _cloneGradStops(Array<Fill::ColorStop>& dst, const Array<Fill::Color
}
}
-
-static void _inheritGradient(SvgLoaderData* loader, SvgStyleGradient* to, SvgStyleGradient* from)
+static void _inheritGradient(SvgParserContext* ctx, SvgStyleGradient* to, SvgStyleGradient* from)
{
if (!to || !from) return;
@@ -2826,19 +3019,12 @@ static void _inheritGradient(SvgLoaderData* loader, SvgStyleGradient* to, SvgSty
if (to->type == SvgGradientType::Linear) {
for (unsigned int i = 0; i < sizeof(linear_tags) / sizeof(linear_tags[0]); i++) {
bool coordSet = to->flags & linear_tags[i].flag;
- if (!(to->flags & linear_tags[i].flag) && (from->flags & linear_tags[i].flag)) {
- linear_tags[i].tagInheritHandler(to, from);
- }
-
+ if (!(to->flags & linear_tags[i].flag) && (from->flags & linear_tags[i].flag)) linear_tags[i].tagInheritHandler(to, from);
//GradUnits not set directly, coord set
- if (!gradUnitSet && coordSet) {
- linear_tags[i].tagRecalc(loader, to->linear, to->userSpace);
- }
+ if (!gradUnitSet && coordSet) linear_tags[i].tagRecalc(ctx, &to->linear, to->userSpace);
//GradUnits set, coord not set directly
if (to->userSpace == from->userSpace) continue;
- if (gradUnitSet && !coordSet) {
- linear_tags[i].tagInheritedRecalc(loader, to->linear, to->userSpace);
- }
+ if (gradUnitSet && !coordSet) linear_tags[i].tagInheritedRecalc(ctx, &to->linear, to->userSpace);
}
} else if (to->type == SvgGradientType::Radial) {
for (unsigned int i = 0; i < sizeof(radialTags) / sizeof(radialTags[0]); i++) {
@@ -2849,10 +3035,10 @@ static void _inheritGradient(SvgLoaderData* loader, SvgStyleGradient* to, SvgSty
//GradUnits not set directly, coord set
if (!gradUnitSet && coordSet) {
- radialTags[i].tagRecalc(loader, to->radial, to->userSpace);
+ radialTags[i].tagRecalc(ctx, &to->radial, to->userSpace);
//If fx and fy are not set, set cx and cy.
- if (STR_AS(radialTags[i].tag, "cx") && !(to->flags & SvgGradientFlags::Fx)) to->radial->fx = to->radial->cx;
- if (STR_AS(radialTags[i].tag, "cy") && !(to->flags & SvgGradientFlags::Fy)) to->radial->fy = to->radial->cy;
+ if (STR_AS(radialTags[i].tag, "cx") && !(to->flags & SvgGradientFlags::Fx)) to->radial.fx = to->radial.cx;
+ if (STR_AS(radialTags[i].tag, "cy") && !(to->flags & SvgGradientFlags::Fy)) to->radial.fy = to->radial.cy;
}
//GradUnits set, coord not set directly
if (to->userSpace == from->userSpace) continue;
@@ -2860,7 +3046,7 @@ static void _inheritGradient(SvgLoaderData* loader, SvgStyleGradient* to, SvgSty
//If fx and fx are not set, do not call recalc.
if (STR_AS(radialTags[i].tag, "fx") && !(to->flags & SvgGradientFlags::Fx)) continue;
if (STR_AS(radialTags[i].tag, "fy") && !(to->flags & SvgGradientFlags::Fy)) continue;
- radialTags[i].tagInheritedRecalc(loader, to->radial, to->userSpace);
+ radialTags[i].tagInheritedRecalc(ctx, &to->radial, to->userSpace);
}
}
}
@@ -2886,13 +3072,8 @@ static SvgStyleGradient* _cloneGradient(SvgStyleGradient* from)
*grad->transform = *from->transform;
}
- if (grad->type == SvgGradientType::Linear) {
- grad->linear = tvg::calloc<SvgLinearGradient>(1, sizeof(SvgLinearGradient));
- memcpy(grad->linear, from->linear, sizeof(SvgLinearGradient));
- } else if (grad->type == SvgGradientType::Radial) {
- grad->radial = tvg::calloc<SvgRadialGradient>(1, sizeof(SvgRadialGradient));
- memcpy(grad->radial, from->radial, sizeof(SvgRadialGradient));
- }
+ if (grad->type == SvgGradientType::Linear) grad->linear = from->linear;
+ else if (grad->type == SvgGradientType::Radial) grad->radial = from->radial;
_cloneGradStops(grad->stops, from->stops);
@@ -2902,6 +3083,13 @@ static SvgStyleGradient* _cloneGradient(SvgStyleGradient* from)
static void _styleInherit(SvgStyleProperty* child, const SvgStyleProperty* parent)
{
+ auto parentWeight = parent ? parent->fontWeight : SvgFontWeight::Normal;
+ if (!(child->flags & SvgStyleFlags::FontWeight) || child->fontWeight == SvgFontWeight::Inherit) child->fontWeight = parentWeight;
+ else if (child->fontWeight == SvgFontWeight::Bolder) child->fontWeight = parentWeight <= SvgFontWeight::Weight300 ? SvgFontWeight::Normal : parentWeight <= SvgFontWeight::Weight500 ? SvgFontWeight::Bold
+ : SvgFontWeight::Weight900;
+ else if (child->fontWeight == SvgFontWeight::Lighter) child->fontWeight = parentWeight <= SvgFontWeight::Weight500 ? SvgFontWeight::Weight100 : parentWeight <= SvgFontWeight::Bold ? SvgFontWeight::Normal
+ : SvgFontWeight::Bold;
+
if (!parent) return;
//Inherit the property of parent if not present in child.
@@ -2943,6 +3131,10 @@ static void _styleInherit(SvgStyleProperty* child, const SvgStyleProperty* paren
if (!(child->stroke.flags & SvgStrokeFlags::Cap)) child->stroke.cap = parent->stroke.cap;
if (!(child->stroke.flags & SvgStrokeFlags::Join)) child->stroke.join = parent->stroke.join;
if (!(child->stroke.flags & SvgStrokeFlags::Miterlimit)) child->stroke.miterlimit = parent->stroke.miterlimit;
+ if (!(child->flags & SvgStyleFlags::TextAnchor)) child->textAnchor = parent->textAnchor;
+ if (!(child->flags & SvgStyleFlags::DominantBaseline)) child->dominantBaseline = parent->dominantBaseline;
+ if (!(child->flags & SvgStyleFlags::LetterSpacing)) child->letterSpacing = parent->letterSpacing;
+ if (!(child->flags & SvgStyleFlags::WordSpacing)) child->wordSpacing = parent->wordSpacing;
}
@@ -2958,6 +3150,19 @@ static void _styleCopy(SvgStyleProperty* to, const SvgStyleProperty* from)
if (from->flags & SvgStyleFlags::Opacity) to->opacity = from->opacity;
if (from->flags & SvgStyleFlags::PaintOrder) to->paintOrder = from->paintOrder;
if (from->flags & SvgStyleFlags::Display) to->display = from->display;
+ if (from->flags & SvgStyleFlags::BlendMode) to->blendMode = from->blendMode;
+ if (from->flags & SvgStyleFlags::TextAnchor) to->textAnchor = from->textAnchor;
+ if (from->flags & SvgStyleFlags::AlignmentBaseline) to->alignmentBaseline = from->alignmentBaseline;
+ if (from->flags & SvgStyleFlags::DominantBaseline) to->dominantBaseline = from->dominantBaseline;
+ if (from->flags & SvgStyleFlags::FontWeight) to->fontWeight = from->fontWeight;
+ if (from->flags & SvgStyleFlags::LetterSpacing) {
+ to->letterSpacing = from->letterSpacing;
+ to->letterSpacingRelative = from->letterSpacingRelative;
+ }
+ if (from->flags & SvgStyleFlags::WordSpacing) {
+ to->wordSpacing = from->wordSpacing;
+ to->wordSpacingRelative = from->wordSpacingRelative;
+ }
//Fill
to->fill.flags = (to->fill.flags | from->fill.flags);
@@ -3056,9 +3261,21 @@ static void _copyAttr(SvgNode* to, const SvgNode* from)
to->node.use = from->node.use;
break;
}
+ case SvgNodeType::Pattern: {
+ to->node.pattern = from->node.pattern;
+ to->node.pattern.applying = false;
+ if (from->node.pattern.transform) {
+ to->node.pattern.transform = tvg::malloc<Matrix>(sizeof(Matrix));
+ *to->node.pattern.transform = *from->node.pattern.transform;
+ }
+ break;
+ }
+ case SvgNodeType::Tspan:
case SvgNodeType::Text: {
to->node.text.x = from->node.text.x;
to->node.text.y = from->node.text.y;
+ to->node.text.dx = from->node.text.dx;
+ to->node.text.dy = from->node.text.dy;
to->node.text.fontSize = from->node.text.fontSize;
svgUtilReplace(&to->node.text.text, from->node.text.text);
svgUtilReplace(&to->node.text.fontFamily, from->node.text.fontFamily);
@@ -3097,8 +3314,18 @@ static void _cloneNode(SvgNode* from, SvgNode* parent, int depth)
static void _clonePostponedNodes(Inlist<SvgNodeIdPair>* cloneNodes, SvgNode* doc)
{
+ uint32_t cloneNodesCount = cloneNodes->count;
+ uint32_t postponeCount = 0;
auto nodeIdPair = cloneNodes->front();
while (nodeIdPair) {
+ if (postponeCount >= cloneNodesCount) {
+ do {
+ TVGERR("SVG", "Circular use reference detected, discarding '%s'.", nodeIdPair->id ? nodeIdPair->id : "");
+ tvg::free(nodeIdPair->id);
+ tvg::free(nodeIdPair);
+ } while ((nodeIdPair = cloneNodes->front()));
+ break;
+ }
if (!_findParentById(nodeIdPair->node, nodeIdPair->id, doc)) {
//Check if none of nodeFrom's children are in the cloneNodes list
auto postpone = false;
@@ -3121,64 +3348,108 @@ static void _clonePostponedNodes(Inlist<SvgNodeIdPair>* cloneNodes, SvgNode* doc
}
tvg::free(nodeIdPair->id);
tvg::free(nodeIdPair);
+ postponeCount = 0;
+ --cloneNodesCount;
+ } else {
+ ++postponeCount;
}
} else {
TVGLOG("SVG", "%s is ancestor element. This reference is invalid.", nodeIdPair->id);
tvg::free(nodeIdPair->id);
tvg::free(nodeIdPair);
+ postponeCount = 0;
+ --cloneNodesCount;
}
nodeIdPair = cloneNodes->front();
}
}
+static int _svgLoaderParserXmlTagName(const char* content, char* tagName, unsigned int tagNameSize)
+{
+ content = svgUtilSkipWhiteSpace(content, nullptr);
+ auto itr = content;
+ while (itr && *itr != '>') itr++;
+ if (!itr) return -1;
+
+ int sz = itr - content;
+ while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
+ if ((unsigned int)sz >= tagNameSize) sz = tagNameSize - 1;
+ strncpy(tagName, content, sz);
+ tagName[sz] = '\0';
+ return sz;
+}
-static void _svgLoaderParserXmlClose(SvgLoaderData* loader, const char* content, unsigned int length)
+static bool _hasTspanChild(const SvgNode* node, const SvgNode* exclude = nullptr)
{
- const char* itr = nullptr;
- int sz = length;
- char tagName[20] = "";
+ ARRAY_FOREACH(p, node->child) {
+ if (*p == exclude) continue;
+ if ((*p)->type == SvgNodeType::Tspan && ((*p)->node.text.text || !(*p)->child.empty())) return true;
+ }
+ return false;
+}
- content = svgUtilSkipWhiteSpace(content, nullptr);
- itr = content;
- while ((itr != nullptr) && *itr != '>') itr++;
- if (itr) {
- sz = itr - content;
- while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
- if ((unsigned int)sz >= sizeof(tagName)) sz = sizeof(tagName) - 1;
- strncpy(tagName, content, sz);
- tagName[sz] = '\0';
+static void _spliceTspanClose(SvgParserContext* ctx)
+{
+ auto cur = ctx->parser->node;
+ if (!cur || cur->type != SvgNodeType::Tspan) return;
+
+ auto& t = cur->node.text;
+ bool unpositioned = (t.x == FLT_MAX && t.y == FLT_MAX && t.dx == 0.0f && t.dy == 0.0f);
+ bool noOverride = (t.fontSize <= 0.0f && !t.fontFamily && cur->xmlSpace == SvgXmlSpace::None && cur->style->flags == SvgStyleFlags::None && cur->style->fill.flags == SvgFillFlags::None);
+
+ auto splice = t.text && unpositioned && noOverride && cur->parent && cur->child.empty() && !_hasTspanChild(cur->parent, cur);
+
+ if (splice) {
+ auto& parentText = cur->parent->node.text;
+ parentText.text = append(parentText.text, t.text, strlen(t.text));
+ tvg::free(t.text);
+ t.text = nullptr;
+ }
+ ctx->parser->node = cur->parent;
+}
+
+static void _svgLoaderParserXmlClose(SvgParserContext* ctx, const char* content, unsigned int length)
+{
+ char tagName[20] = "";
+ auto sz = _svgLoaderParserXmlTagName(content, tagName, sizeof(tagName));
+ if (sz < 0) return;
+
+ if (ctx->gradientStack.count > 0 && !ctx->gradientStack.last()) {
+ ctx->gradientStack.pop();
+ return;
}
- else return;
for (unsigned int i = 0; i < sizeof(groupTags) / sizeof(groupTags[0]); i++) {
if (!strncmp(tagName, groupTags[i].tag, sz)) {
- loader->stack.pop();
+ ctx->stack.pop();
break;
}
}
for (unsigned int i = 0; i < sizeof(gradientTags) / sizeof(gradientTags[0]); i++) {
if (!strncmp(tagName, gradientTags[i].tag, sz)) {
- loader->gradientStack.pop();
+ ctx->gradientStack.pop();
break;
}
}
+ if (ctx->openedTag == OpenedTagType::Text && STR_AS(tagName, "tspan")) {
+ _spliceTspanClose(ctx);
+ return;
+ }
+
for (unsigned int i = 0; i < sizeof(graphicsTags) / sizeof(graphicsTags[0]); i++) {
if (!strncmp(tagName, graphicsTags[i].tag, sz)) {
- loader->currentGraphicsNode = nullptr;
- if (!strncmp(tagName, "text", 4)) loader->openedTag = OpenedTagType::Other;
- loader->stack.pop();
+ ctx->currentGraphicsNode = nullptr;
+ if (!strncmp(tagName, "text", 4)) ctx->openedTag = OpenedTagType::Other;
+ ctx->stack.pop();
break;
}
}
-
- loader->level--;
}
-
-static void _svgLoaderParserXmlOpen(SvgLoaderData* loader, const char* content, unsigned int length, bool empty)
+static void _svgLoaderParserXmlOpen(SvgParserContext* ctx, const char* content, unsigned int length, bool empty)
{
const char* attrs = nullptr;
int attrsLength = 0;
@@ -3187,102 +3458,123 @@ static void _svgLoaderParserXmlOpen(SvgLoaderData* loader, const char* content,
FactoryMethod method;
GradientFactoryMethod gradientMethod;
SvgNode *node = nullptr, *parent = nullptr;
- loader->level++;
attrs = xmlFindAttributesTag(content, length);
- if (!attrs) {
- //Parse the empty tag
- attrs = content;
- while ((attrs != nullptr) && *attrs != '>') attrs++;
- if (empty) attrs--;
+ //Find out the tag name starting from content till sz length
+ sz = attrs - content;
+ while ((sz > 0) && (isspace((unsigned char)content[sz - 1]))) sz--;
+ if ((unsigned)sz >= sizeof(tagName)) return;
+ strncpy(tagName, content, sz);
+ tagName[sz] = '\0';
+ attrsLength = length - sz;
+
+ if (ctx->gradientStack.count > 0 && !ctx->gradientStack.last()) {
+ if (!empty) ctx->gradientStack.push(nullptr);
+ return;
+ }
+
+ if (STR_AS(tagName, "stop")) {
+ if (ctx->gradientStack.empty()) {
+ TVGLOG("SVG", "Ignoring <%s> declared outside of a gradient element", tagName);
+ if (!empty) ctx->gradientStack.push(nullptr);
+ return;
+ }
+ ctx->parser->gradStop = {0.0f, 0, 0, 0, 255};
+ ctx->parser->flags = SvgStopStyleFlags::StopDefault;
+ xmlParseAttributes(attrs, attrsLength, _attrParseStops, ctx);
+ ctx->gradientStack.last()->stops.push(ctx->parser->gradStop);
+ if (!empty) ctx->gradientStack.push(nullptr);
+ return;
}
- if (attrs) {
- //Find out the tag name starting from content till sz length
- sz = attrs - content;
- while ((sz > 0) && (isspace(content[sz - 1]))) sz--;
- if ((unsigned)sz >= sizeof(tagName)) return;
- strncpy(tagName, content, sz);
- tagName[sz] = '\0';
- attrsLength = length - sz;
+ if (ctx->gradientStack.count > 0) {
+ TVGLOG("SVG", "Ignoring <%s> declared inside a gradient element", tagName);
+ if (!empty) ctx->gradientStack.push(nullptr);
+ return;
}
if ((method = _findGroupFactory(tagName))) {
//Group
if (empty) return;
- if (!loader->doc) {
+ if (!ctx->doc) {
if (!STR_AS(tagName, "svg")) return; //Not a valid svg document
- node = method(loader, nullptr, attrs, attrsLength, xmlParseAttributes);
- loader->doc = node;
+ node = method(ctx, nullptr, attrs, attrsLength, xmlParseAttributes);
+ ctx->doc = node;
} else {
- if (STR_AS(tagName, "svg")) return; //Already loaded <svg>(SvgNodeType::Doc) tag
- if (loader->stack.count > 0) parent = loader->stack.last();
- else parent = loader->doc;
+ if (STR_AS(tagName, "svg")) {
+ TVGLOG("SVG", "Nested <svg> element is not supported.");
+ method = _createGNode;
+ }
+ if (ctx->stack.count > 0) parent = ctx->stack.last();
+ else parent = ctx->doc;
if (STR_AS(tagName, "style")) {
- // TODO: For now only the first style node is saved. After the css id selector
- // is introduced this if condition shouldn't be necessary any more
- if (!loader->cssStyle) {
- node = method(loader, nullptr, attrs, attrsLength, xmlParseAttributes);
- loader->cssStyle = node;
- loader->doc->node.doc.style = node;
- loader->openedTag = OpenedTagType::Style;
- }
+ if (!ctx->cssStyle) {
+ node = method(ctx, nullptr, attrs, attrsLength, xmlParseAttributes);
+ ctx->cssStyle = node;
+ ctx->doc->node.doc.style = node;
+ } else node = ctx->cssStyle;
+ ctx->openedTag = OpenedTagType::Style;
} else {
- node = method(loader, parent, attrs, attrsLength, xmlParseAttributes);
+ node = method(ctx, parent, attrs, attrsLength, xmlParseAttributes);
}
}
if (!node) return;
if (node->type != SvgNodeType::Defs || !empty) {
- loader->stack.push(node);
+ ctx->stack.push(node);
}
+ } else if (ctx->openedTag == OpenedTagType::Text && STR_AS(tagName, "tspan")) {
+ parent = ctx->parser->node;
+ node = _createTspanNode(ctx, parent, attrs, attrsLength, xmlParseAttributes);
+ if (empty) ctx->parser->node = parent;
} else if ((method = _findGraphicsFactory(tagName))) {
- if (loader->stack.count > 0) parent = loader->stack.last();
- else parent = loader->doc;
- node = method(loader, parent, attrs, attrsLength, xmlParseAttributes);
+ if (ctx->stack.count > 0) parent = ctx->stack.last();
+ else parent = ctx->doc;
+ node = method(ctx, parent, attrs, attrsLength, xmlParseAttributes);
if (node && !empty) {
- if (STR_AS(tagName, "text")) loader->openedTag = OpenedTagType::Text;
- auto defs = _createDefsNode(loader, nullptr, nullptr, 0, nullptr);
- loader->stack.push(defs);
- loader->currentGraphicsNode = node;
+ if (STR_AS(tagName, "text")) ctx->openedTag = OpenedTagType::Text;
+ auto defs = _createDefsNode(ctx, nullptr, nullptr, 0, nullptr);
+ ctx->stack.push(defs);
+ ctx->currentGraphicsNode = node;
}
} else if ((gradientMethod = _findGradientFactory(tagName))) {
SvgStyleGradient* gradient;
- gradient = gradientMethod(loader, attrs, attrsLength);
+ gradient = gradientMethod(ctx, attrs, attrsLength);
//Gradients do not allow nested declarations, so only the earliest declared Gradient is valid.
- if (loader->gradientStack.count == 0) {
+ if (ctx->gradientStack.count == 0) {
//FIXME: The current parsing structure does not distinguish end tags.
// There is no way to know if the currently parsed gradient is in defs.
// If a gradient is declared outside of defs after defs is set, it is included in the gradients of defs.
// But finally, the loader has a gradient style list regardless of defs.
// This is only to support this when multiple gradients are declared, even if no defs are declared.
// refer to: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs
- if (loader->def && loader->doc->node.doc.defs) {
- loader->def->node.defs.gradients.push(gradient);
+ if (ctx->def && ctx->doc->node.doc.defs) {
+ ctx->def->node.defs.gradients.push(gradient);
} else {
- loader->gradients.push(gradient);
+ ctx->gradients.push(gradient);
}
}
- if (!empty) loader->gradientStack.push(gradient);
- } else if (STR_AS(tagName, "stop")) {
- if (loader->gradientStack.count == 0) {
- TVGLOG("SVG", "Stop element is used outside of the Gradient element");
- return;
- }
- /* default value for opacity */
- loader->svgParse->gradStop = {0.0f, 0, 0, 0, 255};
- loader->svgParse->flags = SvgStopStyleFlags::StopDefault;
- xmlParseAttributes(attrs, attrsLength, _attrParseStops, loader);
- loader->gradientStack.last()->stops.push(loader->svgParse->gradStop);
+ if (!empty) ctx->gradientStack.push(gradient);
} else {
if (!isIgnoreUnsupportedLogElements(tagName)) TVGLOG("SVG", "Unsupported elements used [Elements: %s]", tagName);
}
}
-
-static void _svgLoaderParserText(SvgLoaderData* loader, const char* content, unsigned int length)
+static void _svgLoaderParserText(SvgParserContext* ctx, const char* content, unsigned int length)
{
- auto& text = loader->svgParse->node->node.text;
+ auto node = ctx->parser->node;
+
+ if (node->type != SvgNodeType::Text && node->type != SvgNodeType::Tspan) return;
+
+ if (_hasTspanChild(node)) {
+ auto run = _createNode(node, SvgNodeType::Tspan);
+ run->node.text.x = FLT_MAX;
+ run->node.text.y = FLT_MAX;
+ run->node.text.text = append(run->node.text.text, content, length);
+ return;
+ }
+
+ auto& text = node->node.text;
text.text = append(text.text, content, length);
}
@@ -3378,11 +3670,16 @@ static void _free(SvgNode* node)
tvg::free(node->node.image.href);
break;
}
+ case SvgNodeType::Tspan:
case SvgNodeType::Text: {
tvg::free(node->node.text.text);
tvg::free(node->node.text.fontFamily);
break;
}
+ case SvgNodeType::Pattern: {
+ tvg::free(node->node.pattern.transform);
+ break;
+ }
default: {
break;
}
@@ -3402,6 +3699,7 @@ static bool _cssApplyClass(SvgNode* node, const char* classString, SvgNode* styl
tempNode->style = tvg::calloc<SvgStyleProperty>(1, sizeof(SvgStyleProperty));
tempNode->type = node->type;
tempNode->style->opacity = 255;
+ tempNode->style->color.a = 255;
tempNode->style->fill.opacity = 255;
tempNode->style->stroke.opacity = 255;
@@ -3450,13 +3748,12 @@ static bool _cssApplyClass(SvgNode* node, const char* classString, SvgNode* styl
static void _cssApplyStyleToPostponeds(Array<SvgNodeIdPair>& postponeds, SvgNode* style)
{
ARRAY_FOREACH(p, postponeds) {
- auto nodeIdPair = *p;
- _cssApplyClass(nodeIdPair.node, nodeIdPair.id, style);
+ auto node = p->node;
+ _cssApplyClass(node, node->style->cssClass, style);
}
}
-
-static void _svgLoaderParserXmlCssStyle(SvgLoaderData* loader, const char* content, unsigned int length)
+static void _svgLoaderParserXmlCssStyle(SvgParserContext* ctx, const char* content, unsigned int length)
{
char* tag;
char* name;
@@ -3469,9 +3766,9 @@ static void _svgLoaderParserXmlCssStyle(SvgLoaderData* loader, const char* conte
while (auto next = xmlParseCSSAttribute(content, length, &tag, &name, &attrs, &attrsLength)) {
if ((method = _findGroupFactory(tag))) {
- if ((node = method(loader, loader->cssStyle, attrs, attrsLength, xmlParseW3CAttribute))) _copyId(&node->id, name);
+ if ((node = method(ctx, ctx->cssStyle, attrs, attrsLength, xmlParseW3CAttribute))) _copyId(&node->id, name);
} else if ((method = _findGraphicsFactory(tag))) {
- if ((node = method(loader, loader->cssStyle, attrs, attrsLength, xmlParseW3CAttribute))) _copyId(&node->id, name);
+ if ((node = method(ctx, ctx->cssStyle, attrs, attrsLength, xmlParseW3CAttribute))) _copyId(&node->id, name);
} else if ((gradientMethod = _findGradientFactory(tag))) {
TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
} else if (STR_AS(tag, "stop")) {
@@ -3483,18 +3780,18 @@ static void _svgLoaderParserXmlCssStyle(SvgLoaderData* loader, const char* conte
while (id) {
if (*id == '.') id++;
- if (auto cssNode = cssFindStyleNode(loader->cssStyle, id)) {
- auto oldNode = loader->svgParse->node;
- loader->svgParse->node = cssNode;
- xmlParseW3CAttribute(attrs, attrsLength, _attrParseCssStyleNode, loader);
- loader->svgParse->node = oldNode;
+ if (auto cssNode = cssFindStyleNode(ctx->cssStyle, id)) {
+ auto oldNode = ctx->parser->node;
+ ctx->parser->node = cssNode;
+ xmlParseW3CAttribute(attrs, attrsLength, _attrParseCssStyleNode, ctx);
+ ctx->parser->node = oldNode;
} else {
- if ((node = _createCssStyleNode(loader, loader->cssStyle, attrs, attrsLength, xmlParseW3CAttribute))) _copyId(&node->id, id);
+ if ((node = _createCssStyleNode(ctx, ctx->cssStyle, attrs, attrsLength, xmlParseW3CAttribute))) _copyId(&node->id, id);
}
id = _parseName(nullptr, ",", &tokPtr);
}
} else if (STR_AS(tag, "@font-face")) { //css at-rule specifying font
- _createFontFace(loader, attrs, attrsLength, xmlParseW3CAttribute);
+ _createFontFace(ctx, attrs, attrsLength, xmlParseW3CAttribute);
} else if (!isIgnoreUnsupportedLogElements(tag)) {
TVGLOG("SVG", "Unsupported elements used in the internal CSS style sheets [Elements: %s]", tag);
}
@@ -3505,31 +3802,31 @@ static void _svgLoaderParserXmlCssStyle(SvgLoaderData* loader, const char* conte
tvg::free(tag);
tvg::free(name);
}
- loader->openedTag = OpenedTagType::Other;
+ ctx->openedTag = OpenedTagType::Other;
}
static bool _svgLoaderParser(void* data, XMLType type, const char* content, unsigned int length)
{
- SvgLoaderData* loader = (SvgLoaderData*)data;
+ SvgParserContext* ctx = (SvgParserContext*)data;
switch (type) {
case XMLType::Open: {
- _svgLoaderParserXmlOpen(loader, content, length, false);
+ _svgLoaderParserXmlOpen(ctx, content, length, false);
break;
}
case XMLType::OpenEmpty: {
- _svgLoaderParserXmlOpen(loader, content, length, true);
+ _svgLoaderParserXmlOpen(ctx, content, length, true);
break;
}
case XMLType::Close: {
- _svgLoaderParserXmlClose(loader, content, length);
+ _svgLoaderParserXmlClose(ctx, content, length);
break;
}
case XMLType::Data:
case XMLType::CData: {
- if (loader->openedTag == OpenedTagType::Style) _svgLoaderParserXmlCssStyle(loader, content, length);
- else if (loader->openedTag == OpenedTagType::Text) _svgLoaderParserText(loader, content, length);
+ if (ctx->openedTag == OpenedTagType::Style) _svgLoaderParserXmlCssStyle(ctx, content, length);
+ else if (ctx->openedTag == OpenedTagType::Text) _svgLoaderParserText(ctx, content, length);
break;
}
case XMLType::DoctypeChild: {
@@ -3552,15 +3849,22 @@ static bool _svgLoaderParser(void* data, XMLType type, const char* content, unsi
static void _updateStyle(SvgNode* node, SvgStyleProperty* parentStyle)
{
_styleInherit(node->style, parentStyle);
+ if (node->style->letterSpacingRelative) {
+ node->style->letterSpacing *= _findEmBaseFontSize(node);
+ node->style->letterSpacingRelative = false;
+ }
+ if (node->style->wordSpacingRelative) {
+ node->style->wordSpacing *= _findEmBaseFontSize(node);
+ node->style->wordSpacingRelative = false;
+ }
ARRAY_FOREACH(p, node->child) {
_updateStyle(*p, node->style);
}
}
-
-static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyleGradient*>* gradients)
+static void _updateGradient(SvgParserContext* ctx, SvgNode* node, Array<SvgStyleGradient*>* gradients)
{
- auto duplicate = [&](SvgLoaderData* loader, Array<SvgStyleGradient*>* gradients, const char* id) -> SvgStyleGradient* {
+ auto duplicate = [&](SvgParserContext* ctx, Array<SvgStyleGradient*>* gradients, const char* id) -> SvgStyleGradient* {
SvgStyleGradient* result = nullptr;
ARRAY_FOREACH(p, *gradients) {
@@ -3572,7 +3876,7 @@ static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyle
if (result && result->ref) {
ARRAY_FOREACH(p, *gradients) {
if ((*p)->id && STR_AS((*p)->id, result->ref)) {
- _inheritGradient(loader, result, *p);
+ _inheritGradient(ctx, result, *p);
break;
}
}
@@ -3582,11 +3886,11 @@ static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyle
if (node->child.count > 0) {
ARRAY_FOREACH(p, node->child) {
- _updateGradient(loader, *p, gradients);
+ _updateGradient(ctx, *p, gradients);
}
} else {
if (node->style->fill.paint.url) {
- auto newGrad = duplicate(loader, gradients, node->style->fill.paint.url);
+ auto newGrad = duplicate(ctx, gradients, node->style->fill.paint.url);
if (newGrad) {
if (node->style->fill.paint.gradient) {
node->style->fill.paint.gradient->clear();
@@ -3596,7 +3900,7 @@ static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyle
}
}
if (node->style->stroke.paint.url) {
- auto newGrad = duplicate(loader, gradients, node->style->stroke.paint.url);
+ auto newGrad = duplicate(ctx, gradients, node->style->stroke.paint.url);
if (newGrad) {
if (node->style->stroke.paint.gradient) {
node->style->stroke.paint.gradient->clear();
@@ -3608,6 +3912,24 @@ static void _updateGradient(SvgLoaderData* loader, SvgNode* node, Array<SvgStyle
}
}
+static void _updatePattern(SvgNode* node, SvgNode* root, SvgNode* defs)
+{
+ auto lookup = [&](const char* url) -> SvgNode* {
+ SvgNode* p = nullptr;
+ if (defs) p = _findNodeById(defs, url);
+ if (!p) p = _findNodeById(root, url);
+ if (p && p->type != SvgNodeType::Pattern) return nullptr;
+ return p;
+ };
+
+ if (node->style) {
+ auto& fill = node->style->fill.paint;
+ if (fill.url && !fill.gradient && !fill.pattern) fill.pattern = lookup(fill.url);
+ }
+ ARRAY_FOREACH(c, node->child) {
+ _updatePattern(*c, root, defs);
+ }
+}
static void _updateComposite(SvgNode* node, SvgNode* root)
{
@@ -3637,8 +3959,7 @@ static void _updateFilter(SvgNode* node, SvgNode* root)
}
}
-
-static bool _svgLoaderParserForValidCheckXmlOpen(SvgLoaderData* loader, const char* content, unsigned int length)
+static bool _svgLoaderParserForValidCheckXmlOpen(SvgParserContext* ctx, const char* content, unsigned int length)
{
const char* attrs = nullptr;
int sz = length;
@@ -3646,30 +3967,21 @@ static bool _svgLoaderParserForValidCheckXmlOpen(SvgLoaderData* loader, const ch
FactoryMethod method;
SvgNode *node = nullptr;
int attrsLength = 0;
- loader->level++;
attrs = xmlFindAttributesTag(content, length);
- if (!attrs) {
- //Parse the empty tag
- attrs = content;
- while ((attrs != nullptr) && *attrs != '>') attrs++;
- }
-
- if (attrs) {
- sz = attrs - content;
- while ((sz > 0) && (isspace((unsigned char)content[sz - 1]))) sz--;
- if ((unsigned)sz >= sizeof(tagName)) return false;
- strncpy(tagName, content, sz);
- tagName[sz] = '\0';
- attrsLength = length - sz;
- }
+ sz = attrs - content;
+ while ((sz > 0) && (isspace((unsigned char)content[sz - 1]))) sz--;
+ if ((unsigned)sz >= sizeof(tagName)) return false;
+ strncpy(tagName, content, sz);
+ tagName[sz] = '\0';
+ attrsLength = length - sz;
if ((method = _findGroupFactory(tagName))) {
- if (!loader->doc) {
+ if (!ctx->doc) {
if (!STR_AS(tagName, "svg")) return true; //Not a valid svg document
- node = method(loader, nullptr, attrs, attrsLength, xmlParseAttributes);
- loader->doc = node;
- loader->stack.push(node);
+ node = method(ctx, nullptr, attrs, attrsLength, xmlParseAttributes);
+ ctx->doc = node;
+ ctx->stack.push(node);
return false;
}
}
@@ -3683,7 +3995,7 @@ static bool _svgLoaderParserForValidCheck(void* data, XMLType type, const char*
case XMLType::Open:
case XMLType::OpenEmpty: {
//If 'res' is false, it means <svg> tag is found.
- return _svgLoaderParserForValidCheckXmlOpen(static_cast<SvgLoaderData*>(data), content, length);
+ return _svgLoaderParserForValidCheckXmlOpen(static_cast<SvgParserContext*>(data), content, length);
}
default: return true;
}
@@ -3692,34 +4004,11 @@ static bool _svgLoaderParserForValidCheck(void* data, XMLType type, const char*
void SvgLoader::clear(bool all)
{
- //flush out the intermediate data
- tvg::free(loaderData.svgParse);
- loaderData.svgParse = nullptr;
-
- ARRAY_FOREACH(p, loaderData.gradients) {
- (*p)->clear();
- tvg::free(*p);
- }
- loaderData.gradients.reset();
- loaderData.gradientStack.reset();
-
- _free(loaderData.doc);
- loaderData.doc = nullptr;
- loaderData.stack.reset();
+ ctx.clear(all);
if (!all) return;
- ARRAY_FOREACH(p, loaderData.images) tvg::free(*p);
- loaderData.images.reset();
-
- ARRAY_FOREACH(p, loaderData.fonts) {
- Text::unload(p->name);
- tvg::free(p->decoded);
- tvg::free(p->name);
- }
- loaderData.fonts.reset();
-
- if (copy) tvg::free((char*)content);
+ if (owner != Ownership::Borrow) tvg::free((char*)content);
if (root) {
root->unref();
@@ -3728,52 +4017,61 @@ void SvgLoader::clear(bool all)
size = 0;
content = nullptr;
- copy = false;
+ owner = Ownership::Borrow;
}
void SvgLoader::run(unsigned tid)
{
+ if (!ctx.parser) return;
+
//According to the SVG standard the value of the width/height of the viewbox set to 0 disables rendering
if ((viewFlag & SvgViewFlag::Viewbox) && (fabsf(vbox.w) <= FLOAT_EPSILON || fabsf(vbox.h) <= FLOAT_EPSILON)) {
TVGLOG("SVG", "The <viewBox> width and/or height set to 0 - rendering disabled.");
root = Scene::gen();
} else {
- if (xmlParse(content, size, true, _svgLoaderParser, &(loaderData))) {
- if (loaderData.doc) {
- auto defs = loaderData.doc->node.doc.defs;
+ if (xmlParse(content, size, true, _svgLoaderParser, &(ctx))) {
+ if (ctx.doc) {
+ auto defs = ctx.doc->node.doc.defs;
- if (loaderData.nodesToStyle.count > 0) _cssApplyStyleToPostponeds(loaderData.nodesToStyle, loaderData.cssStyle);
- if (loaderData.cssStyle) cssUpdateStyle(loaderData.doc, loaderData.cssStyle);
+ if (ctx.nodesToStyle.count > 0) _cssApplyStyleToPostponeds(ctx.nodesToStyle, ctx.cssStyle);
+ if (ctx.cssStyle) cssUpdateStyle(ctx.doc, ctx.cssStyle);
- if (!loaderData.cloneNodes.empty()) _clonePostponedNodes(&loaderData.cloneNodes, loaderData.doc);
+ if (!ctx.cloneNodes.empty()) _clonePostponedNodes(&ctx.cloneNodes, ctx.doc);
- _updateComposite(loaderData.doc, loaderData.doc);
- if (defs) _updateComposite(loaderData.doc, defs);
+ _updateComposite(ctx.doc, ctx.doc);
+ if (defs) _updateComposite(ctx.doc, defs);
+ if (defs) _updateComposite(defs, defs);
- _updateFilter(loaderData.doc, loaderData.doc);
- if (defs) _updateFilter(loaderData.doc, defs);
+ _updateFilter(ctx.doc, ctx.doc);
+ if (defs) _updateFilter(ctx.doc, defs);
+ if (defs) _updateFilter(defs, defs);
- _updateStyle(loaderData.doc, nullptr);
+ _updateStyle(ctx.doc, nullptr);
if (defs) _updateStyle(defs, nullptr);
- if (loaderData.gradients.count > 0) _updateGradient(&loaderData, loaderData.doc, &loaderData.gradients);
- if (defs) _updateGradient(&loaderData, loaderData.doc, &defs->node.defs.gradients);
+ if (ctx.gradients.count > 0) _updateGradient(&ctx, ctx.doc, &ctx.gradients);
+ if (defs) _updateGradient(&ctx, ctx.doc, &defs->node.defs.gradients);
+ if (defs && ctx.gradients.count > 0) _updateGradient(&ctx, defs, &ctx.gradients);
+ if (defs) _updateGradient(&ctx, defs, &defs->node.defs.gradients);
+
+ _updatePattern(ctx.doc, ctx.doc, defs);
+ if (defs) _updatePattern(defs, ctx.doc, defs);
- root = svgSceneBuild(loaderData, vbox, w, h, align, meetOrSlice, svgPath, viewFlag);
+ root = svgSceneBuild(ctx, vbox, w, h, align, meetOrSlice, svgPath, viewFlag);
//In case no viewbox and width/height data is provided the completion of loading
//has to be forced, in order to establish this data based on the whole picture.
if (!(viewFlag & SvgViewFlag::Viewbox)) {
//Override viewbox & size again after svg loading.
- vbox = loaderData.doc->node.doc.vbox;
- w = loaderData.doc->node.doc.w;
- h = loaderData.doc->node.doc.h;
+ vbox = ctx.doc->node.doc.vbox;
+ w = ctx.doc->node.doc.w;
+ h = ctx.doc->node.doc.h;
}
}
}
}
- root->ref();
+ if (root) root->ref();
clear(false);
}
@@ -3782,10 +4080,36 @@ void SvgLoader::run(unsigned tid)
/* External Class Implementation */
/************************************************************************/
-SvgLoader::SvgLoader() : ImageLoader(FileType::Svg)
+void SvgParserContext::clear(bool all)
{
-}
+ tvg::free(parser);
+ parser = nullptr;
+ ARRAY_FOREACH(p, gradients) {
+ (*p)->clear();
+ tvg::free(*p);
+ }
+ gradients.reset();
+ gradientStack.reset();
+
+ _free(doc);
+ doc = nullptr;
+ stack.reset();
+
+ if (!all) return;
+
+ ARRAY_FOREACH(p, images) {
+ tvg::free(*p);
+ }
+ ARRAY_FOREACH(p, fonts) {
+ Text::unload(p->name);
+ tvg::free(p->decoded);
+ tvg::free(p->name);
+ }
+ ARRAY_FOREACH(a, access) {
+ tvg::free(a->name);
+ }
+}
SvgLoader::~SvgLoader()
{
@@ -3794,43 +4118,43 @@ SvgLoader::~SvgLoader()
}
-bool SvgLoader::header()
+Result SvgLoader::header()
{
//For valid check, only <svg> tag is parsed first.
//If the <svg> tag is found, the loaded file is valid and stores viewbox information.
//After that, the remaining content data is parsed in order with async.
- loaderData.svgParse = tvg::malloc<SvgParser>(sizeof(SvgParser));
- loaderData.svgParse->flags = SvgStopStyleFlags::StopDefault;
+ ctx.parser = tvg::malloc<SvgParser>(sizeof(SvgParser));
+ ctx.parser->flags = SvgStopStyleFlags::StopDefault;
viewFlag = SvgViewFlag::None;
- xmlParse(content, size, true, _svgLoaderParserForValidCheck, &(loaderData));
+ xmlParse(content, size, true, _svgLoaderParserForValidCheck, &(ctx));
- if (!loaderData.doc || loaderData.doc->type != SvgNodeType::Doc) {
+ if (!ctx.doc || ctx.doc->type != SvgNodeType::Doc) {
TVGLOG("SVG", "No SVG File. There is no <svg/>");
- return false;
+ return Result::InvalidArguments;
}
- viewFlag = loaderData.doc->node.doc.viewFlag;
- align = loaderData.doc->node.doc.align;
- meetOrSlice = loaderData.doc->node.doc.meetOrSlice;
+ viewFlag = ctx.doc->node.doc.viewFlag;
+ align = ctx.doc->node.doc.align;
+ meetOrSlice = ctx.doc->node.doc.meetOrSlice;
if (viewFlag & SvgViewFlag::Viewbox) {
- vbox = loaderData.doc->node.doc.vbox;
+ vbox = ctx.doc->node.doc.vbox;
- if (viewFlag & SvgViewFlag::Width) w = loaderData.doc->node.doc.w;
+ if (viewFlag & SvgViewFlag::Width) w = ctx.doc->node.doc.w;
else {
- w = loaderData.doc->node.doc.vbox.w;
+ w = ctx.doc->node.doc.vbox.w;
if (viewFlag & SvgViewFlag::WidthInPercent) {
- w *= loaderData.doc->node.doc.w;
+ w *= ctx.doc->node.doc.w;
viewFlag = (viewFlag ^ SvgViewFlag::WidthInPercent);
}
viewFlag = (viewFlag | SvgViewFlag::Width);
}
- if (viewFlag & SvgViewFlag::Height) h = loaderData.doc->node.doc.h;
+ if (viewFlag & SvgViewFlag::Height) h = ctx.doc->node.doc.h;
else {
- h = loaderData.doc->node.doc.vbox.h;
+ h = ctx.doc->node.doc.vbox.h;
if (viewFlag & SvgViewFlag::HeightInPercent) {
- h *= loaderData.doc->node.doc.h;
+ h *= ctx.doc->node.doc.h;
viewFlag = (viewFlag ^ SvgViewFlag::HeightInPercent);
}
viewFlag = (viewFlag | SvgViewFlag::Height);
@@ -3841,53 +4165,59 @@ bool SvgLoader::header()
//Before loading, set default viewbox & size if they are empty
vbox.x = vbox.y = 0.0f;
if (viewFlag & SvgViewFlag::Width) {
- vbox.w = w = loaderData.doc->node.doc.w;
+ vbox.w = w = ctx.doc->node.doc.w;
} else {
vbox.w = 1.0f;
if (viewFlag & SvgViewFlag::WidthInPercent) {
- w = loaderData.doc->node.doc.w;
+ w = ctx.doc->node.doc.w;
} else w = 1.0f;
}
if (viewFlag & SvgViewFlag::Height) {
- vbox.h = h = loaderData.doc->node.doc.h;
+ vbox.h = h = ctx.doc->node.doc.h;
} else {
vbox.h = 1.0f;
if (viewFlag & SvgViewFlag::HeightInPercent) {
- h = loaderData.doc->node.doc.h;
+ h = ctx.doc->node.doc.h;
} else h = 1.0f;
}
run(0);
}
- return true;
+ return Result::Success;
}
-
-bool SvgLoader::open(const char* data, uint32_t size, TVG_UNUSED const char* rpath, bool copy)
+Result SvgLoader::open(const char* data, uint32_t size, const LoaderOps& ops)
{
- if (copy) {
+ if (ops.caller != tvg::Type::Picture) return Result::InvalidArguments;
+
+ if (ops.owner == Ownership::Copy) {
content = tvg::malloc<char>(size + 1);
memcpy((char*)content, data, size);
content[size] = '\0';
} else content = (char*)data;
this->size = size;
- this->copy = copy;
+ owner = ops.owner;
+ ctx.accessible = static_cast<const PictureOps*>(&ops)->accessible;
return header();
}
-
-bool SvgLoader::open(const char* path)
+Result SvgLoader::open(const char* path, const LoaderOps& ops)
{
#ifdef THORVG_FILE_IO_SUPPORT
- if ((content = LoadModule::open(path, size, true))) {
- copy = true;
+ if (ops.caller != tvg::Type::Picture) return Result::InvalidArguments;
+
+ if ((content = Loader::open(path, size, true))) {
+ ctx.accessible = static_cast<const PictureOps*>(&ops)->accessible;
+ owner = Ownership::Transfer;
return header();
}
+ return Result::InvalidArguments;
+#else
+ return Result::NonSupport;
#endif
- return false;
}
@@ -3908,7 +4238,7 @@ bool SvgLoader::read()
{
if (!content || size == 0) return false;
- if (!LoadModule::read() || root) return true;
+ if (!Loader::read() || root) return true;
TaskScheduler::request(this);
@@ -3918,9 +4248,8 @@ bool SvgLoader::read()
bool SvgLoader::close()
{
- if (!LoadModule::close()) return false;
+ if (!Loader::close()) return false;
this->done();
- clear();
return true;
}
@@ -3935,3 +4264,20 @@ Paint* SvgLoader::paint()
}
return nullptr;
}
+
+const AccessorEntity* SvgLoader::access(uint32_t id)
+{
+ this->done();
+ ARRAY_FOREACH(a, ctx.access) {
+ if (a->id == id) return a;
+ }
+ return nullptr;
+}
+
+void SvgLoader::access(AccessorCallback& cb)
+{
+ this->done();
+ ARRAY_FOREACH(a, ctx.access) {
+ if (!cb.func(a->paint, cb.data)) return;
+ }
+}
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.h b/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.h
index 063b718c414..e943662320f 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.h
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgLoader.h
@@ -24,29 +24,28 @@
#define _TVG_SVG_LOADER_H_
#include "tvgTaskScheduler.h"
-#include "tvgSvgLoaderCommon.h"
+#include "tvgSvgCommon.h"
-class SvgLoader : public ImageLoader, public Task
+struct SvgLoader : ImageLoader, Task
{
-public:
+ SvgParserContext ctx;
string svgPath = "";
char* content = nullptr;
uint32_t size = 0;
-
- SvgLoaderData loaderData;
Scene* root = nullptr;
- bool copy = false;
-
- SvgLoader();
+ SvgLoader() : ImageLoader(FileType::Svg) {}
~SvgLoader();
- bool open(const char* path) override;
- bool open(const char* data, uint32_t size, const char* rpath, bool copy) override;
+ Result open(const char* path, const LoaderOps& ops) override;
+ Result open(const char* data, uint32_t size, const LoaderOps& ops) override;
bool resize(Paint* paint, float w, float h) override;
bool read() override;
bool close() override;
+ const AccessorEntity* access(uint32_t id) override;
+ void access(AccessorCallback& cb) override;
+
Paint* paint() override;
private:
@@ -55,7 +54,7 @@ private:
AspectRatioMeetOrSlice meetOrSlice = AspectRatioMeetOrSlice::Meet;
Box vbox{};
- bool header();
+ Result header();
void clear(bool all = true);
void run(unsigned tid) override;
};
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgPath.cpp b/thirdparty/thorvg/src/loaders/svg/tvgSvgPath.cpp
index 422d1cd28b6..bb834715521 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgPath.cpp
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgPath.cpp
@@ -20,12 +20,10 @@
* SOFTWARE.
*/
-#define _USE_MATH_DEFINES //Math Constants are not defined in Standard C/C++.
-
#include <cstring>
#include <ctype.h>
#include "tvgMath.h"
-#include "tvgSvgLoaderCommon.h"
+#include "tvgSvgCommon.h"
#include "tvgSvgPath.h"
#include "tvgStr.h"
#include "tvgSvgUtil.h"
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgSceneBuilder.cpp b/thirdparty/thorvg/src/loaders/svg/tvgSvgSceneBuilder.cpp
deleted file mode 100644
index 50e91adaabb..00000000000
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgSceneBuilder.cpp
+++ /dev/null
@@ -1,1076 +0,0 @@
-/*
- * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
-
- * 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 "tvgMath.h" /* to include math.h before cstring */
-#include "tvgShape.h"
-#include "tvgCompressor.h"
-#include "tvgFill.h"
-#include "tvgStr.h"
-#include "tvgShape.h"
-#include "tvgSvgLoaderCommon.h"
-#include "tvgSvgSceneBuilder.h"
-#include "tvgSvgPath.h"
-#include "tvgSvgUtil.h"
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-static bool _appendClipShape(SvgLoaderData& loaderData, SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath, const Matrix* transform);
-static Scene* _sceneBuildHelper(SvgLoaderData& loaderData, const SvgNode* node, const Box& vBox, const string& svgPath, bool mask, int depth);
-
-
-static inline bool _isGroupType(SvgNodeType type)
-{
- if (type == SvgNodeType::Doc || type == SvgNodeType::G || type == SvgNodeType::Use || type == SvgNodeType::ClipPath || type == SvgNodeType::Symbol || type == SvgNodeType::Filter) return true;
- return false;
-}
-
-
-//According to: https://www.w3.org/TR/SVG11/coords.html#ObjectBoundingBoxUnits (the last paragraph)
-//a stroke width should be ignored for bounding box calculations
-static Box _bounds(Paint* paint)
-{
- float x, y, w, h;
- paint->bounds(&x, &y, &w, &h);
- return {x, y, w, h};
-}
-
-
-static void _transformMultiply(const Matrix* mBBox, Matrix* gradTransf)
-{
- gradTransf->e13 = gradTransf->e13 * mBBox->e11 + mBBox->e13;
- gradTransf->e12 *= mBBox->e11;
- gradTransf->e11 *= mBBox->e11;
-
- gradTransf->e23 = gradTransf->e23 * mBBox->e22 + mBBox->e23;
- gradTransf->e22 *= mBBox->e22;
- gradTransf->e21 *= mBBox->e22;
-}
-
-
-static LinearGradient* _applyLinearGradientProperty(SvgStyleGradient* g, const Box& vBox, int opacity)
-{
- Fill::ColorStop* stops;
- auto fillGrad = LinearGradient::gen();
- auto isTransform = (g->transform ? true : false);
- auto& finalTransform = fillGrad->transform();
- if (isTransform) finalTransform = *g->transform;
-
- if (g->userSpace) {
- g->linear->x1 = g->linear->x1 * vBox.w;
- g->linear->y1 = g->linear->y1 * vBox.h;
- g->linear->x2 = g->linear->x2 * vBox.w;
- g->linear->y2 = g->linear->y2 * vBox.h;
- } else {
- Matrix m = {vBox.w, 0, vBox.x, 0, vBox.h, vBox.y, 0, 0, 1};
- if (isTransform) _transformMultiply(&m, &finalTransform);
- else finalTransform = m;
- }
-
- fillGrad->linear(g->linear->x1, g->linear->y1, g->linear->x2, g->linear->y2);
- fillGrad->spread(g->spread);
-
- //Update the stops
- if (g->stops.count == 0) return fillGrad;
-
- stops = tvg::malloc<Fill::ColorStop>(g->stops.count * sizeof(Fill::ColorStop));
- auto prevOffset = 0.0f;
- for (uint32_t i = 0; i < g->stops.count; ++i) {
- auto colorStop = &g->stops[i];
- //Use premultiplied color
- stops[i].r = colorStop->r;
- stops[i].g = colorStop->g;
- stops[i].b = colorStop->b;
- stops[i].a = static_cast<uint8_t>((colorStop->a * opacity) / 255);
- stops[i].offset = colorStop->offset;
- //check the offset corner cases - refer to: https://svgwg.org/svg2-draft/pservers.html#StopNotes
- if (colorStop->offset < prevOffset) stops[i].offset = prevOffset;
- else if (colorStop->offset > 1) stops[i].offset = 1;
- prevOffset = stops[i].offset;
- }
- fillGrad->colorStops(stops, g->stops.count);
- tvg::free(stops);
- return fillGrad;
-}
-
-
-static RadialGradient* _applyRadialGradientProperty(SvgStyleGradient* g, const Box& vBox, int opacity)
-{
- Fill::ColorStop *stops;
- auto fillGrad = RadialGradient::gen();
- auto isTransform = (g->transform ? true : false);
- auto& finalTransform = fillGrad->transform();
- if (isTransform) finalTransform = *g->transform;
-
- if (g->userSpace) {
- //The radius scaling is done according to the Units section:
- //https://www.w3.org/TR/2015/WD-SVG2-20150915/coords.html
- g->radial->cx = g->radial->cx * vBox.w;
- g->radial->cy = g->radial->cy * vBox.h;
- g->radial->r = g->radial->r * sqrtf(powf(vBox.w, 2.0f) + powf(vBox.h, 2.0f)) / sqrtf(2.0f);
- g->radial->fx = g->radial->fx * vBox.w;
- g->radial->fy = g->radial->fy * vBox.h;
- g->radial->fr = g->radial->fr * sqrtf(powf(vBox.w, 2.0f) + powf(vBox.h, 2.0f)) / sqrtf(2.0f);
- } else {
- Matrix m = {vBox.w, 0, vBox.x, 0, vBox.h, vBox.y, 0, 0, 1};
- if (isTransform) _transformMultiply(&m, &finalTransform);
- else finalTransform = m;
- }
-
- fillGrad->radial(g->radial->cx, g->radial->cy, g->radial->r, g->radial->fx, g->radial->fy, g->radial->fr);
- fillGrad->spread(g->spread);
-
- //Update the stops
- if (g->stops.count == 0) return fillGrad;
-
- stops = tvg::malloc<Fill::ColorStop>(g->stops.count * sizeof(Fill::ColorStop));
- auto prevOffset = 0.0f;
- for (uint32_t i = 0; i < g->stops.count; ++i) {
- auto colorStop = &g->stops[i];
- //Use premultiplied color
- stops[i].r = colorStop->r;
- stops[i].g = colorStop->g;
- stops[i].b = colorStop->b;
- stops[i].a = static_cast<uint8_t>((colorStop->a * opacity) / 255);
- stops[i].offset = colorStop->offset;
- //check the offset corner cases - refer to: https://svgwg.org/svg2-draft/pservers.html#StopNotes
- if (colorStop->offset < prevOffset) stops[i].offset = prevOffset;
- else if (colorStop->offset > 1) stops[i].offset = 1;
- prevOffset = stops[i].offset;
- }
- fillGrad->colorStops(stops, g->stops.count);
- tvg::free(stops);
- return fillGrad;
-}
-
-
-static void _appendRect(Shape* shape, float x, float y, float w, float h, float rx, float ry)
-{
- auto halfW = w * 0.5f;
- auto halfH = h * 0.5f;
-
- //clamping cornerRadius by minimum size
- if (rx > halfW) rx = halfW;
- if (ry > halfH) ry = halfH;
-
- if (rx == 0 && ry == 0) {
- to<ShapeImpl>(shape)->grow(5, 4);
- shape->moveTo(x, y);
- shape->lineTo(x + w, y);
- shape->lineTo(x + w, y + h);
- shape->lineTo(x, y + h);
- shape->close();
- } else {
- auto hrx = rx * PATH_KAPPA;
- auto hry = ry * PATH_KAPPA;
-
- to<ShapeImpl>(shape)->grow(10, 17);
- shape->moveTo(x + rx, y);
- shape->lineTo(x + w - rx, y);
- shape->cubicTo(x + w - rx + hrx, y, x + w, y + ry - hry, x + w, y + ry);
- shape->lineTo(x + w, y + h - ry);
- shape->cubicTo(x + w, y + h - ry + hry, x + w - rx + hrx, y + h, x + w - rx, y + h);
- shape->lineTo(x + rx, y + h);
- shape->cubicTo(x + rx - hrx, y + h, x, y + h - ry + hry, x, y + h - ry);
- shape->lineTo(x, y + ry);
- shape->cubicTo(x, y + ry - hry, x + rx - hrx, y, x + rx, y);
- shape->close();
- }
-}
-
-
-static void _appendCircle(Shape* shape, float cx, float cy, float rx, float ry)
-{
- auto rxKappa = rx * PATH_KAPPA;
- auto ryKappa = ry * PATH_KAPPA;
-
- to<ShapeImpl>(shape)->grow(6, 13);
- shape->moveTo(cx + rx, cy);
- shape->cubicTo(cx + rx, cy + ryKappa, cx + rxKappa, cy + ry, cx, cy + ry);
- shape->cubicTo(cx - rxKappa, cy + ry, cx - rx, cy + ryKappa, cx - rx, cy);
- shape->cubicTo(cx - rx, cy - ryKappa, cx - rxKappa, cy - ry, cx, cy - ry);
- shape->cubicTo(cx + rxKappa, cy - ry, cx + rx, cy - ryKappa, cx + rx, cy);
- shape->close();
-}
-
-
-static bool _appendClipChild(SvgLoaderData& loaderData, SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath)
-{
- //The SVG standard allows only for 'use' nodes that point directly to a basic shape.
- if (node->type == SvgNodeType::Use) {
- if (node->child.count != 1) return false;
- auto child = *(node->child.data);
- auto finalTransform = tvg::identity();
- if (node->transform) finalTransform = *node->transform;
- if (node->node.use.x != 0.0f || node->node.use.y != 0.0f) {
- finalTransform *= {1, 0, node->node.use.x, 0, 1, node->node.use.y, 0, 0, 1};
- }
- if (child->transform) finalTransform *= *child->transform;
-
- return _appendClipShape(loaderData, child, shape, vBox, svgPath, tvg::identity((const Matrix*)(&finalTransform)) ? nullptr : &finalTransform);
- }
- return _appendClipShape(loaderData, node, shape, vBox, svgPath, nullptr);
-}
-
-
-static Matrix _compositionTransform(Paint* paint, const SvgNode* node, const SvgNode* compNode, SvgNodeType type)
-{
- auto m = tvg::identity();
- //The initial mask transformation ignored according to the SVG standard.
- if (node->transform && type != SvgNodeType::Mask) {
- m = *node->transform;
- }
- if (compNode->transform) {
- m *= *compNode->transform;
- }
- if (!compNode->node.clip.userSpace) {
- auto bbox = _bounds(paint);
- m *= {bbox.w, 0, bbox.x, 0, bbox.h, bbox.y, 0, 0, 1};
- }
- return m;
-}
-
-static bool _applyClip(SvgLoaderData& loaderData, Paint* paint, const SvgNode* node, const SvgNode* clipNode, const Box& vBox, const string& svgPath)
-{
- node->style->clipPath.applying = true;
-
- auto clipper = Shape::gen();
- auto valid = false; //Composite only when valid shapes exist
-
- ARRAY_FOREACH(p, clipNode->child) {
- if (_appendClipChild(loaderData, *p, clipper, vBox, svgPath)) valid = true;
- }
-
- if (valid) {
- Matrix finalTransform = _compositionTransform(paint, node, clipNode, SvgNodeType::ClipPath);
- clipper->transform(finalTransform);
- paint->clip(clipper);
- } else {
- Paint::rel(clipper);
- }
-
- node->style->clipPath.applying = false;
- return valid;
-}
-
-
-static Paint* _applyComposition(SvgLoaderData& loaderData, Paint* paint, const SvgNode* node, const Box& vBox, const string& svgPath)
-{
- if (node->style->clipPath.applying || node->style->mask.applying) {
- TVGLOG("SVG", "Multiple composition tried! Check out circular dependency?");
- return paint;
- }
-
- auto clipNode = node->style->clipPath.node;
- auto maskNode = node->style->mask.node;
-
- if (!clipNode && !maskNode) return paint;
- if ((clipNode && clipNode->child.empty()) || (maskNode && maskNode->child.empty())) {
- Paint::rel(paint);
- return nullptr;
- }
-
- auto scene = Scene::gen();
- scene->add(paint);
-
- if (clipNode) {
- if (!_applyClip(loaderData, scene, node, clipNode, vBox, svgPath)) {
- Paint::rel(scene);
- return nullptr;
- }
- }
-
- /* Mask */
- if (maskNode) {
- node->style->mask.applying = true;
-
- if (auto mask = _sceneBuildHelper(loaderData, maskNode, vBox, svgPath, true, 0)) {
- if (!maskNode->node.mask.userSpace) {
- Matrix finalTransform = _compositionTransform(paint, node, maskNode, SvgNodeType::Mask);
- mask->transform(finalTransform);
- } else if (node->transform) {
- mask->transform(*node->transform);
- }
- scene->mask(mask, maskNode->node.mask.type == SvgMaskType::Luminance ? MaskMethod::Luma: MaskMethod::Alpha);
- }
-
- node->style->mask.applying = false;
- }
-
- return scene;
-}
-
-
-static Paint* _applyFilter(SvgLoaderData& loaderData, Paint* paint, const SvgNode* node, const Box& vBox, const string& svgPath)
-{
- auto filterNode = node->style->filter.node;
- if (!filterNode || filterNode->child.count == 0) return paint;
- auto& filter = filterNode->node.filter;
-
- auto scene = Scene::gen();
-
- auto bbox = _bounds(paint);
- Box clipBox = filter.filterUserSpace ? filter.box : Box{bbox.x + filter.box.x * bbox.w, bbox.y + filter.box.y * bbox.h, filter.box.w * bbox.w, filter.box.h * bbox.h};
- auto primitiveUserSpace = filter.primitiveUserSpace;
- auto sx = paint->transform().e11;
- auto sy = paint->transform().e22;
-
- auto child = filterNode->child.data;
- for (uint32_t i = 0; i < filterNode->child.count; ++i, ++child) {
- if ((*child)->type == SvgNodeType::GaussianBlur) {
- auto& gauss = (*child)->node.gaussianBlur;
-
- auto direction = gauss.stdDevX > 0.0f ? (gauss.stdDevY > 0.0f ? 0 : 1) : (gauss.stdDevY > 0.0f ? 2 : -1);
- if (direction == -1) continue;
-
- auto stdDevX = gauss.stdDevX;
- auto stdDevY = gauss.stdDevY;
- if (gauss.hasBox) {
- auto gaussBox = gauss.box;
- auto isPercent = gauss.isPercentage;
- if (primitiveUserSpace) {
- if (isPercent[0]) gaussBox.x *= loaderData.svgParse->global.w;
- if (isPercent[1]) gaussBox.y *= loaderData.svgParse->global.h;
- if (isPercent[2]) gaussBox.w *= loaderData.svgParse->global.w;
- if (isPercent[3]) gaussBox.h *= loaderData.svgParse->global.h;
- } else {
- stdDevX *= bbox.w;
- stdDevY *= bbox.h;
- if (isPercent[0]) gaussBox.x = bbox.x + gauss.box.x * bbox.w;
- if (isPercent[1]) gaussBox.y = bbox.y + gauss.box.y * bbox.h;
- if (isPercent[2]) gaussBox.w *= bbox.w;
- if (isPercent[3]) gaussBox.h *= bbox.h;
- }
- clipBox.intersect(gaussBox);
- } else if (!primitiveUserSpace) {
- stdDevX *= bbox.w;
- stdDevY *= bbox.h;
- }
- scene->add(SceneEffect::GaussianBlur, (double)(1.25f * (direction == 2 ? stdDevY * sy : stdDevX * sx)), direction, gauss.edgeModeWrap, 55);
- }
- }
-
- scene->add(paint);
-
- auto clip = Shape::gen();
- clip->appendRect(clipBox.x, clipBox.y, clipBox.w, clipBox.h);
- scene->clip(clip);
-
- return scene;
-}
-
-static Paint* _applyProperty(SvgLoaderData& loaderData, SvgNode* node, Shape* vg, const Box& vBox, const string& svgPath, bool clip)
-{
- SvgStyleProperty* style = node->style;
-
- //Clip transformation is applied directly to the path in the _appendClipShape function
- if (node->type == SvgNodeType::Doc || !node->style->display) return vg;
-
- //If fill property is nullptr then do nothing
- if (style->fill.paint.none) {
- //Do nothing
- } else if (style->fill.paint.gradient) {
- auto bBox = style->fill.paint.gradient->userSpace ? vBox : _bounds(vg);
- if (style->fill.paint.gradient->type == SvgGradientType::Linear) {
- vg->fill(_applyLinearGradientProperty(style->fill.paint.gradient, bBox, style->fill.opacity));
- } else if (style->fill.paint.gradient->type == SvgGradientType::Radial) {
- vg->fill(_applyRadialGradientProperty(style->fill.paint.gradient, bBox, style->fill.opacity));
- }
- } else if (style->fill.paint.url) {
- TVGLOG("SVG", "The fill's url not supported.");
- } else if (style->fill.paint.curColor) {
- //Apply the current style color
- vg->fill(style->color.r, style->color.g, style->color.b, style->fill.opacity);
- } else {
- //Apply the fill color
- vg->fill(style->fill.paint.color.r, style->fill.paint.color.g, style->fill.paint.color.b, style->fill.opacity);
- }
-
- vg->fillRule(style->fill.fillRule);
- vg->order(!style->paintOrder);
- vg->opacity(style->opacity);
-
- if (node->type == SvgNodeType::G || node->type == SvgNodeType::Use) return vg;
-
- //Apply the stroke style property
- vg->strokeWidth(style->stroke.width);
- vg->strokeCap(style->stroke.cap);
- vg->strokeJoin(style->stroke.join);
- vg->strokeMiterlimit(style->stroke.miterlimit);
- vg->strokeDash(style->stroke.dash.array.data, style->stroke.dash.array.count, style->stroke.dash.offset);
-
- //If stroke property is nullptr then do nothing
- if (style->stroke.paint.none) {
- vg->strokeWidth(0.0f);
- } else if (style->stroke.paint.gradient) {
- auto bBox = style->stroke.paint.gradient->userSpace ? vBox : _bounds(vg);
- if (style->stroke.paint.gradient->type == SvgGradientType::Linear) {
- vg->strokeFill(_applyLinearGradientProperty(style->stroke.paint.gradient, bBox, style->stroke.opacity));
- } else if (style->stroke.paint.gradient->type == SvgGradientType::Radial) {
- vg->strokeFill(_applyRadialGradientProperty(style->stroke.paint.gradient, bBox, style->stroke.opacity));
- }
- } else if (style->stroke.paint.url) {
- //TODO: Apply the color pointed by url
- TVGLOG("SVG", "The stroke's url not supported.");
- } else if (style->stroke.paint.curColor) {
- //Apply the current style color
- vg->strokeFill(style->color.r, style->color.g, style->color.b, style->stroke.opacity);
- } else {
- //Apply the stroke color
- vg->strokeFill(style->stroke.paint.color.r, style->stroke.paint.color.g, style->stroke.paint.color.b, style->stroke.opacity);
- }
-
- //apply transform after the local space shape bbox for gradient acquisition
- if (node->transform && !clip) vg->transform(*node->transform);
-
- auto p = _applyFilter(loaderData, vg, node, vBox, svgPath);
- return _applyComposition(loaderData, p, node, vBox, svgPath);
-}
-
-
-static bool _recognizeShape(SvgNode* node, Shape* shape)
-{
- switch (node->type) {
- case SvgNodeType::Path: {
- if (node->node.path.path) {
- if (!svgPathToShape(node->node.path.path, to<ShapeImpl>(shape)->rs.path)) {
- TVGERR("SVG", "Invalid path information.");
- return false;
- }
- }
- break;
- }
- case SvgNodeType::Ellipse: {
- _appendCircle(shape, node->node.ellipse.cx, node->node.ellipse.cy, node->node.ellipse.rx, node->node.ellipse.ry);
- break;
- }
- case SvgNodeType::Polygon: {
- if (node->node.polygon.pts.count < 2) break;
- auto pts = node->node.polygon.pts.begin();
- shape->moveTo(pts[0], pts[1]);
- for (pts += 2; pts < node->node.polygon.pts.end(); pts += 2) {
- shape->lineTo(pts[0], pts[1]);
- }
- shape->close();
- break;
- }
- case SvgNodeType::Polyline: {
- if (node->node.polyline.pts.count < 2) break;
- auto pts = node->node.polyline.pts.begin();
- shape->moveTo(pts[0], pts[1]);
- for (pts += 2; pts < node->node.polyline.pts.end(); pts += 2) {
- shape->lineTo(pts[0], pts[1]);
- }
- break;
- }
- case SvgNodeType::Circle: {
- _appendCircle(shape, node->node.circle.cx, node->node.circle.cy, node->node.circle.r, node->node.circle.r);
- break;
- }
- case SvgNodeType::Rect: {
- _appendRect(shape, node->node.rect.x, node->node.rect.y, node->node.rect.w, node->node.rect.h, node->node.rect.rx, node->node.rect.ry);
- break;
- }
- case SvgNodeType::Line: {
- shape->moveTo(node->node.line.x1, node->node.line.y1);
- shape->lineTo(node->node.line.x2, node->node.line.y2);
- break;
- }
- default: {
- return false;
- }
- }
- return true;
-}
-
-
-static Paint* _shapeBuildHelper(SvgLoaderData& loaderData, SvgNode* node, const Box& vBox, const string& svgPath)
-{
- auto shape = Shape::gen();
- if (!_recognizeShape(node, shape)) return nullptr;
- return _applyProperty(loaderData, node, shape, vBox, svgPath, false);
-}
-
-
-static bool _appendClipShape(SvgLoaderData& loaderData, SvgNode* node, Shape* shape, const Box& vBox, const string& svgPath, const Matrix* transform)
-{
- uint32_t currentPtsCnt;
- shape->path(nullptr, nullptr, nullptr, &currentPtsCnt);
-
- if (!_recognizeShape(node, shape)) return false;
-
- //The 'transform' matrix has higher priority than the node->transform, since it already contains it
- auto m = transform ? transform : (node->transform ? node->transform : nullptr);
-
- if (m) {
- const Point *pts;
- uint32_t ptsCnt;
- shape->path(nullptr, nullptr, &pts, &ptsCnt);
- auto p = const_cast<Point*>(pts) + currentPtsCnt;
- while (currentPtsCnt++ < ptsCnt) {
- *p *= *m;
- ++p;
- }
- }
-
- //Apply Clip Chaining
- if (auto clipNode = node->style->clipPath.node) {
- if (clipNode->child.count == 0) return false;
- if (node->style->clipPath.applying) {
- TVGLOG("SVG", "Multiple composition tried! Check out circular dependency?");
- return false;
- }
- return _applyClip(loaderData, shape, node, clipNode, vBox, svgPath);
- }
-
- return true;
-}
-
-
-enum class imageMimeTypeEncoding
-{
- base64 = 0x1,
- utf8 = 0x2
-};
-
-
-constexpr imageMimeTypeEncoding operator|(imageMimeTypeEncoding a, imageMimeTypeEncoding b) {
- return static_cast<imageMimeTypeEncoding>(static_cast<int>(a) | static_cast<int>(b));
-}
-
-
-constexpr bool operator&(imageMimeTypeEncoding a, imageMimeTypeEncoding b) {
- return (static_cast<int>(a) & static_cast<int>(b));
-}
-
-
-static constexpr struct
-{
- const char* name;
- int sz;
- imageMimeTypeEncoding encoding;
-} imageMimeTypes[] = {
- {"jpeg", sizeof("jpeg"), imageMimeTypeEncoding::base64},
- {"png", sizeof("png"), imageMimeTypeEncoding::base64},
- {"webp", sizeof("webp"), imageMimeTypeEncoding::base64},
- {"svg+xml", sizeof("svg+xml"), imageMimeTypeEncoding::base64 | imageMimeTypeEncoding::utf8},
-};
-
-
-static bool _isValidImageMimeTypeAndEncoding(const char** href, const char** mimetype, imageMimeTypeEncoding* encoding) {
- if (strncmp(*href, "image/", sizeof("image/") - 1)) return false; //not allowed mime type
- *href += sizeof("image/") - 1;
-
- //RFC2397 data:[<mediatype>][;base64],<data>
- //mediatype := [ type "/" subtype ] *( ";" parameter )
- //parameter := attribute "=" value
- for (unsigned int i = 0; i < sizeof(imageMimeTypes) / sizeof(imageMimeTypes[0]); i++) {
- if (strncmp(*href, imageMimeTypes[i].name, imageMimeTypes[i].sz - 1)) continue;
- *href += imageMimeTypes[i].sz - 1;
- *mimetype = imageMimeTypes[i].name;
-
- while (**href && **href != ',') {
- while (**href && **href != ';') ++(*href);
- if (!**href) return false;
- ++(*href);
-
- if (imageMimeTypes[i].encoding & imageMimeTypeEncoding::base64) {
- if (!strncmp(*href, "base64,", sizeof("base64,") - 1)) {
- *href += sizeof("base64,") - 1;
- *encoding = imageMimeTypeEncoding::base64;
- return true; //valid base64
- }
- }
- if (imageMimeTypes[i].encoding & imageMimeTypeEncoding::utf8) {
- if (!strncmp(*href, "utf8,", sizeof("utf8,") - 1)) {
- *href += sizeof("utf8,") - 1;
- *encoding = imageMimeTypeEncoding::utf8;
- return true; //valid utf8
- }
- }
- }
- //no encoding defined
- if (**href == ',' && (imageMimeTypes[i].encoding & imageMimeTypeEncoding::utf8)) {
- ++(*href);
- *encoding = imageMimeTypeEncoding::utf8;
- return true; //allow no encoding defined if utf8 expected
- }
- return false;
- }
- return false;
-}
-
-#include "tvgTaskScheduler.h"
-
-static Paint* _imageBuildHelper(SvgLoaderData& loaderData, SvgNode* node, const Box& vBox, const string& svgPath)
-{
- if (!node->node.image.href || !strlen(node->node.image.href)) return nullptr;
-
- auto picture = Picture::gen();
-
- const char* href = node->node.image.href;
- if (!strncmp(href, "data:", sizeof("data:") - 1)) {
- href += sizeof("data:") - 1;
- const char* mimetype;
- imageMimeTypeEncoding encoding;
- if (!_isValidImageMimeTypeAndEncoding(&href, &mimetype, &encoding)) return nullptr; //not allowed mime type or encoding
- char *decoded = nullptr;
- if (encoding == imageMimeTypeEncoding::base64) {
- auto size = b64Decode(href, strlen(href), &decoded);
- if (picture->load(decoded, size, mimetype) != Result::Success) {
- tvg::free(decoded);
- return nullptr;
- }
- } else {
- auto size = svgUtilURLDecode(href, &decoded);
- if (picture->load(decoded, size, mimetype) != Result::Success) {
- tvg::free(decoded);
- return nullptr;
- }
- }
- loaderData.images.push(decoded);
- } else {
- if (!strncmp(href, "file://", sizeof("file://") - 1)) href += sizeof("file://") - 1;
- //TODO: protect against recursive svg image loading
- //Temporarily disable embedded svg:
- const char *dot = strrchr(href, '.');
- if (dot && STR_AS(dot, ".svg")) {
- TVGLOG("SVG", "Embedded svg file is disabled.");
- return nullptr;
- }
- string imagePath = href;
- if (strncmp(href, "/", 1)) {
- auto last = svgPath.find_last_of("/");
- imagePath = svgPath.substr(0, (last == string::npos ? 0 : last + 1)) + imagePath;
- }
- if (picture->load(imagePath.c_str()) != Result::Success) {
- return nullptr;
- }
- }
-
- float w, h;
- Matrix m;
- if (picture->size(&w, &h) == Result::Success && w > 0 && h > 0) {
- auto sx = node->node.image.w / w;
- auto sy = node->node.image.h / h;
- m = {sx, 0, node->node.image.x, 0, sy, node->node.image.y, 0, 0, 1};
- } else {
- m = tvg::identity();
- }
- if (node->transform) m = *node->transform * m;
- picture->transform(m);
-
- auto p = _applyFilter(loaderData, picture, node, vBox, svgPath);
- return _applyComposition(loaderData, p, node, vBox, svgPath);
-}
-
-
-static Matrix _calculateAspectRatioMatrix(AspectRatioAlign align, AspectRatioMeetOrSlice meetOrSlice, float width, float height, const Box& box)
-{
- auto sx = width / box.w;
- auto sy = height / box.h;
- auto tvx = box.x * sx;
- auto tvy = box.y * sy;
-
- if (align == AspectRatioAlign::None) return {sx, 0, -tvx, 0, sy, -tvy, 0, 0, 1};
-
- //Scale
- if (meetOrSlice == AspectRatioMeetOrSlice::Meet) {
- if (sx < sy) sy = sx;
- else sx = sy;
- } else {
- if (sx < sy) sx = sy;
- else sy = sx;
- }
-
- //Align
- tvx = box.x * sx;
- tvy = box.y * sy;
- auto tvw = box.w * sx;
- auto tvh = box.h * sy;
-
- switch (align) {
- case AspectRatioAlign::XMinYMin: {
- break;
- }
- case AspectRatioAlign::XMidYMin: {
- tvx -= (width - tvw) * 0.5f;
- break;
- }
- case AspectRatioAlign::XMaxYMin: {
- tvx -= width - tvw;
- break;
- }
- case AspectRatioAlign::XMinYMid: {
- tvy -= (height - tvh) * 0.5f;
- break;
- }
- case AspectRatioAlign::XMidYMid: {
- tvx -= (width - tvw) * 0.5f;
- tvy -= (height - tvh) * 0.5f;
- break;
- }
- case AspectRatioAlign::XMaxYMid: {
- tvx -= width - tvw;
- tvy -= (height - tvh) * 0.5f;
- break;
- }
- case AspectRatioAlign::XMinYMax: {
- tvy -= height - tvh;
- break;
- }
- case AspectRatioAlign::XMidYMax: {
- tvx -= (width - tvw) * 0.5f;
- tvy -= height - tvh;
- break;
- }
- case AspectRatioAlign::XMaxYMax: {
- tvx -= width - tvw;
- tvy -= height - tvh;
- break;
- }
- default: {
- break;
- }
- }
-
- return {sx, 0, -tvx, 0, sy, -tvy, 0, 0, 1};
-}
-
-
-static Scene* _useBuildHelper(SvgLoaderData& loaderData, const SvgNode* node, const Box& vBox, const string& svgPath, int depth)
-{
- auto scene = _sceneBuildHelper(loaderData, node, vBox, svgPath, false, depth + 1);
-
- // mUseTransform = mUseTransform * mTranslate
- auto mUseTransform = tvg::identity();
- if (node->transform) mUseTransform = *node->transform;
- if (node->node.use.x != 0.0f || node->node.use.y != 0.0f) {
- Matrix mTranslate = {1, 0, node->node.use.x, 0, 1, node->node.use.y, 0, 0, 1};
- mUseTransform *= mTranslate;
- }
-
- if (node->node.use.symbol) {
- auto symbol = node->node.use.symbol->node.symbol;
- auto width = (symbol.hasWidth ? symbol.w : vBox.w);
- if (node->node.use.isWidthSet) width = node->node.use.w;
- auto height = (symbol.hasHeight ? symbol.h : vBox.h);;
- if (node->node.use.isHeightSet) height = node->node.use.h;
- auto vw = (symbol.hasViewBox ? symbol.vw : width);
- auto vh = (symbol.hasViewBox ? symbol.vh : height);
-
- auto mViewBox = tvg::identity();
- if ((!tvg::equal(width, vw) || !tvg::equal(height, vh)) && vw > 0 && vh > 0) {
- Box box = {symbol.vx, symbol.vy, vw, vh};
- mViewBox = _calculateAspectRatioMatrix(symbol.align, symbol.meetOrSlice, width, height, box);
- } else if (!tvg::zero(symbol.vx) || !tvg::zero(symbol.vy)) {
- mViewBox = {1, 0, -symbol.vx, 0, 1, -symbol.vy, 0, 0, 1};
- }
-
- // mSceneTransform = mUseTransform * mSymbolTransform * mViewBox
- Matrix mSceneTransform = mViewBox;
- if (node->node.use.symbol->transform) {
- mSceneTransform = *node->node.use.symbol->transform * mViewBox;
- }
- mSceneTransform = mUseTransform * mSceneTransform;
- scene->transform(mSceneTransform);
-
- if (!node->node.use.symbol->node.symbol.overflowVisible) {
- auto viewBoxClip = Shape::gen();
- viewBoxClip->appendRect(0, 0, width, height);
-
- // mClipTransform = mUseTransform * mSymbolTransform
- Matrix mClipTransform = mUseTransform;
- if (node->node.use.symbol->transform) {
- mClipTransform = mUseTransform * *node->node.use.symbol->transform;
- }
- viewBoxClip->transform(mClipTransform);
-
- auto clippingLayer = Scene::gen();
- clippingLayer->clip(viewBoxClip);
- clippingLayer->add(scene);
- return clippingLayer;
- }
- return scene;
- }
-
- if (auto clipper = PAINT(scene)->clipper) {
- auto& clipTransform = clipper->transform();
- Matrix inv;
- if (node->transform && inverse(node->transform, &inv)) clipTransform = inv * clipTransform;
- clipTransform = mUseTransform * clipTransform ;
- }
-
- scene->transform(mUseTransform);
- return scene;
-}
-
-
-static void _applyTextFill(SvgStyleProperty* style, Text* text, const Box& vBox)
-{
- //If fill property is nullptr then do nothing
- if (style->fill.paint.none) {
- //Do nothing
- } else if (style->fill.paint.gradient) {
- auto bBox = style->fill.paint.gradient->userSpace ? vBox : _bounds(text);
- if (style->fill.paint.gradient->type == SvgGradientType::Linear) {
- text->fill(_applyLinearGradientProperty(style->fill.paint.gradient, bBox, style->fill.opacity));
- } else if (style->fill.paint.gradient->type == SvgGradientType::Radial) {
- text->fill(_applyRadialGradientProperty(style->fill.paint.gradient, bBox, style->fill.opacity));
- }
- } else if (style->fill.paint.url) {
- //TODO: Apply the color pointed by url
- TVGLOG("SVG", "The fill's url not supported.");
- } else if (style->fill.paint.curColor) {
- //Apply the current style color
- text->fill(style->color.r, style->color.g, style->color.b);
- text->opacity(style->fill.opacity);
- } else {
- //Apply the fill color
- text->fill(style->fill.paint.color.r, style->fill.paint.color.g, style->fill.paint.color.b);
- text->opacity(style->fill.opacity);
- }
-}
-
-
-static char* _processText(const char* text, SvgXmlSpace space)
-{
- if (!text) return nullptr;
-
- auto len = strlen(text);
- auto processed = (char*)tvg::malloc(len + 1);
- auto dst = processed;
- auto src = text;
-
- if (space == SvgXmlSpace::Preserve) {
- while (*src) {
- if (*src == '\n' || *src == '\t' || *src == '\r') *dst++ = ' ';
- else *dst++ = *src;
- src++;
- }
- *dst = '\0';
- } else {
- auto spaceFound = false;
- src = svgUtilSkipWhiteSpace(src, nullptr);
-
- while (*src) {
- if (isspace((unsigned char)*src)) {
- if (!spaceFound) {
- *dst++ = ' ';
- spaceFound = true;
- }
- } else {
- *dst++ = *src;
- spaceFound = false;
- }
- src++;
- }
- dst = (char*)svgUtilUnskipWhiteSpace(dst, processed);
- *dst = '\0';
- }
- return processed;
-}
-
-
-static Paint* _textBuildHelper(SvgLoaderData& loaderData, const SvgNode* node, const Box& vBox, const string& svgPath)
-{
- auto textNode = &node->node.text;
- if (!textNode->text) return nullptr;
-
- auto text = Text::gen();
-
- Matrix textTransform;
- if (node->transform) textTransform = *node->transform;
- else textTransform = tvg::identity();
-
- translateR(&textTransform, {node->node.text.x, node->node.text.y - textNode->fontSize});
- text->transform(textTransform);
-
- //TODO: handle def values of font and size as used in a system?
- auto size = textNode->fontSize * 0.75f; //1 pt = 1/72; 1 in = 96 px; -> 72/96 = 0.75
- if (text->font(textNode->fontFamily) != Result::Success) {
- text->font(nullptr); //fallback to any available font
- }
- text->size(size);
-
- // Handle xml:space
- auto xmlSpace = node->xmlSpace;
- auto parent = node->parent;
- while (xmlSpace == SvgXmlSpace::None && parent) {
- xmlSpace = parent->xmlSpace;
- parent = parent->parent;
- }
- if (xmlSpace == SvgXmlSpace::None) xmlSpace = SvgXmlSpace::Default;
- auto processedText = _processText(textNode->text, xmlSpace);
- text->text(processedText);
- tvg::free(processedText);
-
- _applyTextFill(node->style, text, vBox);
-
- auto p = _applyFilter(loaderData, text, node, vBox, svgPath);
- return _applyComposition(loaderData, p, node, vBox, svgPath);
-}
-
-
-static Scene* _sceneBuildHelper(SvgLoaderData& loaderData, const SvgNode* node, const Box& vBox, const string& svgPath, bool mask, int depth)
-{
- /* Exception handling: Prevent invalid SVG data input.
- The size is the arbitrary value, we need an experimental size. */
- if (depth > 2192) {
- TVGERR("SVG", "Infinite recursive call - stopped after %d calls! Svg file may be incorrectly formatted.", depth);
- return nullptr;
- }
-
- if (!_isGroupType(node->type) && !mask) return nullptr;
-
- auto scene = Scene::gen();
- // For a Symbol node, the viewBox transformation has to be applied first - see _useBuildHelper()
- if (!mask && node->transform && node->type != SvgNodeType::Symbol && node->type != SvgNodeType::Use) {
- scene->transform(*node->transform);
- }
-
- if (!node->style->display || node->style->opacity == 0) return scene;
-
- ARRAY_FOREACH(p, node->child) {
- auto child = *p;
- if (child->type == SvgNodeType::ClipPath || child->type == SvgNodeType::Filter) continue;
- if (_isGroupType(child->type)) {
- Paint* paint = nullptr;
- if (child->type == SvgNodeType::Use)
- paint = _useBuildHelper(loaderData, child, vBox, svgPath, depth + 1);
- else if (!(child->type == SvgNodeType::Symbol && node->type != SvgNodeType::Use))
- paint = _sceneBuildHelper(loaderData, child, vBox, svgPath, false, depth + 1);
- if (paint) {
- if (child->id) paint->id = djb2Encode(child->id);
- scene->add(paint);
- }
- } else {
- Paint* paint = nullptr;
- if (child->type == SvgNodeType::Image) paint = _imageBuildHelper(loaderData, child, vBox, svgPath);
- else if (child->type == SvgNodeType::Text) paint = _textBuildHelper(loaderData, child, vBox, svgPath);
- else if (child->type != SvgNodeType::Mask) paint = _shapeBuildHelper(loaderData, child, vBox, svgPath);
- if (paint) {
- if (child->id) paint->id = djb2Encode(child->id);
- scene->add(paint);
- }
- }
- }
- scene->opacity(node->style->opacity);
-
- auto p = _applyFilter(loaderData, scene, node, vBox, svgPath);
- return static_cast<Scene*>(_applyComposition(loaderData, p, node, vBox, svgPath));
-}
-
-
-static void _updateInvalidViewSize(Scene* scene, Box& vBox, float& w, float& h, SvgViewFlag viewFlag)
-{
- auto useW = (viewFlag & SvgViewFlag::Width);
- auto useH = (viewFlag & SvgViewFlag::Height);
- auto bbox = _bounds(scene);
-
- if (!useW && !useH) {
- vBox = bbox;
- } else {
- vBox.w = useW ? w : bbox.w;
- vBox.h = useH ? h : bbox.h;
- }
-
- //the size would have 1x1 or percentage values.
- if (!useW) w *= vBox.w;
- if (!useH) h *= vBox.h;
-}
-
-
-static void _loadFonts(Array<FontFace>& fonts)
-{
- if (fonts.empty()) return;
-
- static constexpr struct {
- const char* prefix;
- size_t len;
- } prefixes[] = {
- {"data:font/ttf;base64,", sizeof("data:font/ttf;base64,") - 1},
- {"data:application/font-ttf;base64,", sizeof("data:application/font-ttf;base64,") - 1}
- };
-
-
- ARRAY_FOREACH(p, fonts) {
- if (!p->name) continue;
-
- size_t shift = 0;
- for (const auto& prefix : prefixes) {
- if (p->srcLen > prefix.len && !memcmp(p->src, prefix.prefix, prefix.len)) {
- shift = prefix.len;
- break;
- }
- }
- if (shift == 0) {
- TVGLOG("SVG", "The embedded font \"%s\" data not loaded properly.", p->name);
- continue;
- }
-
- auto size = b64Decode(p->src + shift, p->srcLen - shift, &p->decoded);
-
- if (Text::load(p->name, p->decoded, size) != Result::Success) TVGERR("SVG", "Error while loading the ttf font named \"%s\".", p->name);
- }
-}
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-Scene* svgSceneBuild(SvgLoaderData& loaderData, Box vBox, float w, float h, AspectRatioAlign align, AspectRatioMeetOrSlice meetOrSlice, const string& svgPath, SvgViewFlag viewFlag)
-{
- //TODO: aspect ratio is valid only if viewBox was set
-
- if (!loaderData.doc || (loaderData.doc->type != SvgNodeType::Doc)) return nullptr;
-
- _loadFonts(loaderData.fonts);
-
- auto docNode = _sceneBuildHelper(loaderData, loaderData.doc, vBox, svgPath, false, 0);
-
- if (!(viewFlag & SvgViewFlag::Viewbox)) _updateInvalidViewSize(docNode, vBox, w, h, viewFlag);
-
- if (!tvg::equal(w, vBox.w) || !tvg::equal(h, vBox.h)) {
- Matrix m = _calculateAspectRatioMatrix(align, meetOrSlice, w, h, vBox);
- docNode->transform(m);
- } else if (!tvg::zero(vBox.x) || !tvg::zero(vBox.y)) {
- docNode->translate(-vBox.x, -vBox.y);
- }
-
- auto viewBoxClip = Shape::gen();
- viewBoxClip->appendRect(0, 0, w, h);
-
- auto clippingLayer = Scene::gen();
- clippingLayer->clip(viewBoxClip);
- clippingLayer->add(docNode);
-
- loaderData.doc->node.doc.vbox = vBox;
- loaderData.doc->node.doc.w = w;
- loaderData.doc->node.doc.h = h;
-
- auto root = Scene::gen();
- root->add(clippingLayer);
-
- return root;
-}
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.cpp b/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.cpp
index 6540c553f0c..014a519722e 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.cpp
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.cpp
@@ -20,6 +20,7 @@
* SOFTWARE.
*/
+#include "tvgMath.h"
#include "tvgStr.h"
#include "tvgSvgUtil.h"
@@ -58,6 +59,7 @@ const char* svgUtilSkipWhiteSpace(const char* itr, const char* itrEnd)
const char* svgUtilUnskipWhiteSpace(const char* itr, const char* itrStart)
{
+ if (itr == itrStart) return itr;
for (itr--; itr > itrStart; itr--) {
if (!isspace((unsigned char)*itr)) break;
}
@@ -103,3 +105,41 @@ size_t svgUtilURLDecode(const char *src, char** dst)
return idx + 1;
}
+void svgUtilHslToRgb(float h, float s, float l, uint8_t& r, uint8_t& g, uint8_t& b)
+{
+ if (tvg::zero(s)) {
+ r = g = b = (uint8_t)nearbyint(l * 255.0f);
+ return;
+ }
+
+ if (tvg::equal(h, 360.0f)) {
+ h = 0.0f;
+ } else {
+ h = fmod(h, 360.0f);
+ if (h < 0.0f) h += 360.0f;
+ h /= 60.0f;
+ }
+
+ auto v = (l <= 0.5f) ? (l * (1.0f + s)) : (l + s - (l * s));
+ auto p = l + l - v;
+ auto sv = tvg::zero(v) ? 0.0f : (v - p) / v;
+ auto i = static_cast<uint8_t>(h);
+ auto f = h - i;
+ auto vsf = v * sv * f;
+ auto t = p + vsf;
+ auto q = v - vsf;
+ float tr, tg, tb;
+
+ switch (i) {
+ case 0: tr = v; tg = t; tb = p; break;
+ case 1: tr = q; tg = v; tb = p; break;
+ case 2: tr = p; tg = v; tb = t; break;
+ case 3: tr = p; tg = q; tb = v; break;
+ case 4: tr = t; tg = p; tb = v; break;
+ case 5: tr = v; tg = p; tb = q; break;
+ default: tr = tg = tb = 0.0f; break;
+ }
+ r = (uint8_t)nearbyint(tr * 255.0f);
+ g = (uint8_t)nearbyint(tg * 255.0f);
+ b = (uint8_t)nearbyint(tb * 255.0f);
+}
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.h b/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.h
index 4cd1de351d9..3336b281fb5 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.h
+++ b/thirdparty/thorvg/src/loaders/svg/tvgSvgUtil.h
@@ -30,5 +30,6 @@ const char* svgUtilSkipWhiteSpace(const char* itr, const char* itrEnd);
const char* svgUtilUnskipWhiteSpace(const char* itr, const char* itrStart);
const char* svgUtilSkipWhiteSpaceAndComma(const char* content);
size_t svgUtilURLDecode(const char *src, char** dst);
+void svgUtilHslToRgb(float h, float s, float l, uint8_t& r, uint8_t& g, uint8_t& b);
#endif //_TVG_SVG_UTIL_H_
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp b/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp
index f67aa0f85c5..68bcc422d38 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp
+++ b/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.cpp
@@ -68,76 +68,53 @@ static const char* _xmlFindWhiteSpace(const char* itr, const char* itrEnd)
return itr;
}
-
-static const char* _xmlSkipXmlEntities(const char* itr, const char* itrEnd)
+struct XmlEntity
{
- auto p = itr;
- while (itr < itrEnd && *itr == '&') {
- for (int i = 0; i < NUMBER_OF_XML_ENTITIES; ++i) {
- if (strncmp(itr, xmlEntity[i], xmlEntityLength[i]) == 0) {
- itr += xmlEntityLength[i];
- break;
- }
- }
- if (itr == p) break;
- p = itr;
- }
- return itr;
-}
-
-
-static const char* _xmlUnskipXmlEntities(const char* itr, const char* itrStart)
+ const char* name;
+ uint8_t length;
+ char decoded;
+};
+
+static constexpr XmlEntity xmlEntities[] = {
+ {"&#10;", 5, '\n'},
+ {"&#035;", 6, '#'},
+ {"&#039;", 6, '\''},
+ {"&quot;", 6, '"'},
+ {"&nbsp;", 6, ' '},
+ {"&apos;", 6, '\''},
+ {"&amp;", 5, '&'},
+ {"&lt;", 4, '<'},
+ {"&gt;", 4, '>'},
+};
+
+static const XmlEntity* _xmlFindEntity(const char* itr, const char* itrEnd)
{
- auto p = itr;
- while (itr > itrStart && *(itr - 1) == ';') {
- for (int i = 0; i < NUMBER_OF_XML_ENTITIES; ++i) {
- if (itr - xmlEntityLength[i] > itrStart &&
- strncmp(itr - xmlEntityLength[i], xmlEntity[i], xmlEntityLength[i]) == 0) {
- itr -= xmlEntityLength[i];
- break;
- }
- }
- if (itr == p) break;
- p = itr;
- }
- return itr;
-}
-
-
-static const char* _skipWhiteSpacesAndXmlEntities(const char* itr, const char* itrEnd)
-{
- itr = svgUtilSkipWhiteSpace(itr, itrEnd);
- auto p = itr;
- while (true) {
- if (p != (itr = _xmlSkipXmlEntities(itr, itrEnd))) p = itr;
- else break;
- if (p != (itr = svgUtilSkipWhiteSpace(itr, itrEnd))) p = itr;
- else break;
+ for (auto& entity : xmlEntities) {
+ if (itrEnd - itr >= entity.length && !memcmp(itr, entity.name, entity.length)) return &entity;
}
- return itr;
+ return nullptr;
}
-
-static const char* _unskipWhiteSpacesAndXmlEntities(const char* itr, const char* itrStart)
+static unsigned _xmlDecodeEntities(const char* itr, const char* itrEnd, char* decoded)
{
- itr = svgUtilUnskipWhiteSpace(itr, itrStart);
- auto p = itr;
- while (true) {
- if (p != (itr = _xmlUnskipXmlEntities(itr, itrStart))) p = itr;
- else break;
- if (p != (itr = svgUtilUnskipWhiteSpace(itr, itrStart))) p = itr;
- else break;
+ auto dst = decoded;
+ while (itr < itrEnd) {
+ auto entity = (*itr == '&') ? _xmlFindEntity(itr, itrEnd) : nullptr;
+ if (!entity) *dst++ = *itr++;
+ else {
+ *dst++ = entity->decoded;
+ itr += entity->length;
+ }
}
- return itr;
+ *dst = '\0';
+ return dst - decoded;
}
-
static const char* _xmlFindStartTag(const char* itr, const char* itrEnd)
{
return (const char*)memchr(itr, '<', itrEnd - itr);
}
-
static const char* _xmlFindEndTag(const char* itr, const char* itrEnd)
{
bool insideQuote[2] = {false, false}; // 0: ", 1: '
@@ -240,6 +217,7 @@ const char* xmlNodeTypeToString(TVG_UNUSED SvgNodeType type)
"Symbol",
"Filter",
"GaussianBlur",
+ "Pattern",
"Unknown",
};
return TYPE_NAMES[(int) type];
@@ -268,13 +246,15 @@ bool isIgnoreUnsupportedLogElements(TVG_UNUSED const char* tagName)
bool xmlParseAttributes(const char* buf, unsigned bufLength, xmlAttributeCb func, const void* data)
{
+ if (!buf || !func) return false;
+
const char *itr = buf, *itrEnd = buf + bufLength;
char* tmpBuf = tvg::malloc<char>(bufLength + 1);
- if (!buf || !func || !tmpBuf) goto error;
+ if (!tmpBuf) return false;
while (itr < itrEnd) {
- const char* p = _skipWhiteSpacesAndXmlEntities(itr, itrEnd);
+ const char* p = svgUtilSkipWhiteSpace(itr, itrEnd);
const char *key, *keyEnd, *value, *valueEnd;
char* tval;
@@ -296,39 +276,36 @@ bool xmlParseAttributes(const char* buf, unsigned bufLength, xmlAttributeCb func
if (!value) goto error;
value++;
}
- keyEnd = _xmlUnskipXmlEntities(keyEnd, key);
-
- value = _skipWhiteSpacesAndXmlEntities(value, itrEnd);
+ value = svgUtilSkipWhiteSpace(value, itrEnd);
if (value == itrEnd) goto error;
if ((*value == '"') || (*value == '\'')) {
- valueEnd = (const char*)memchr(value + 1, *value, itrEnd - value);
+ valueEnd = (const char*)memchr(value + 1, *value, itrEnd - value - 1);
if (!valueEnd) goto error;
value++;
} else {
valueEnd = _xmlFindWhiteSpace(value, itrEnd);
}
- itr = valueEnd + 1;
+ itr = (valueEnd < itrEnd) ? valueEnd + 1 : valueEnd;
- value = _skipWhiteSpacesAndXmlEntities(value, itrEnd);
- valueEnd = _unskipWhiteSpacesAndXmlEntities(valueEnd, value);
+ value = svgUtilSkipWhiteSpace(value, valueEnd);
+ if (value < valueEnd) valueEnd = svgUtilUnskipWhiteSpace(valueEnd, value);
memcpy(tmpBuf, key, keyEnd - key);
tmpBuf[keyEnd - key] = '\0';
tval = tmpBuf + (keyEnd - key) + 1;
- int i = 0;
- while (value < valueEnd) {
- value = _xmlSkipXmlEntities(value, valueEnd);
- tval[i++] = *value;
- value++;
+ auto decodedLength = _xmlDecodeEntities(value, valueEnd, tval);
+ if (decodedLength) {
+ auto decodedEnd = svgUtilUnskipWhiteSpace(tval + decodedLength, tval);
+ *const_cast<char*>(decodedEnd) = '\0';
+ tval = const_cast<char*>(svgUtilSkipWhiteSpace(tval, decodedEnd));
}
- tval[i] = '\0';
if (!func((void*)data, tmpBuf, tval)) {
if (_unsupported(tmpBuf, tval)) {
- TVGLOG("SVG", "Unsupported attributes used [Elements type: %s][Id : %s][Attribute: %s][Value: %s]", xmlNodeTypeToString(((SvgLoaderData*)data)->svgParse->node->type), ((SvgLoaderData*)data)->svgParse->node->id ? ((SvgLoaderData*)data)->svgParse->node->id : "NO_ID", tmpBuf, tval ? tval : "NONE");
+ TVGLOG("SVG", "Unsupported attributes used [Elements type: %s][Id : %s][Attribute: %s][Value: %s]", xmlNodeTypeToString(((SvgParserContext*)data)->parser->node->type), ((SvgParserContext*)data)->parser->node->id ? ((SvgParserContext*)data)->parser->node->id : "NO_ID", tmpBuf, tval ? tval : "NONE");
}
}
}
@@ -395,8 +372,8 @@ bool xmlParse(const char* buf, unsigned bufLength, bool strip, xmlCb func, const
}
if (strip && (type != XMLType::CData)) {
- start = _skipWhiteSpacesAndXmlEntities(start, end);
- end = _unskipWhiteSpacesAndXmlEntities(end, start);
+ start = svgUtilSkipWhiteSpace(start, end);
+ end = svgUtilUnskipWhiteSpace(end, start);
}
if (!func((void*)data, type, start, (unsigned int)(end - start))) return false;
@@ -408,10 +385,10 @@ bool xmlParse(const char* buf, unsigned bufLength, bool strip, xmlCb func, const
} else {
const char *p, *end;
- if (strip && ((SvgLoaderData*)data)->openedTag != OpenedTagType::Text) {
+ if (strip && ((SvgParserContext*)data)->openedTag != OpenedTagType::Text) {
p = itr;
- p = _skipWhiteSpacesAndXmlEntities(p, itrEnd);
- if (p) {
+ p = svgUtilSkipWhiteSpace(p, itrEnd);
+ if (p != itr) {
if (!func((void*)data, XMLType::Ignored, itr, (unsigned int)(p - itr))) return false;
itr = p;
}
@@ -421,9 +398,19 @@ bool xmlParse(const char* buf, unsigned bufLength, bool strip, xmlCb func, const
if (!p) p = itrEnd;
end = p;
- if (strip && ((SvgLoaderData*)data)->openedTag != OpenedTagType::Text) end = _unskipWhiteSpacesAndXmlEntities(end, itr);
-
- if (itr != end && !func((void*)data, XMLType::Data, itr, (unsigned int)(end - itr))) return false;
+ if (strip && ((SvgParserContext*)data)->openedTag != OpenedTagType::Text) end = svgUtilUnskipWhiteSpace(end, itr);
+
+ if (itr != end) {
+ auto length = (unsigned int)(end - itr);
+ if (memchr(itr, '&', length)) {
+ auto decoded = tvg::malloc<char>(length + 1);
+ if (!decoded) return false;
+ auto decodedLength = _xmlDecodeEntities(itr, end, decoded);
+ auto result = func((void*)data, XMLType::Data, decoded, decodedLength);
+ tvg::free(decoded);
+ if (!result) return false;
+ } else if (!func((void*)data, XMLType::Data, itr, length)) return false;
+ }
if (strip && (end < p) && !func((void*)data, XMLType::Ignored, end, (unsigned int)(p - end))) return false;
@@ -447,35 +434,37 @@ bool xmlParseW3CAttribute(const char* buf, unsigned bufLength, xmlAttributeCb fu
auto val = vmem;
do {
- auto sep = (char*)strchr(buf, ':');
- auto next = (char*)strchr(buf, ';');
-
- if (auto src = strstr(buf, "src")) {//src tag from css font-face contains extra semicolon
- if (src < sep) {
- if (next + 1 < end) next = (char*)strchr(next + 1, ';');
- else break;
- }
+ auto sep = (const char*)memchr(buf, ':', end - buf);
+ auto next = (const char*)memchr(buf, ';', end - buf);
+ if (!sep) sep = end;
+ if (!next) next = end;
+ auto src = buf;
+ while (sep - src >= 3 && memcmp(src, "src", 3)) ++src;
+ if (sep - src < 3) src = sep;
+
+ if (sep < end && next < end && src < sep) { // src tag from css font-face contains extra semicolon
+ if (next + 1 < end) {
+ next = (const char*)memchr(next + 1, ';', end - next - 1);
+ if (!next) next = end;
+ } else break;
}
- if (sep >= end) next = sep = nullptr;
- if (next >= end) next = nullptr;
-
key[0] = '\0';
val[0] = '\0';
- if (sep != nullptr && next == nullptr) {
+ if (sep < end && next >= end) {
memcpy(key, buf, sep - buf);
key[sep - buf] = '\0';
memcpy(val, sep + 1, end - sep - 1);
val[end - sep - 1] = '\0';
- } else if (sep != nullptr && sep < next) {
+ } else if (sep < end && sep < next) {
memcpy(key, buf, sep - buf);
key[sep - buf] = '\0';
memcpy(val, sep + 1, next - sep - 1);
val[next - sep - 1] = '\0';
- } else if (next) {
+ } else if (next < end) {
memcpy(key, buf, next - buf);
key[next - buf] = '\0';
}
@@ -487,11 +476,11 @@ bool xmlParseW3CAttribute(const char* buf, unsigned bufLength, xmlAttributeCb fu
if (!func((void*)data, key, val)) {
if (!_unsupported(key, val)) {
- TVGLOG("SVG", "Unsupported attributes used [Elements type: %s][Id : %s][Attribute: %s][Value: %s]", xmlNodeTypeToString(((SvgLoaderData*)data)->svgParse->node->type), ((SvgLoaderData*)data)->svgParse->node->id ? ((SvgLoaderData*)data)->svgParse->node->id : "NO_ID", key, val ? val : "NONE");
+ TVGLOG("SVG", "Unsupported attributes used [Elements type: %s][Id : %s][Attribute: %s][Value: %s]", xmlNodeTypeToString(((SvgParserContext*)data)->parser->node->type), ((SvgParserContext*)data)->parser->node->id ? ((SvgParserContext*)data)->parser->node->id : "NO_ID", key, val ? val : "NONE");
}
}
}
- if (!next) break;
+ if (next >= end) break;
buf = next + 1;
} while (true);
@@ -552,11 +541,9 @@ const char* xmlFindAttributesTag(const char* buf, unsigned bufLength)
//User skip tagname and already gave it the attributes.
if (*itr == '=') return buf;
} else {
- itr = _xmlUnskipXmlEntities(itr, buf);
- if (itr == itrEnd) return nullptr;
return itr;
}
}
- return nullptr;
+ return itrEnd;
}
diff --git a/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.h b/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.h
index c85431be8fd..c2b8bfc0aac 100644
--- a/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.h
+++ b/thirdparty/thorvg/src/loaders/svg/tvgXmlParser.h
@@ -23,11 +23,7 @@
#ifndef _TVG_XML_PARSER_H_
#define _TVG_XML_PARSER_H_
-#include "tvgSvgLoaderCommon.h"
-
-#define NUMBER_OF_XML_ENTITIES 9
-const char* const xmlEntity[] = {"&#10;", "&quot;", "&nbsp;", "&apos;", "&amp;", "&lt;", "&gt;", "&#035;", "&#039;"};
-const int xmlEntityLength[] = {5, 6, 6, 6, 5, 4, 4, 6, 6};
+#include "tvgSvgCommon.h"
enum class XMLType
{
diff --git a/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwBlendOp.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwBlendOp.cpp
new file mode 100644
index 00000000000..7f428d6d226
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwBlendOp.cpp
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2026 ThorVG project. All rights reserved.
+
+ * 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 "tvgSwCommon.h"
+
+/************************************************************************/
+/* Internal Class Implementation */
+/************************************************************************/
+
+static uint32_t _premultiply(uint32_t c1, uint32_t c2, uint8_t a)
+{
+ if (a == 255) return c1;
+ else if (a == 0) return c2;
+ return ALPHA_BLEND(c1, a) + ALPHA_BLEND(c2, 255 - a);
+}
+
+static RenderColor _unpremultiply(uint32_t c)
+{
+ RenderColor o = {C1(c), C2(c), C3(c), A(c)};
+ if (o.a > 0 && o.a < 255) {
+ o.r = std::min(o.r * 255u / o.a, 255u);
+ o.g = std::min(o.g * 255u / o.a, 255u);
+ o.b = std::min(o.b * 255u / o.a, 255u);
+ }
+ return o;
+}
+
+static void _saturate(uint8_t& c1, uint8_t& c2, uint8_t& c3, const uint8_t& s1, const uint8_t& s2, const uint8_t& s3)
+{
+ // to saturation
+ auto s = std::max(s1, std::max(s2, s3)) - std::min(s1, std::min(s2, s3));
+
+ uint8_t v[3] = {c1, c2, c3};
+ int lo = 0, mid = 1, hi = 2;
+
+ if (v[lo] > v[mid]) std::swap(lo, mid);
+ if (v[mid] > v[hi]) std::swap(mid, hi);
+ if (v[lo] > v[mid]) std::swap(lo, mid);
+
+ auto minv = v[lo];
+ auto maxv = v[hi];
+
+ if (maxv > minv) {
+ v[mid] = uint8_t((int(v[mid] - minv) * s) / (maxv - minv));
+ v[hi] = s;
+ } else {
+ v[mid] = v[hi] = 0;
+ }
+
+ v[lo] = 0;
+ c1 = v[0];
+ c2 = v[1];
+ c3 = v[2];
+}
+
+static void _luminance(uint8_t& c1, uint8_t& c2, uint8_t& c3, int cl, int l)
+{
+ auto d = l - cl;
+ auto r = int(c1) + d;
+ auto g = int(c2) + d;
+ auto b = int(c3) + d;
+ auto minv = std::min(r, std::min(g, b));
+ auto maxv = std::max(r, std::max(g, b));
+
+ if (minv < 0) {
+ r = l + ((r - l) * l) / (l - minv);
+ g = l + ((g - l) * l) / (l - minv);
+ b = l + ((b - l) * l) / (l - minv);
+ maxv = std::max(r, std::max(g, b));
+ }
+
+ if (maxv > 255) {
+ r = l + ((r - l) * (255 - l)) / (maxv - l);
+ g = l + ((g - l) * (255 - l)) / (maxv - l);
+ b = l + ((b - l) * (255 - l)) / (maxv - l);
+ }
+
+ c1 = static_cast<uint8_t>(r);
+ c2 = static_cast<uint8_t>(g);
+ c3 = static_cast<uint8_t>(b);
+}
+
+/************************************************************************/
+/* External Class Implementation */
+/************************************************************************/
+
+uint32_t blendDifference(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto f = [](uint8_t s, uint8_t d) {
+ return (s > d) ? (s - d) : (d - s);
+ };
+
+ return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
+}
+
+uint32_t blendExclusion(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto f = [](uint8_t s, uint8_t d) {
+ return tvg::clamp(s + d - 2 * MULTIPLY(s, d), 0, 255);
+ };
+
+ return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
+}
+
+uint32_t blendAdd(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto f = [](uint8_t s, uint8_t d) {
+ return std::min(s + d, 255);
+ };
+
+ return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
+}
+
+uint32_t blendScreen(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto f = [](uint8_t s, uint8_t d) {
+ return s + d - MULTIPLY(s, d);
+ };
+
+ return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
+}
+
+uint32_t blendMultiply(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) {
+ return MULTIPLY(s, d);
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendOverlay(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) {
+ return (d < 128) ? std::min(255, 2 * MULTIPLY(s, d)) : (255 - std::min(255, 2 * MULTIPLY(255 - s, 255 - d)));
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendDarken(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) {
+ return std::min(s, d);
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendLighten(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto f = [](uint8_t s, uint8_t d) {
+ return std::max(s, d);
+ };
+
+ return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
+}
+
+uint32_t blendColorDodge(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) {
+ return d == 0 ? 0 : (s == 255 ? 255 : std::min(d * 255 / (255 - s), 255));
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendColorBurn(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) {
+ return d == 255 ? 255 : (s == 0 ? 0 : 255 - std::min((255 - d) * 255 / s, 255));
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendHardLight(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) {
+ return (s < 128) ? std::min(255, 2 * MULTIPLY(s, d)) : (255 - std::min(255, 2 * MULTIPLY(255 - s, 255 - d)));
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendSoftLight(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto f = [](uint8_t s, uint8_t d) -> uint8_t {
+ if (s <= 127) return (d - ((255 - 2 * s) * d * (255 - d)) / 65025);
+
+ // use Look up table for skip sqrt per every pixels.
+ static constexpr uint8_t SQRT_LUT[256] = {
+ 0, 15, 22, 27, 31, 35, 39, 42, 45, 47, 50, 52, 55, 57, 59, 61,
+ 63, 65, 67, 69, 71, 73, 74, 76, 78, 79, 81, 82, 84, 85, 87, 88,
+ 90, 91, 93, 94, 95, 97, 98, 99, 100, 102, 103, 104, 105, 107, 108, 109,
+ 110, 111, 112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
+ 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 141,
+ 142, 143, 144, 145, 146, 147, 148, 148, 149, 150, 151, 152, 153, 153, 154, 155,
+ 156, 157, 158, 158, 159, 160, 161, 162, 162, 163, 164, 165, 165, 166, 167, 168,
+ 168, 169, 170, 171, 171, 172, 173, 174, 174, 175, 176, 177, 177, 178, 179, 179,
+ 180, 181, 182, 182, 183, 184, 184, 185, 186, 186, 187, 188, 188, 189, 190, 190,
+ 191, 192, 192, 193, 194, 194, 195, 196, 196, 197, 198, 198, 199, 200, 200, 201,
+ 201, 202, 203, 203, 204, 205, 205, 206, 206, 207, 208, 208, 209, 210, 210, 211,
+ 211, 212, 213, 213, 214, 214, 215, 216, 216, 217, 217, 218, 218, 219, 220, 220,
+ 221, 221, 222, 222, 223, 224, 224, 225, 225, 226, 226, 227, 228, 228, 229, 229,
+ 230, 230, 231, 231, 232, 233, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238,
+ 238, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246,
+ 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 255};
+ auto D = (d <= 64) ? (4 * d - (12 * d * d) / 255 + (16 * d * d * d) / 65025) : SQRT_LUT[d];
+ return static_cast<uint8_t>(d + ((2 * s - 255) * (D - d)) / 255);
+ };
+
+ return _premultiply(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
+}
+
+uint32_t blendHue(const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto c1 = C1(s);
+ auto c2 = C2(s);
+ auto c3 = C3(s);
+ _saturate(c1, c2, c3, o.r, o.g, o.b);
+ _luminance(c1, c2, c3, surface->luma((c1 << 16 | c2 << 8 | c3)), surface->luma((o.r << 16 | o.g << 8 | o.b)));
+
+ return _premultiply(JOIN(255, c1, c2, c3), s, o.a);
+}
+
+uint32_t blendSaturation(const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto c1 = o.r;
+ auto c2 = o.g;
+ auto c3 = o.b;
+ _saturate(c1, c2, c3, C1(s), C2(s), C3(s));
+ _luminance(c1, c2, c3, surface->luma((c1 << 16 | c2 << 8 | c3)), surface->luma((o.r << 16 | o.g << 8 | o.b)));
+
+ return _premultiply(JOIN(255, c1, c2, c3), s, o.a);
+}
+
+uint32_t blendColor(const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ auto c1 = C1(s);
+ auto c2 = C2(s);
+ auto c3 = C3(s);
+ _luminance(c1, c2, c3, surface->luma(s), surface->luma((o.r << 16 | o.g << 8 | o.b)));
+
+ return _premultiply(JOIN(255, c1, c2, c3), s, o.a);
+}
+
+uint32_t blendLuminosity(const SwSurface* surface, uint32_t s, uint32_t d)
+{
+ auto o = _unpremultiply(d);
+
+ _luminance(o.r, o.g, o.b, surface->luma((o.r << 16 | o.g << 8 | o.b)), surface->luma(s));
+
+ return _premultiply(JOIN(255, o.r, o.g, o.b), s, o.a);
+}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwCommon.h b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwCommon.h
similarity index 54%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwCommon.h
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwCommon.h
index 0875c40b07e..4cd4d9934ec 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwCommon.h
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwCommon.h
@@ -29,17 +29,14 @@
#include "tvgColor.h"
#include "tvgRender.h"
-#define SW_CURVE_TYPE_POINT 0
-#define SW_CURVE_TYPE_CUBIC 1
-#define SW_ANGLE_PI (180L << 16)
-#define SW_ANGLE_2PI (SW_ANGLE_PI << 1)
-#define SW_ANGLE_PI2 (SW_ANGLE_PI >> 1)
+#ifdef THORVG_OPENMP_SUPPORT
+ #include <omp.h>
+#endif
+
#define SW_COLOR_TABLE 1024
-static inline float TO_FLOAT(int32_t val)
-{
- return static_cast<float>(val) / 64.0f;
-}
+struct SwCompositor;
+struct SwSurface;
struct SwPoint
{
@@ -94,7 +91,7 @@ struct SwPoint
Point toPoint() const
{
- return {TO_FLOAT(x), TO_FLOAT(y)};
+ return {static_cast<float>(x) / 64.0f, static_cast<float>(y) / 64.0f};
}
};
@@ -105,23 +102,31 @@ struct SwSize
struct SwOutline
{
- Array<SwPoint> pts; //the outline's points
- Array<uint32_t> cntrs; //the contour end points
- Array<uint8_t> types; //curve type
- Array<bool> closed; //opened or closed path?
+ /**
+ * A shape refers to the renderer's path as is.
+ * trim, dash, stroke and image build theirs in the per-thread pool path (SwMpool::paths).
+ */
+ const RenderPath* path;
+
+ /**
+ * path->pts transformed into fixed-point form by utilExport().
+ * rle walks path->cmds and reads the coordinates from here.
+ */
+ Array<SwPoint> out;
+
FillRule fillRule;
};
struct SwSpan
{
- uint16_t x, y;
- uint16_t len;
+ int32_t x, y;
+ int32_t len;
uint8_t coverage;
bool fetch(const RenderRegion& bbox, int32_t& x, int32_t& len) const
{
- x = std::max((int32_t)this->x, bbox.min.x);
- len = std::min((int32_t)(this->x + this->len), bbox.max.x) - x;
+ x = std::max((int32_t)this->x, bbox.xMin);
+ len = std::min((int32_t)(this->x + this->len), bbox.xMax) - x;
return (len > 0) ? true : false;
}
};
@@ -132,10 +137,10 @@ struct SwRle
const SwSpan* fetch(const RenderRegion& bbox, const SwSpan** end) const
{
- return fetch(bbox.min.y, bbox.max.y - 1, end);
+ return fetch(bbox.yMin, bbox.yMax - 1, end);
}
- const SwSpan* fetch(int32_t min, uint32_t max, const SwSpan** end) const
+ const SwSpan* fetch(int32_t min, int32_t max, const SwSpan** end) const
{
const SwSpan* begin;
@@ -162,13 +167,11 @@ struct SwRle
SwSpan* data() const { return spans.data; }
};
-using Area = long;
-
struct SwCell
{
int32_t x;
int32_t cover;
- Area area;
+ long area;
SwCell *next;
};
@@ -187,13 +190,26 @@ struct SwFill
float invA, a;
};
+ struct SwConic {
+ float a11, a12, a13;
+ float a21, a22, a23;
+ float cx, cy;
+ float offset;
+ Point normal;
+ float invFwidth;
+ float distanceDx, seamProjectionDx;
+ };
+
union {
SwLinear linear;
SwRadial radial;
+ SwConic conic;
};
uint32_t ctable[SW_COLOR_TABLE];
+ float extent;
FillSpread spread;
+ Type type;
bool solid = false; //solid color fill with the last color from colorStops
bool translucent;
@@ -201,7 +217,7 @@ struct SwFill
struct SwStrokeBorder
{
- Array<SwPoint> pts;
+ Array<Point> pts;
uint8_t* tags = nullptr;
int32_t start = 0; //index of current sub-path start point
bool movable = false; //true: for ends of lineto borders
@@ -214,21 +230,18 @@ struct SwStrokeBorder
struct SwStroke
{
- int64_t angleIn;
- int64_t angleOut;
- SwPoint center;
- int64_t lineLength;
- int64_t subPathAngle;
- SwPoint ptStartSubPath;
- int64_t subPathLineLength;
- int64_t width;
- int64_t miterlimit;
- SwFill* fill = nullptr;
+ float angleIn, angleOut;
+ Point center;
+ float length;
+ float subPathAngle;
+ Point subPathStart;
+ float subPathLength;
+ float width;
+ float miterlimit;
+ SwFill* fill;
SwStrokeBorder* borders[2];
- float sx, sy;
StrokeCap cap;
StrokeJoin join;
- StrokeJoin joinSaved;
bool firstPt;
bool closedSubPath;
bool handleWideStrokes;
@@ -236,7 +249,7 @@ struct SwStroke
struct SwDashStroke
{
- SwOutline* outline = nullptr;
+ RenderPath* path = nullptr;
float curLen = 0;
int32_t curIdx = 0;
Point ptStart = {0, 0};
@@ -274,22 +287,21 @@ struct SwImage
uint8_t channelSize;
FilterMethod filter;
- bool direct = false; //draw image directly (with offset)
- bool scaled = false; //draw scaled image
+ bool direct = false; // draw image directly (with offset)
+ bool scaled = false; // draw uniform scaled image
+ bool alphaIgnored = false; // If true, the alpha channel can be ignored.
};
-typedef uint8_t(*SwMask)(uint8_t s, uint8_t d, uint8_t a); //src, dst, alpha
-typedef uint32_t(*SwBlender)(uint32_t s, uint32_t d); //src, dst
-typedef uint32_t(*SwBlenderA)(uint32_t s, uint32_t d, uint8_t a); //src, dst, alpha
-typedef uint32_t(*SwJoin)(uint8_t r, uint8_t g, uint8_t b, uint8_t a); //color channel join
-typedef uint8_t(*SwAlpha)(uint8_t*); //blending alpha
-
-struct SwCompositor;
+typedef uint8_t (*SwMask)(uint8_t s, uint8_t d, uint8_t a); // src, dst, alpha
+typedef uint32_t (*SwBlender)(const SwSurface* surface, uint32_t s, uint32_t d); // src, dst
+typedef uint32_t (*SwBlenderA)(uint32_t s, uint32_t d, uint8_t a); // src, dst, alpha
+typedef uint32_t (*SwJoin)(uint8_t r, uint8_t g, uint8_t b, uint8_t a); // color channel join
+typedef uint8_t (*SwAlpha)(uint8_t*); // blending alpha
struct SwSurface : RenderSurface
{
SwJoin join;
- SwAlpha alphas[4]; //Alpha:2, InvAlpha:3, Luma:4, InvLuma:5
+ SwAlpha alphas[4]; // Alpha:0, InvAlpha:1, Luma:2, InvLuma:3
SwBlender blender = nullptr; //blender (optional)
SwCompositor* compositor = nullptr; //compositor (optional)
BlendMethod blendMethod = BlendMethod::Normal;
@@ -300,10 +312,13 @@ struct SwSurface : RenderSurface
return alphas[idx > 3 ? 0 : idx]; //CompositeMethod has only four Matting methods.
}
- SwSurface()
+ uint8_t luma(const uint32_t& c) const
{
+ return alphas[2]((uint8_t*)&c);
}
+ SwSurface() = default;
+
SwSurface(const SwSurface* rhs) : RenderSurface(rhs)
{
join = rhs->join;
@@ -337,6 +352,7 @@ struct SwCellPool
struct SwMpool
{
SwOutline* outlines;
+ RenderPath* paths;
SwStrokeBorder* lBorders;
SwStrokeBorder* rBorders;
SwCellPool* cellPools;
@@ -345,6 +361,7 @@ struct SwMpool
{
auto allocSize = threads + 1;
outlines = new SwOutline[allocSize];
+ paths = new RenderPath[allocSize];
lBorders = new SwStrokeBorder[allocSize];
rBorders = new SwStrokeBorder[allocSize];
cellPools = new SwCellPool[allocSize];
@@ -353,6 +370,7 @@ struct SwMpool
~SwMpool()
{
delete[] (outlines);
+ delete[] (paths);
delete[] (lBorders);
delete[] (rBorders);
delete[] (cellPools);
@@ -365,10 +383,9 @@ struct SwMpool
SwOutline* outline(unsigned idx)
{
- outlines[idx].pts.clear();
- outlines[idx].cntrs.clear();
- outlines[idx].types.clear();
- outlines[idx].closed.clear();
+ paths[idx].clear();
+ outlines[idx].path = &paths[idx];
+ outlines[idx].out.clear();
return &outlines[idx];
}
@@ -388,11 +405,6 @@ struct SwMpool
}
};
-static inline int32_t TO_SWCOORD(float val)
-{
- return int32_t(val * 64.0f);
-}
-
static inline uint32_t JOIN(uint8_t c0, uint8_t c1, uint8_t c2, uint8_t c3)
{
return (c0 << 24 | c1 << 16 | c2 << 8 | c3);
@@ -414,11 +426,6 @@ static inline uint8_t INTERPOLATE8(uint8_t s, uint8_t d, uint8_t a)
return (((s) * (a) + 0xff) >> 8) + (((d) * ~(a) + 0xff) >> 8);
}
-static inline int32_t HALF_STROKE(float width)
-{
- return TO_SWCOORD(width * 0.5f);
-}
-
static inline uint8_t A(uint32_t c)
{
return ((c) >> 24);
@@ -449,22 +456,16 @@ static inline uint32_t PREMULTIPLY(uint32_t c, uint8_t a)
return (c & 0xff000000) + ((((c >> 8) & 0xff) * a) & 0xff00) + ((((c & 0x00ff00ff) * a) >> 8) & 0x00ff00ff);
}
-static inline RenderColor BLEND_UPRE(uint32_t c)
+static inline uint32_t UNPREMULTIPLY(uint32_t data)
{
- RenderColor o = {C1(c), C2(c), C3(c), A(c)};
- if (o.a > 0 && o.a < 255) {
- o.r = std::min(o.r * 255u / o.a, 255u);
- o.g = std::min(o.g * 255u / o.a, 255u);
- o.b = std::min(o.b * 255u / o.a, 255u);
- }
- return o;
-}
+ auto a = A(data);
+ if (a == 255 || a == 0) return data;
-static inline uint32_t BLEND_PRE(uint32_t c1, uint32_t c2, uint8_t a)
-{
- if (a == 255) return c1;
- else if (a == 0) return c2;
- return ALPHA_BLEND(c1, a) + ALPHA_BLEND(c2, 255 - a);
+ uint8_t r = std::min(C1(data) * 255u / a, 255u);
+ uint8_t g = std::min(C2(data) * 255u / a, 255u);
+ uint8_t b = std::min(C3(data) * 255u / a, 255u);
+
+ return JOIN(a, r, g, b);
}
static inline uint32_t opBlendInterp(uint32_t s, uint32_t d, uint8_t a)
@@ -488,246 +489,36 @@ static inline uint32_t opBlendSrcOver(uint32_t s, TVG_UNUSED uint32_t d, TVG_UNU
return s;
}
-static inline uint32_t opBlendDifference(uint32_t s, uint32_t d)
-{
- auto f = [](uint8_t s, uint8_t d) {
- return (s > d) ? (s - d) : (d - s);
- };
-
- return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
-}
-
-static inline uint32_t opBlendExclusion(uint32_t s, uint32_t d)
-{
- auto f = [](uint8_t s, uint8_t d) {
- return tvg::clamp(s + d - 2 * MULTIPLY(s, d), 0, 255);
- };
-
- return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
-}
-
-static inline uint32_t opBlendAdd(uint32_t s, uint32_t d)
-{
- auto f = [](uint8_t s, uint8_t d) {
- return std::min(s + d, 255);
- };
-
- return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
-}
-
-static inline uint32_t opBlendScreen(uint32_t s, uint32_t d)
-{
- auto f = [](uint8_t s, uint8_t d) {
- return s + d - MULTIPLY(s, d);
- };
-
- return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
-}
-
-static inline uint32_t opBlendMultiply(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return MULTIPLY(s, d);
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-static inline uint32_t opBlendOverlay(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return (d < 128) ? std::min(255, 2 * MULTIPLY(s, d)) : (255 - std::min(255, 2 * MULTIPLY(255 - s, 255 - d)));
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-static inline uint32_t opBlendDarken(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return std::min(s, d);
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-static inline uint32_t opBlendLighten(uint32_t s, uint32_t d)
-{
- auto f = [](uint8_t s, uint8_t d) {
- return std::max(s, d);
- };
-
- return JOIN(255, f(C1(s), C1(d)), f(C2(s), C2(d)), f(C3(s), C3(d)));
-}
-
-static inline uint32_t opBlendColorDodge(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return d == 0 ? 0 : (s == 255 ? 255 : std::min(d * 255 / (255 - s), 255));
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-static inline uint32_t opBlendColorBurn(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return d == 255 ? 255 : (s == 0 ? 0 : 255 - std::min((255 - d) * 255 / s, 255));
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-static inline uint32_t opBlendHardLight(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return (s < 128) ? std::min(255, 2 * MULTIPLY(s, d)) : (255 - std::min(255, 2 * MULTIPLY(255 - s, 255 - d)));
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-static inline uint32_t opBlendSoftLight(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- auto f = [](uint8_t s, uint8_t d) {
- return MULTIPLY(255 - std::min(255, 2 * s), MULTIPLY(d, d)) + std::min(255, 2 * MULTIPLY(s, d));
- };
-
- return BLEND_PRE(JOIN(255, f(C1(s), o.r), f(C2(s), o.g), f(C3(s), o.b)), s, o.a);
-}
-
-void rasterRGB2HSL(uint8_t r, uint8_t g, uint8_t b, float* h, float* s, float* l);
-
-static inline uint32_t opBlendHue(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- float sh, ds, dl;
- rasterRGB2HSL(C1(s), C2(s), C3(s), &sh, 0, 0);
- rasterRGB2HSL(o.r, o.g, o.b, 0, &ds, &dl);
-
- uint8_t r, g, b;
- hsl2rgb(sh, ds, dl, r, g, b);
-
- return BLEND_PRE(JOIN(255, r, g, b), s, o.a);
-}
-
-static inline uint32_t opBlendSaturation(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- float dh, ss, dl;
- rasterRGB2HSL(C1(s), C2(s), C3(s), 0, &ss, 0);
- rasterRGB2HSL(o.r, o.g, o.b, &dh, 0, &dl);
-
- uint8_t r, g, b;
- hsl2rgb(dh, ss, dl, r, g, b);
-
- return BLEND_PRE(JOIN(255, r, g, b), s, o.a);
-}
-
-static inline uint32_t opBlendColor(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- float sh, ss, dl;
- rasterRGB2HSL(C1(s), C2(s), C3(s), &sh, &ss, 0);
- rasterRGB2HSL(o.r, o.g, o.b, 0, 0, &dl);
-
- uint8_t r, g, b;
- hsl2rgb(sh, ss, dl, r, g, b);
-
- return BLEND_PRE(JOIN(255, r, g, b), s, o.a);
-}
-
-static inline uint32_t opBlendLuminosity(uint32_t s, uint32_t d)
-{
- auto o = BLEND_UPRE(d);
-
- float dh, ds, sl;
- rasterRGB2HSL(C1(s), C2(s), C3(s), 0, 0, &sl);
- rasterRGB2HSL(o.r, o.g, o.b, &dh, &ds, 0);
-
- uint8_t r, g, b;
- hsl2rgb(dh, ds, sl, r, g, b);
-
- return BLEND_PRE(JOIN(255, r, g, b), s, o.a);
-}
-
-int64_t mathMultiply(int64_t a, int64_t b);
-int64_t mathDivide(int64_t a, int64_t b);
-int64_t mathMulDiv(int64_t a, int64_t b, int64_t c);
-void mathRotate(SwPoint& pt, int64_t angle);
-int64_t mathTan(int64_t angle);
-int64_t mathAtan(const SwPoint& pt);
-int64_t mathCos(int64_t angle);
-int64_t mathSin(int64_t angle);
-void mathSplitCubic(SwPoint* base);
-void mathSplitLine(SwPoint* base);
-int64_t mathDiff(int64_t angle1, int64_t angle2);
-int64_t mathLength(const SwPoint& pt);
-int mathCubicAngle(const SwPoint* base, int64_t& angleIn, int64_t& angleMid, int64_t& angleOut);
-int64_t mathMean(int64_t angle1, int64_t angle2);
-SwPoint mathTransform(const Point* to, const Matrix& transform);
-bool mathUpdateOutlineBBox(const SwOutline* outline, const RenderRegion& clipBox, RenderRegion& renderBox, bool fastTrack);
+void utilExport(SwOutline* outline, const Matrix& transform, BBox& bbox);
+bool utilBBox(const BBox& bbox, const RenderRegion& clipBox, RenderRegion& renderBox, bool fastTrack);
void shapeReset(SwShape& shape);
-bool shapePrepare(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool hasComposite);
-bool shapeGenRle(SwShape& shape, const RenderRegion& bbox, SwMpool* mpool, unsigned tid, bool antiAlias);
-void shapeDelOutline(SwShape& shape, SwMpool* mpool, uint32_t tid);
+void shapeDelOutline(SwShape& shape);
+bool shapeGenRle(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool composite, bool antiAlias);
void shapeResetStroke(SwShape& shape, const RenderShape* rshape, const Matrix& transform, SwMpool* mpool, unsigned tid);
-bool shapeGenStrokeRle(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid);
+bool shapeGenStrokeRle(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool antiAlias);
void shapeFree(SwShape& shape);
void shapeDelStroke(SwShape& shape);
-bool shapeGenFillColors(SwShape& shape, const Fill* fill, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable);
-bool shapeGenStrokeFillColors(SwShape& shape, const Fill* fill, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable);
-void shapeResetFill(SwShape& shape);
-void shapeResetStrokeFill(SwShape& shape);
bool shapeStrokeBBox(SwShape& shape, const RenderShape* rshape, Point* pt4, const Matrix& m, SwMpool* mpool);
-void shapeDelFill(SwShape& shape);
void strokeReset(SwStroke* stroke, const RenderShape* shape, const Matrix& transform, SwMpool* mpool, unsigned tid);
-bool strokeParseOutline(SwStroke* stroke, const SwOutline& outline, SwMpool* mpool, unsigned tid);
+bool strokeParseOutline(SwStroke* stroke, const SwOutline& outline);
SwOutline* strokeExportOutline(SwStroke* stroke, SwMpool* mpool, unsigned tid);
void strokeFree(SwStroke* stroke);
bool imagePrepare(SwImage& image, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid);
bool imageGenRle(SwImage& image, const RenderRegion& bbox, SwMpool* mpool, unsigned tid, bool antiAlias);
-void imageDelOutline(SwImage& image, SwMpool* mpool, uint32_t tid);
void imageReset(SwImage& image);
void imageFree(SwImage& image);
-bool fillGenColorTable(SwFill* fill, const Fill* fdata, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable);
+bool fillPrepare(SwFill*& fill, const Fill* fdata, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable);
const Fill::ColorStop* fillFetchSolid(const SwFill* fill, const Fill* fdata);
void fillReset(SwFill* fill);
-void fillFree(SwFill* fill);
-
-//OPTIMIZE_ME: Skip the function pointer access
-void fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t opacity); //composite masking ver.
-void fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t opacity); //direct masking ver.
-void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a); //blending ver.
-void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a); //blending + BlendingMethod(op2) ver.
-void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity); //matting ver.
-
-void fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask op, uint8_t a); //composite masking ver.
-void fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask op, uint8_t a) ; //direct masking ver.
-void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a); //blending ver.
-void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a); //blending + BlendingMethod(op2) ver.
-void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity); //matting ver.
+void fillRaster(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t opacity); // composite masking ver.
+void fillRaster(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t opacity); // direct masking ver.
+void fillRaster(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a); // blending ver.
+void fillRaster(const SwSurface* surface, const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a); // blending + BlendingMethod(op2) ver.
+void fillRaster(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity); // matting ver.
SwRle* rleRender(SwRle* rle, const SwOutline* outline, const RenderRegion& bbox, SwMpool* mpool, unsigned tid, bool antiAlias);
SwRle* rleRender(const RenderRegion* bbox);
@@ -742,7 +533,8 @@ void mpoolInit(uint32_t threads);
void mpoolTerm();
SwMpool* mpoolReq();
-bool rasterCompositor(SwSurface* surface);
+void rasterInit();
+Result rasterCompositor(SwSurface* surface);
bool rasterShape(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, RenderColor& c);
bool rasterTexmapPolygon(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity);
bool rasterScaledImage(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity);
@@ -753,16 +545,13 @@ bool rasterStroke(SwSurface* surface, SwShape* shape, const RenderRegion& bbox,
bool rasterGradientShape(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, const Fill* fdata, uint8_t opacity);
bool rasterGradientStroke(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, const Fill* fdata, uint8_t opacity);
bool rasterClear(SwSurface* surface, uint32_t x, uint32_t y, uint32_t w, uint32_t h);
-void rasterPixel32(uint32_t *dst, uint32_t val, uint32_t offset, int32_t len);
-void rasterTranslucentPixel32(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity);
-void rasterPixel32(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity);
-void rasterGrayscale8(uint8_t *dst, uint8_t val, uint32_t offset, int32_t len);
-void rasterXYFlip(uint32_t* src, uint32_t* dst, int32_t stride, int32_t w, int32_t h, const RenderRegion& bbox, bool flipped);
-void rasterUnpremultiply(RenderSurface* surface);
-void rasterPremultiply(RenderSurface* surface);
+void rasterUnpremultiplySurface(RenderSurface* surface);
+void rasterPremultiplySurface(RenderSurface* surface);
bool rasterConvertCS(RenderSurface* surface, ColorSpace to);
-uint32_t rasterUnpremultiply(uint32_t data);
+bool effectMotionBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffectMotionBlur* params);
+bool effectMotionBlurRegion(RenderEffectMotionBlur* params);
+void effectMotionBlurUpdate(RenderEffectMotionBlur* params, const Matrix& transform);
bool effectGaussianBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffectGaussianBlur* params);
bool effectGaussianBlurRegion(RenderEffectGaussianBlur* effect);
void effectGaussianBlurUpdate(RenderEffectGaussianBlur* effect, const Matrix& transform);
@@ -776,4 +565,21 @@ bool effectTint(SwCompositor* cmp, const RenderEffectTint* params, bool direct);
void effectTritoneUpdate(RenderEffectTritone* effect);
bool effectTritone(SwCompositor* cmp, const RenderEffectTritone* params, bool direct);
+uint32_t blendDifference(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendExclusion(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendAdd(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendScreen(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendMultiply(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendOverlay(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendDarken(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendLighten(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendColorDodge(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendColorBurn(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendHardLight(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendSoftLight(TVG_UNUSED const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendHue(const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendSaturation(const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendColor(const SwSurface* surface, uint32_t s, uint32_t d);
+uint32_t blendLuminosity(const SwSurface* surface, uint32_t s, uint32_t d);
+
#endif /* _TVG_SW_COMMON_H_ */
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwFill.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwFill.cpp
similarity index 59%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwFill.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwFill.cpp
index f2587af1f88..2b4110f1f04 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwFill.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwFill.cpp
@@ -27,86 +27,51 @@
/* Internal Class Implementation */
/************************************************************************/
-#define RADIAL_A_THRESHOLD 0.0005f
#define FIXPT_BITS 8
#define FIXPT_SIZE (1<<FIXPT_BITS)
+#define MARGIN_MAX 40 // The maximum number of color table entries for the anti-aliasing (AA) margin at both ends.
-/*
- * quadratic equation with the following coefficients (rx and ry defined in the _calculateCoefficients()):
- * A = a // fill->radial.a
- * B = 2 * (dr * fr + rx * dx + ry * dy)
- * C = fr^2 - rx^2 - ry^2
- * Derivatives are computed with respect to dx.
- * This procedure aims to optimize and eliminate the need to calculate all values from the beginning
- * for consecutive x values with a constant y. The Taylor series expansions are computed as long as
- * its terms are non-zero.
- */
-static void _calculateCoefficients(const SwFill* fill, uint32_t x, uint32_t y, float& b, float& deltaB, float& det, float& deltaDet, float& deltaDeltaDet)
-{
- auto radial = &fill->radial;
-
- auto rx = (x + 0.5f) * radial->a11 + (y + 0.5f) * radial->a12 + radial->a13 - radial->fx;
- auto ry = (x + 0.5f) * radial->a21 + (y + 0.5f) * radial->a22 + radial->a23 - radial->fy;
-
- b = (radial->dr * radial->fr + rx * radial->dx + ry * radial->dy) * radial->invA;
- deltaB = (radial->a11 * radial->dx + radial->a21 * radial->dy) * radial->invA;
-
- auto rr = rx * rx + ry * ry;
- auto deltaRr = 2.0f * (rx * radial->a11 + ry * radial->a21) * radial->invA;
- auto deltaDeltaRr = 2.0f * (radial->a11 * radial->a11 + radial->a21 * radial->a21) * radial->invA;
-
- det = b * b + (rr - radial->fr * radial->fr) * radial->invA;
- deltaDet = 2.0f * b * deltaB + deltaB * deltaB + deltaRr + deltaDeltaRr * 0.5f;
- deltaDeltaDet = 2.0f * deltaB * deltaB + deltaDeltaRr;
-}
-
-
-static uint32_t _estimateAAMargin(const Fill* fdata)
-{
- constexpr float marginScalingFactor = 800.0f;
-
- if (fdata->type() == Type::RadialGradient) {
- auto radius = CONST_RADIAL(fdata)->r;
- return tvg::zero(radius) ? 0 : static_cast<uint32_t>(marginScalingFactor / radius);
- } else {
- auto grad = CONST_LINEAR(fdata);
- auto len = length(grad->p1, grad->p2);
- return tvg::zero(len) ? 0 : static_cast<uint32_t>(marginScalingFactor / len);
- }
-}
-
-
-static void _adjustAAMargin(uint32_t& iMargin, uint32_t index)
+static void _adjustAAMargin(uint32_t& iMargin, uint32_t count)
{
constexpr float threshold = 0.1f;
- constexpr uint32_t iMarginMax = 40;
- auto iThreshold = static_cast<uint32_t>(index * threshold);
+ auto iThreshold = static_cast<uint32_t>(count * threshold);
if (iMargin > iThreshold) iMargin = iThreshold;
- if (iMargin > iMarginMax) iMargin = iMarginMax;
+ if (iMargin > MARGIN_MAX) iMargin = MARGIN_MAX;
}
-
-static inline uint32_t _alphaUnblend(uint32_t c)
+static void _applyRepeatAA(SwFill* fill, const Fill::ColorStop* colors, uint32_t cnt)
{
- auto a = (c >> 24);
- if (a == 255 || a == 0) return c;
- auto invA = 255.0f / static_cast<float>(a);
- auto c0 = static_cast<uint8_t>(static_cast<float>((c >> 16) & 0xFF) * invA);
- auto c1 = static_cast<uint8_t>(static_cast<float>((c >> 8) & 0xFF) * invA);
- auto c2 = static_cast<uint8_t>(static_cast<float>(c & 0xFF) * invA);
+ if (cnt == 1) return;
- return (a << 24) | (c0 << 16) | (c1 << 8) | c2;
-}
+ // Calculate count that satisfies (i + 0.5) / SW_COLOR_TABLE < offset
+ auto countBegin = static_cast<uint32_t>(max(0.0f, floor((colors + 1)->offset * SW_COLOR_TABLE - 0.5f) + 1.0f));
+ auto countEnd = static_cast<uint32_t>(max(0.0f, floor((1.0f - (colors + cnt - 2)->offset) * SW_COLOR_TABLE - 0.5f) + 1.0f));
+ // estimate AA margine
+ constexpr float marginScaleFactor = 800.0f;
+ auto begin = tvg::zero(fill->extent) ? 0 : static_cast<uint32_t>(marginScaleFactor / fill->extent);
+ _adjustAAMargin(begin, countBegin);
+ auto end = begin;
+ _adjustAAMargin(end, countEnd);
-static void _applyAA(SwFill* fill, uint32_t begin, uint32_t end)
-{
+ // apply AA
if (begin == 0 || end == 0) return;
+ auto unblend = [](uint32_t c) {
+ auto a = (c >> 24);
+ if (a == 255 || a == 0) return c;
+ auto invA = 255.0f / static_cast<float>(a);
+ auto c0 = static_cast<uint8_t>(static_cast<float>((c >> 16) & 0xFF) * invA);
+ auto c1 = static_cast<uint8_t>(static_cast<float>((c >> 8) & 0xFF) * invA);
+ auto c2 = static_cast<uint8_t>(static_cast<float>(c & 0xFF) * invA);
+
+ return (a << 24) | (c0 << 16) | (c1 << 8) | c2;
+ };
+
auto i = SW_COLOR_TABLE - end;
- auto rgbaEnd = _alphaUnblend(fill->ctable[i]);
- auto rgbaBegin = _alphaUnblend(fill->ctable[begin]);
+ auto rgbaEnd = unblend(fill->ctable[i]);
+ auto rgbaBegin = unblend(fill->ctable[begin]);
auto dt = 1.0f / (begin + end + 1.0f);
float t = dt;
@@ -120,15 +85,9 @@ static void _applyAA(SwFill* fill, uint32_t begin, uint32_t end)
}
}
-
-static bool _updateColorTable(SwFill* fill, const Fill* fdata, const SwSurface* surface, uint8_t opacity)
+// Generate the ctable entries over the [begin, end) range
+static void _genColorTable(SwFill* fill, const Fill::ColorStop* colors, uint32_t cnt, const SwSurface* surface, uint8_t opacity, uint32_t begin, uint32_t end)
{
- if (fill->solid) return true;
-
- const Fill::ColorStop* colors;
- auto cnt = fdata->colorStops(&colors);
- if (cnt == 0 || !colors) return false;
-
auto pColors = colors;
auto a = MULTIPLY(pColors->a, opacity);
@@ -139,28 +98,17 @@ static bool _updateColorTable(SwFill* fill, const Fill* fdata, const SwSurface*
auto b = pColors->b;
auto rgba = surface->join(r, g, b, a);
auto inc = 1.0f / static_cast<float>(SW_COLOR_TABLE);
- auto pos = 1.5f * inc;
- uint32_t i = 0;
-
- //If repeat is true, anti-aliasing must be applied between the last and the first colors.
- auto repeat = fill->spread == FillSpread::Repeat;
- uint32_t iAABegin = repeat ? _estimateAAMargin(fdata) : 0;
- uint32_t iAAEnd = 0;
+ auto pos = (begin + 0.5f) * inc;
+ auto i = begin;
- fill->ctable[i++] = ALPHA_BLEND(rgba | 0xff000000, a);
+ auto padColor = ALPHA_BLEND(rgba | 0xff000000, a);
- while (pos <= pColors->offset) {
- fill->ctable[i] = fill->ctable[i - 1];
- ++i;
+ while (i < end && (i == 0 || pos <= pColors->offset)) {
+ fill->ctable[i++] = padColor;
pos += inc;
}
for (uint32_t j = 0; j < cnt - 1; ++j) {
- if (repeat && j == cnt - 2 && iAAEnd == 0) {
- iAAEnd = iAABegin;
- _adjustAAMargin(iAAEnd, SW_COLOR_TABLE - i);
- }
-
auto curr = colors + j;
auto next = curr + 1;
auto div = next->offset - curr->offset;
@@ -171,7 +119,7 @@ static bool _updateColorTable(SwFill* fill, const Fill* fdata, const SwSurface*
auto rgba2 = surface->join(next->r, next->g, next->b, a2);
- while (pos < next->offset && i < SW_COLOR_TABLE) {
+ while (i < end && pos < next->offset) {
auto t = (pos - curr->offset) * delta;
auto dist = static_cast<int32_t>(255 * t);
auto dist2 = 255 - dist;
@@ -182,60 +130,110 @@ static bool _updateColorTable(SwFill* fill, const Fill* fdata, const SwSurface*
}
rgba = rgba2;
a = a2;
-
- if (repeat && j == 0) _adjustAAMargin(iAABegin, i - 1);
}
rgba = ALPHA_BLEND((rgba | 0xff000000), a);
- for (; i < SW_COLOR_TABLE; ++i) {
+ for (; i < end; ++i) {
fill->ctable[i] = rgba;
}
- //For repeat fill spread apply anti-aliasing between the last and first colors,
- //otherwise make sure the last color stop is represented at the end of the table.
- if (repeat) _applyAA(fill, iAABegin, iAAEnd);
- else fill->ctable[SW_COLOR_TABLE - 1] = rgba;
+ if (end == SW_COLOR_TABLE) fill->ctable[SW_COLOR_TABLE - 1] = rgba;
+}
+
+static bool _updateColorTable(SwFill* fill, const Fill* fdata, const SwSurface* surface, uint8_t opacity)
+{
+ if (fill->solid) return true;
+
+ const Fill::ColorStop* colors;
+ auto cnt = fdata->colorStops(&colors);
+ if (cnt == 0 || !colors) return false;
+
+ _genColorTable(fill, colors, cnt, surface, opacity, 0, SW_COLOR_TABLE);
+ if (fill->spread == FillSpread::Repeat && fdata->type() != Type::ConicGradient) _applyRepeatAA(fill, colors, cnt);
return true;
}
-
-bool _prepareLinear(SwFill* fill, const LinearGradient* linear, const Matrix& pTransform)
+// Update only the ctable corresponding to the margin based on the updated extent
+static bool _updateAAMargin(SwFill* fill, const Fill* fdata, const SwSurface* surface, uint8_t opacity)
{
- float x1, x2, y1, y2;
- linear->linear(&x1, &y1, &x2, &y2);
+ const Fill::ColorStop* colors;
+ auto cnt = fdata->colorStops(&colors);
+ if (cnt == 0) return false;
- fill->linear.dx = x2 - x1;
- fill->linear.dy = y2 - y1;
- auto len = fill->linear.dx * fill->linear.dx + fill->linear.dy * fill->linear.dy;
+ _genColorTable(fill, colors, cnt, surface, opacity, 0, MARGIN_MAX);
+ _genColorTable(fill, colors, cnt, surface, opacity, SW_COLOR_TABLE - MARGIN_MAX, SW_COLOR_TABLE);
+ _applyRepeatAA(fill, colors, cnt);
- if (len < FLOAT_EPSILON) {
- if (tvg::zero(fill->linear.dx) && tvg::zero(fill->linear.dy)) {
- fill->solid = true;
+ return true;
+}
+
+static inline uint32_t _clamp(const SwFill* fill, int32_t pos)
+{
+ switch (fill->spread) {
+ case FillSpread::Pad: {
+ if (pos >= SW_COLOR_TABLE) pos = SW_COLOR_TABLE - 1;
+ else if (pos < 0) pos = 0;
+ break;
+ }
+ case FillSpread::Repeat: {
+ pos = pos % SW_COLOR_TABLE;
+ if (pos < 0) pos = SW_COLOR_TABLE + pos;
+ break;
+ }
+ case FillSpread::Reflect: {
+ auto limit = SW_COLOR_TABLE * 2;
+ pos = pos % limit;
+ if (pos < 0) pos = limit + pos;
+ if (pos >= SW_COLOR_TABLE) pos = (limit - pos - 1);
+ break;
}
- return true;
}
+ return pos;
+}
- fill->linear.dx /= len;
- fill->linear.dy /= len;
- fill->linear.offset = -fill->linear.dx * x1 - fill->linear.dy * y1;
+static inline uint32_t _pixel(const SwFill* fill, float pos)
+{
+ auto i = static_cast<int32_t>(pos * (SW_COLOR_TABLE - 1) + 0.5f);
+ return fill->ctable[_clamp(fill, i)];
+}
- const auto& transform = pTransform * linear->transform();
+/************************************************************************/
+/* Radial Implementation */
+/************************************************************************/
- Matrix itransform;
- if (!inverse(&transform, &itransform)) return false;
+#define RADIAL_A_THRESHOLD 0.0005f
- fill->linear.offset += fill->linear.dx * itransform.e13 + fill->linear.dy * itransform.e23;
+/*
+ * quadratic equation with the following coefficients (rx and ry defined in the _calculateCoefficients()):
+ * A = a // fill->radial.a
+ * B = 2 * (dr * fr + rx * dx + ry * dy)
+ * C = fr^2 - rx^2 - ry^2
+ * Derivatives are computed with respect to dx.
+ * This procedure aims to optimize and eliminate the need to calculate all values from the beginning
+ * for consecutive x values with a constant y. The Taylor series expansions are computed as long as
+ * its terms are non-zero.
+ */
+static void _calculateCoefficients(const SwFill* fill, uint32_t x, uint32_t y, float& b, float& deltaB, float& det, float& deltaDet, float& deltaDeltaDet)
+{
+ auto radial = &fill->radial;
- auto dx = fill->linear.dx;
- fill->linear.dx = dx * itransform.e11 + fill->linear.dy * itransform.e21;
- fill->linear.dy = dx * itransform.e12 + fill->linear.dy * itransform.e22;
+ auto rx = (x + 0.5f) * radial->a11 + (y + 0.5f) * radial->a12 + radial->a13 - radial->fx;
+ auto ry = (x + 0.5f) * radial->a21 + (y + 0.5f) * radial->a22 + radial->a23 - radial->fy;
- return true;
-}
+ b = (radial->dr * radial->fr + rx * radial->dx + ry * radial->dy) * radial->invA;
+ deltaB = (radial->a11 * radial->dx + radial->a21 * radial->dy) * radial->invA;
+ auto rr = rx * rx + ry * ry;
+ auto deltaRr = 2.0f * (rx * radial->a11 + ry * radial->a21) * radial->invA;
+ auto deltaDeltaRr = 2.0f * (radial->a11 * radial->a11 + radial->a21 * radial->a21) * radial->invA;
+
+ det = b * b + (rr - radial->fr * radial->fr) * radial->invA;
+ deltaDet = 2.0f * b * deltaB + deltaB * deltaB + deltaRr + deltaDeltaRr * 0.5f;
+ deltaDeltaDet = 2.0f * deltaB * deltaB + deltaDeltaRr;
+}
-bool _prepareRadial(SwFill* fill, const RadialGradient* radial, const Matrix& pTransform)
+bool _prepareRadial(SwFill* fill, const RadialGradient* radial, const Matrix& pTransform, bool& extentChanged)
{
float cx, cy, r, fx, fy, fr;
radial->radial(&cx, &cy, &r, &fx, &fy, &fr);
@@ -267,55 +265,22 @@ bool _prepareRadial(SwFill* fill, const RadialGradient* radial, const Matrix& pT
fill->radial.a22 = itransform.e22;
fill->radial.a23 = itransform.e23;
- return true;
-}
-
-
-static inline uint32_t _clamp(const SwFill* fill, int32_t pos)
-{
- switch (fill->spread) {
- case FillSpread::Pad: {
- if (pos >= SW_COLOR_TABLE) pos = SW_COLOR_TABLE - 1;
- else if (pos < 0) pos = 0;
- break;
- }
- case FillSpread::Repeat: {
- pos = pos % SW_COLOR_TABLE;
- if (pos < 0) pos = SW_COLOR_TABLE + pos;
- break;
- }
- case FillSpread::Reflect: {
- auto limit = SW_COLOR_TABLE * 2;
- pos = pos % limit;
- if (pos < 0) pos = limit + pos;
- if (pos >= SW_COLOR_TABLE) pos = (limit - pos - 1);
- break;
- }
+ // The transform maps the gradient circle to an ellipse. Take its semi-minor axis
+ // (the smaller singular value), where the table packs tightest and needs most margin.
+ auto sx = transform.e11 * transform.e11 + transform.e21 * transform.e21;
+ auto sy = transform.e12 * transform.e12 + transform.e22 * transform.e22;
+ auto sxy = transform.e11 * transform.e12 + transform.e21 * transform.e22;
+ auto d = sqrtf((sx - sy) * (sx - sy) + 4.0f * sxy * sxy);
+ auto ext = r * sqrtf(0.5f * std::max(0.0f, sx + sy - d));
+ if (!tvg::equal(ext, fill->extent)) {
+ extentChanged = true;
+ fill->extent = ext;
}
- return pos;
-}
-
-static inline uint32_t _fixedPixel(const SwFill* fill, int32_t pos)
-{
- int32_t i = (pos + (FIXPT_SIZE / 2)) >> FIXPT_BITS;
- return fill->ctable[_clamp(fill, i)];
-}
-
-
-static inline uint32_t _pixel(const SwFill* fill, float pos)
-{
- auto i = static_cast<int32_t>(pos * (SW_COLOR_TABLE - 1) + 0.5f);
- return fill->ctable[_clamp(fill, i)];
+ return true;
}
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-
-void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
+static void _fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
{
//edge case
if (fill->radial.a < RADIAL_A_THRESHOLD) {
@@ -360,8 +325,7 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
}
}
-
-void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
+static void _fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
{
if (fill->radial.a < RADIAL_A_THRESHOLD) {
auto radial = &fill->radial;
@@ -386,8 +350,7 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
}
}
-
-void fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t a)
+static void _fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t a)
{
if (fill->radial.a < RADIAL_A_THRESHOLD) {
auto radial = &fill->radial;
@@ -414,8 +377,7 @@ void fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32
}
}
-
-void fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t a)
+static void _fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t a)
{
if (fill->radial.a < RADIAL_A_THRESHOLD) {
auto radial = &fill->radial;
@@ -444,8 +406,7 @@ void fillRadial(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32
}
}
-
-void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
+static void _fillRadial(const SwSurface* surface, const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
{
if (fill->radial.a < RADIAL_A_THRESHOLD) {
auto radial = &fill->radial;
@@ -456,7 +417,7 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
for (uint32_t i = 0; i < len; ++i, ++dst) {
auto x0 = 0.5f * (rx * rx + ry * ry - radial->fr * radial->fr) / (radial->dr * radial->fr + rx * radial->dx + ry * radial->dy);
auto tmp = op(_pixel(fill, x0), *dst, 255);
- *dst = op2(tmp, *dst);
+ *dst = op2(surface, tmp, *dst);
rx += radial->a11;
ry += radial->a21;
}
@@ -464,7 +425,7 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
for (uint32_t i = 0; i < len; ++i, ++dst) {
auto x0 = 0.5f * (rx * rx + ry * ry - radial->fr * radial->fr) / (radial->dr * radial->fr + rx * radial->dx + ry * radial->dy);
auto tmp = op(_pixel(fill, x0), *dst, 255);
- auto tmp2 = op2(tmp, *dst);
+ auto tmp2 = op2(surface, tmp, *dst);
*dst = INTERPOLATE(tmp2, *dst, a);
rx += radial->a11;
ry += radial->a21;
@@ -476,7 +437,7 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
if (a == 255) {
for (uint32_t i = 0 ; i < len ; ++i, ++dst) {
auto tmp = op(_pixel(fill, sqrtf(det) - b), *dst, 255);
- *dst = op2(tmp, *dst);
+ *dst = op2(surface, tmp, *dst);
det += deltaDet;
deltaDet += deltaDeltaDet;
b += deltaB;
@@ -484,7 +445,7 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
} else {
for (uint32_t i = 0 ; i < len ; ++i, ++dst) {
auto tmp = op(_pixel(fill, sqrtf(det) - b), *dst, 255);
- auto tmp2 = op2(tmp, *dst);
+ auto tmp2 = op2(surface, tmp, *dst);
*dst = INTERPOLATE(tmp2, *dst, a);
det += deltaDet;
deltaDet += deltaDeltaDet;
@@ -494,8 +455,252 @@ void fillRadial(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
}
}
+/************************************************************************/
+/* Conic Implementation */
+/************************************************************************/
+
+struct ConicAARange
+{
+ float begin = 0.0f;
+ float end = 0.0f;
+ float distance = 0.0f;
+};
+
+static ConicAARange _conicAARange(const SwFill* fill, float rx, float ry, uint32_t len)
+{
+ auto conic = &fill->conic;
+ if (conic->invFwidth <= 0.0f || len == 0) return {};
+
+ auto offset = Point{rx, ry};
+
+ // normal distance limits AA to the band around the infinite boundary line
+ auto distance = dot(conic->normal, offset) * conic->invFwidth;
+ auto distanceDx = conic->distanceDx;
+ auto range = ConicAARange{0.0f, static_cast<float>(len)};
+ if (tvg::zero(distanceDx)) {
+ if (distance <= -0.5f || distance >= 0.5f) return {};
+ } else {
+ auto first = (-0.5f - distance) / distanceDx; // distance + first * distanceDx = -0.5
+ auto last = (0.5f - distance) / distanceDx; // distance + last * distanceDx = 0.5
+ if (first > last) std::swap(first, last);
+ range.begin = std::max(range.begin, floorf(first) + 1.0f);
+ range.end = std::min(range.end, ceilf(last));
+ }
+
+ // exclude the half of the AA band opposite the conic seam
+ auto seam = Point{conic->normal.y, -conic->normal.x};
+ auto seamProjection = dot(offset, seam);
+ auto seamProjectionDx = conic->seamProjectionDx;
+ if (tvg::zero(seamProjectionDx)) {
+ if (seamProjection < 0.0f) return {};
+ } else if (seamProjectionDx > 0.0f) {
+ range.begin = std::max(range.begin, ceilf(-seamProjection / seamProjectionDx));
+ } else {
+ range.end = std::min(range.end, floorf(-seamProjection / seamProjectionDx) + 1.0f);
+ }
+
+ if (range.begin >= range.end) return {};
+
+ range.distance = distance + range.begin * distanceDx;
+ return range;
+}
+
+static uint32_t _conicPixel(const SwFill* fill, float rx, float ry, uint32_t i, const ConicAARange& range)
+{
+ auto t = [](const SwFill* fill, float rx, float ry) {
+ // atan2 starts at 3 o'clock; offset rotates to the configured start angle.
+ auto t = atan2f(ry, rx) * (0.5f / MATH_PI) + fill->conic.offset;
+ return t - floorf(t); // wrap to [0..1)
+ };
+
+ if (i < range.begin || i >= range.end) return _pixel(fill, t(fill, rx, ry));
+ auto distance = range.distance + (i - range.begin) * fill->conic.distanceDx;
+ return INTERPOLATE(fill->ctable[0], fill->ctable[SW_COLOR_TABLE - 1], static_cast<uint8_t>(255.0f * (distance + 0.5f))); // distance is kept within (-0.5f, 0.5f) by _conicAARange()
+}
+
+bool _prepareConic(SwFill* fill, const ConicGradient* conic, const Matrix& pTransform)
+{
+ float cx, cy, angle;
+ conic->conic(&cx, &cy, &angle);
+
+ fill->conic.cx = cx;
+ fill->conic.cy = cy;
+ fill->conic.offset = -angle / 360.0f;
+
+ const auto& transform = pTransform * conic->transform();
+
+ Matrix itransform;
+ if (!inverse(&transform, &itransform)) return false;
+
+ fill->conic.a11 = itransform.e11;
+ fill->conic.a12 = itransform.e12;
+ fill->conic.a13 = itransform.e13;
+ fill->conic.a21 = itransform.e21;
+ fill->conic.a22 = itransform.e22;
+ fill->conic.a23 = itransform.e23;
+
+ // prepare conic anti-aliasing variables
+ auto radian = angle * (MATH_PI / 180.0f);
+ auto seam = Point{cosf(radian), sinf(radian)};
+ fill->conic.normal = {-seam.y, seam.x};
+ auto xStep = Point{fill->conic.a11, fill->conic.a21};
+ auto yStep = Point{fill->conic.a12, fill->conic.a22};
+ auto dFdx = dot(fill->conic.normal, xStep);
+ auto dFdy = dot(fill->conic.normal, yStep);
+ auto fwidth = fabsf(dFdx) + fabsf(dFdy);
+
+ fill->conic.invFwidth = (tvg::zero(dFdx) || tvg::zero(dFdy)) ? 0.0f : 1.0f / fwidth;
+ fill->conic.distanceDx = dFdx * fill->conic.invFwidth;
+ fill->conic.seamProjectionDx = dot(seam, xStep);
+
+ return true;
+}
+
+static void _fillConic(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
+{
+ auto conic = &fill->conic;
+ auto rx = (x + 0.5f) * conic->a11 + (y + 0.5f) * conic->a12 + conic->a13 - conic->cx;
+ auto ry = (x + 0.5f) * conic->a21 + (y + 0.5f) * conic->a22 + conic->a23 - conic->cy;
+ auto range = _conicAARange(fill, rx, ry, len);
+
+ if (opacity == 255) {
+ for (uint32_t i = 0; i < len; ++i, ++dst, cmp += csize) {
+ *dst = opBlendNormal(_conicPixel(fill, rx, ry, i, range), *dst, alpha(cmp));
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+ } else {
+ for (uint32_t i = 0; i < len; ++i, ++dst, cmp += csize) {
+ *dst = opBlendNormal(_conicPixel(fill, rx, ry, i, range), *dst, MULTIPLY(opacity, alpha(cmp)));
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+ }
+}
+
+static void _fillConic(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
+{
+ auto conic = &fill->conic;
+ auto rx = (x + 0.5f) * conic->a11 + (y + 0.5f) * conic->a12 + conic->a13 - conic->cx;
+ auto ry = (x + 0.5f) * conic->a21 + (y + 0.5f) * conic->a22 + conic->a23 - conic->cy;
+ auto range = _conicAARange(fill, rx, ry, len);
+
+ for (uint32_t i = 0; i < len; ++i, ++dst) {
+ *dst = op(_conicPixel(fill, rx, ry, i, range), *dst, a);
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+}
+
+static void _fillConic(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t a)
+{
+ auto conic = &fill->conic;
+ auto rx = (x + 0.5f) * conic->a11 + (y + 0.5f) * conic->a12 + conic->a13 - conic->cx;
+ auto ry = (x + 0.5f) * conic->a21 + (y + 0.5f) * conic->a22 + conic->a23 - conic->cy;
+ auto range = _conicAARange(fill, rx, ry, len);
+
+ for (uint32_t i = 0; i < len; ++i, ++dst) {
+ auto src = MULTIPLY(a, A(_conicPixel(fill, rx, ry, i, range)));
+ *dst = maskOp(src, *dst, ~src);
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+}
+
+static void _fillConic(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t a)
+{
+ auto conic = &fill->conic;
+ auto rx = (x + 0.5f) * conic->a11 + (y + 0.5f) * conic->a12 + conic->a13 - conic->cx;
+ auto ry = (x + 0.5f) * conic->a21 + (y + 0.5f) * conic->a22 + conic->a23 - conic->cy;
+ auto range = _conicAARange(fill, rx, ry, len);
+
+ for (uint32_t i = 0; i < len; ++i, ++dst, ++cmp) {
+ auto src = MULTIPLY(A(_conicPixel(fill, rx, ry, i, range)), a);
+ auto tmp = maskOp(src, *cmp, 0);
+ *dst = tmp + MULTIPLY(*dst, ~tmp);
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+}
-void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
+static void _fillConic(const SwSurface* surface, const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
+{
+ auto conic = &fill->conic;
+ auto rx = (x + 0.5f) * conic->a11 + (y + 0.5f) * conic->a12 + conic->a13 - conic->cx;
+ auto ry = (x + 0.5f) * conic->a21 + (y + 0.5f) * conic->a22 + conic->a23 - conic->cy;
+ auto range = _conicAARange(fill, rx, ry, len);
+
+ if (a == 255) {
+ for (uint32_t i = 0; i < len; ++i, ++dst) {
+ auto tmp = op(_conicPixel(fill, rx, ry, i, range), *dst, 255);
+ *dst = op2(surface, tmp, *dst);
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+ } else {
+ for (uint32_t i = 0; i < len; ++i, ++dst) {
+ auto tmp = op(_conicPixel(fill, rx, ry, i, range), *dst, 255);
+ auto tmp2 = op2(surface, tmp, *dst);
+ *dst = INTERPOLATE(tmp2, *dst, a);
+ rx += conic->a11;
+ ry += conic->a21;
+ }
+ }
+}
+
+/************************************************************************/
+/* Linear Implementation */
+/************************************************************************/
+
+static inline uint32_t _fixedPixel(const SwFill* fill, int32_t pos)
+{
+ int32_t i = (pos + (FIXPT_SIZE / 2)) >> FIXPT_BITS;
+ return fill->ctable[_clamp(fill, i)];
+}
+
+bool _prepareLinear(SwFill* fill, const LinearGradient* linear, const Matrix& pTransform, bool& extentChanged)
+{
+ float x1, x2, y1, y2;
+ linear->linear(&x1, &y1, &x2, &y2);
+
+ fill->linear.dx = x2 - x1;
+ fill->linear.dy = y2 - y1;
+ auto len = fill->linear.dx * fill->linear.dx + fill->linear.dy * fill->linear.dy;
+
+ if (len < FLOAT_EPSILON) {
+ if (tvg::zero(fill->linear.dx) && tvg::zero(fill->linear.dy)) {
+ fill->solid = true;
+ }
+ return true;
+ }
+
+ fill->linear.dx /= len;
+ fill->linear.dy /= len;
+ fill->linear.offset = -fill->linear.dx * x1 - fill->linear.dy * y1;
+
+ const auto& transform = pTransform * linear->transform();
+
+ Matrix itransform;
+ if (!inverse(&transform, &itransform)) return false;
+
+ fill->linear.offset += fill->linear.dx * itransform.e13 + fill->linear.dy * itransform.e23;
+
+ auto dx = fill->linear.dx;
+ fill->linear.dx = dx * itransform.e11 + fill->linear.dy * itransform.e21;
+ fill->linear.dy = dx * itransform.e12 + fill->linear.dy * itransform.e22;
+
+ // dx/dy is amount of change in screen space. The reciprocal of its magnitude is
+ // the pixel span of one full color table cycle.
+ auto ext = 1.0f / sqrtf(fill->linear.dx * fill->linear.dx + fill->linear.dy * fill->linear.dy);
+ if (!tvg::equal(ext, fill->extent)) {
+ extentChanged = true;
+ fill->extent = ext;
+ }
+
+ return true;
+}
+
+static void _fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
{
//Rotation
float rx = x + 0.5f;
@@ -568,8 +773,7 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
}
}
-
-void fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t a)
+static void _fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask maskOp, uint8_t a)
{
//Rotation
float rx = x + 0.5f;
@@ -610,8 +814,7 @@ void fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32
}
}
-
-void fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t a)
+static void _fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask maskOp, uint8_t a)
{
//Rotation
float rx = x + 0.5f;
@@ -657,8 +860,7 @@ void fillLinear(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32
}
}
-
-void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
+static void _fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
{
//Rotation
float rx = x + 0.5f;
@@ -697,8 +899,7 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
}
}
-
-void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
+static void _fillLinear(const SwSurface* surface, const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
{
//Rotation
float rx = x + 0.5f;
@@ -711,12 +912,12 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
if (a == 255) {
for (uint32_t i = 0; i < len; ++i, ++dst) {
auto tmp = op(color, *dst, a);
- *dst = op2(tmp, *dst);
+ *dst = op2(surface, tmp, *dst);
}
} else {
for (uint32_t i = 0; i < len; ++i, ++dst) {
auto tmp = op(color, *dst, a);
- auto tmp2 = op2(tmp, *dst);
+ auto tmp2 = op2(surface, tmp, *dst);
*dst = INTERPOLATE(tmp2, *dst, a);
}
}
@@ -734,7 +935,7 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
auto inc2 = static_cast<int32_t>(inc * FIXPT_SIZE);
for (uint32_t j = 0; j < len; ++j, ++dst) {
auto tmp = op(_fixedPixel(fill, t2), *dst, 255);
- *dst = op2(tmp, *dst);
+ *dst = op2(surface, tmp, *dst);
t2 += inc2;
}
//we have to fallback to float math
@@ -742,7 +943,7 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
uint32_t counter = 0;
while (counter++ < len) {
auto tmp = op(_pixel(fill, t / SW_COLOR_TABLE), *dst, 255);
- *dst = op2(tmp, *dst);
+ *dst = op2(surface, tmp, *dst);
++dst;
t += inc;
}
@@ -754,7 +955,7 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
auto inc2 = static_cast<int32_t>(inc * FIXPT_SIZE);
for (uint32_t j = 0; j < len; ++j, ++dst) {
auto tmp = op(_fixedPixel(fill, t2), *dst, 255);
- auto tmp2 = op2(tmp, *dst);
+ auto tmp2 = op2(surface, tmp, *dst);
*dst = INTERPOLATE(tmp2, *dst, a);
t2 += inc2;
}
@@ -763,7 +964,7 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
uint32_t counter = 0;
while (counter++ < len) {
auto tmp = op(_pixel(fill, t / SW_COLOR_TABLE), *dst, 255);
- auto tmp2 = op2(tmp, *dst);
+ auto tmp2 = op2(surface, tmp, *dst);
*dst = INTERPOLATE(tmp2, *dst, a);
++dst;
t += inc;
@@ -772,24 +973,45 @@ void fillLinear(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint3
}
}
+/************************************************************************/
+/* External Interace Implementation */
+/************************************************************************/
-bool fillGenColorTable(SwFill* fill, const Fill* fdata, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable)
+bool fillPrepare(SwFill*& fill, const Fill* fdata, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable)
{
- if (!fill) return false;
+ if (!fdata) return true; // a normal case
- fill->spread = fdata->spread();
+ if (!fill) {
+ fill = tvg::calloc<SwFill>(1, sizeof(SwFill));
+ ctable = true;
+ } else if (ctable) {
+ fillReset(fill);
+ }
+
+ // single color stop is treated as solid
+ if (fdata->colorStops(nullptr) == 1) {
+ fill->solid = true;
+ return true;
+ }
- if (fdata->type() == Type::LinearGradient) {
- if (!_prepareLinear(fill, static_cast<const LinearGradient*>(fdata), transform)) return false;
- } else if (fdata->type() == Type::RadialGradient) {
- if (!_prepareRadial(fill, static_cast<const RadialGradient*>(fdata), transform)) return false;
+ auto extentChanged = false;
+
+ fill->spread = fdata->spread();
+ fill->type = fdata->type();
+
+ if (fill->type == Type::LinearGradient) {
+ if (!_prepareLinear(fill, static_cast<const LinearGradient*>(fdata), transform, extentChanged)) return false;
+ } else if (fill->type == Type::RadialGradient) {
+ if (!_prepareRadial(fill, static_cast<const RadialGradient*>(fdata), transform, extentChanged)) return false;
+ } else if (fill->type == Type::ConicGradient) {
+ if (!_prepareConic(fill, static_cast<const ConicGradient*>(fdata), transform)) return false;
}
if (ctable) return _updateColorTable(fill, fdata, surface, opacity);
+ else if (extentChanged && fill->spread == FillSpread::Repeat) return _updateAAMargin(fill, fdata, surface, opacity);
return true;
}
-
const Fill::ColorStop* fillFetchSolid(const SwFill* fill, const Fill* fdata)
{
if (!fill->solid) return nullptr;
@@ -801,15 +1023,48 @@ const Fill::ColorStop* fillFetchSolid(const SwFill* fill, const Fill* fdata)
return colors + cnt - 1;
}
-
void fillReset(SwFill* fill)
{
fill->translucent = false;
fill->solid = false;
}
+// composite masking ver.
+void fillRaster(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask op, uint8_t a)
+{
+ if (fill->type == Type::LinearGradient) _fillLinear(fill, dst, y, x, len, op, a);
+ if (fill->type == Type::RadialGradient) _fillRadial(fill, dst, y, x, len, op, a);
+ if (fill->type == Type::ConicGradient) _fillConic(fill, dst, y, x, len, op, a);
+}
+
+// direct masking ver.
+void fillRaster(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask op, uint8_t a)
+{
+ if (fill->type == Type::LinearGradient) _fillLinear(fill, dst, y, x, len, cmp, op, a);
+ if (fill->type == Type::RadialGradient) _fillRadial(fill, dst, y, x, len, cmp, op, a);
+ if (fill->type == Type::ConicGradient) _fillConic(fill, dst, y, x, len, cmp, op, a);
+}
+
+// blending ver.
+void fillRaster(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
+{
+ if (fill->type == Type::LinearGradient) _fillLinear(fill, dst, y, x, len, op, a);
+ if (fill->type == Type::RadialGradient) _fillRadial(fill, dst, y, x, len, op, a);
+ if (fill->type == Type::ConicGradient) _fillConic(fill, dst, y, x, len, op, a);
+}
+
+// matting ver.
+void fillRaster(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
+{
+ if (fill->type == Type::LinearGradient) _fillLinear(fill, dst, y, x, len, cmp, alpha, csize, opacity);
+ if (fill->type == Type::RadialGradient) _fillRadial(fill, dst, y, x, len, cmp, alpha, csize, opacity);
+ if (fill->type == Type::ConicGradient) _fillConic(fill, dst, y, x, len, cmp, alpha, csize, opacity);
+}
-void fillFree(SwFill* fill)
+// blending + BlendingMethod(op2) ver.
+void fillRaster(const SwSurface* surface, const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
{
- if (fill) tvg::free(fill);
+ if (fill->type == Type::LinearGradient) _fillLinear(surface, fill, dst, y, x, len, op, op2, a);
+ if (fill->type == Type::RadialGradient) _fillRadial(surface, fill, dst, y, x, len, op, op2, a);
+ if (fill->type == Type::ConicGradient) _fillConic(surface, fill, dst, y, x, len, op, op2, a);
}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwImage.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwImage.cpp
similarity index 54%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwImage.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwImage.cpp
index ffffb342e2e..7555036f67c 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwImage.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwImage.cpp
@@ -27,95 +27,64 @@
/* Internal Class Implementation */
/************************************************************************/
-static inline bool _onlyShifted(const Matrix& m)
+static SwOutline* _genOutline(SwImage& image, SwMpool* mpool, unsigned tid)
{
- if (tvg::equal(m.e11, 1.0f) && tvg::equal(m.e22, 1.0f) && tvg::zero(m.e12) && tvg::zero(m.e21)) return true;
- return false;
-}
-
-
-static bool _genOutline(SwImage& image, const Matrix& transform, SwMpool* mpool, unsigned tid)
-{
- image.outline = mpool->outline(tid);
- auto outline = image.outline;
+ auto outline = mpool->outline(tid);
+ auto& path = *const_cast<RenderPath*>(outline->path);
+ path.pts.reserve(4);
+ path.cmds.reserve(5);
- outline->pts.reserve(5);
- outline->types.reserve(5);
- outline->cntrs.reserve(1);
- outline->closed.reserve(1);
-
- Point to[4];
auto w = static_cast<float>(image.w);
auto h = static_cast<float>(image.h);
- to[0] = {0, 0};
- to[1] = {w, 0};
- to[2] = {w, h};
- to[3] = {0, h};
-
- for (int i = 0; i < 4; i++) {
- outline->pts.push(mathTransform(&to[i], transform));
- outline->types.push(SW_CURVE_TYPE_POINT);
- }
- outline->pts.push(outline->pts[0]);
- outline->types.push(SW_CURVE_TYPE_POINT);
- outline->cntrs.push(outline->pts.count - 1);
- outline->closed.push(true);
+ path.moveTo({0.0f, 0.0f});
+ path.lineTo({w, 0.0f});
+ path.lineTo({w, h});
+ path.lineTo({0.0f, h});
+ path.close();
- image.outline = outline;
- image.outline->fillRule = FillRule::NonZero;
+ outline->fillRule = FillRule::NonZero;
- return true;
+ return outline;
}
-
/************************************************************************/
/* External Class Implementation */
/************************************************************************/
bool imagePrepare(SwImage& image, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid)
{
- image.direct = _onlyShifted(transform);
+ // only shifted
+ image.direct = tvg::equal(transform.e11, 1.0f) && tvg::equal(transform.e22, 1.0f) && tvg::zero(transform.e12) && tvg::zero(transform.e21);
- //Fast track: Non-transformed image but just shifted.
+ // fast track: Non-transformed image but just shifted.
if (image.direct) {
image.ox = -static_cast<int32_t>(nearbyint(transform.e13));
image.oy = -static_cast<int32_t>(nearbyint(transform.e23));
- //Figure out the scale factor by transform matrix
+ // figure out the scale factor by transform matrix
} else {
- auto scaleX = sqrtf((transform.e11 * transform.e11) + (transform.e21 * transform.e21));
- auto scaleY = sqrtf((transform.e22 * transform.e22) + (transform.e12 * transform.e12));
- image.scale = (fabsf(scaleX - scaleY) > 0.01f) ? 1.0f : scaleX;
-
- if (tvg::zero(transform.e12) && tvg::zero(transform.e21)) image.scaled = true;
- else image.scaled = false;
+ image.scale = scaling(transform);
+ image.scaled = (tvg::zero(transform.e12) && tvg::zero(transform.e21)) ? true : false;
}
+ image.outline = _genOutline(image, mpool, tid);
+ if (!image.outline) return false;
- if (!_genOutline(image, transform, mpool, tid)) return false;
- return mathUpdateOutlineBBox(image.outline, clipBox, renderBox, image.direct);
+ BBox bbox;
+ utilExport(image.outline, transform, bbox);
+ return utilBBox(bbox, clipBox, renderBox, image.direct);
}
-
bool imageGenRle(SwImage& image, const RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool antiAlias)
{
- if ((image.rle = rleRender(image.rle, image.outline, renderBox, mpool, tid, antiAlias))) return true;
-
- return false;
-}
-
-
-void imageDelOutline(SwImage& image, SwMpool* mpool, uint32_t tid)
-{
- image.outline = nullptr;
+ image.rle = rleRender(image.rle, image.outline, renderBox, mpool, tid, antiAlias);
+ return image.rle ? true : false;
}
-
void imageReset(SwImage& image)
{
rleReset(image.rle);
}
-
void imageFree(SwImage& image)
{
rleFree(image.rle);
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwMemPool.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwMemPool.cpp
similarity index 98%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwMemPool.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwMemPool.cpp
index e90bc4bf7f3..9db5f951394 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwMemPool.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwMemPool.cpp
@@ -29,7 +29,7 @@
static thread_local SwMpool* _pool = nullptr;
static Array<SwMpool*> _pools;
static uint32_t _threads = 0;
-static Key _key;
+static StrictKey _key;
/************************************************************************/
/* External Class Implementation */
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwPostEffect.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwPostEffect.cpp
similarity index 61%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwPostEffect.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwPostEffect.cpp
index e7cc19d07ea..513e497f119 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwPostEffect.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwPostEffect.cpp
@@ -20,8 +20,7 @@
* SOFTWARE.
*/
-#include "tvgMath.h"
-#include "tvgSwCommon.h"
+#include "tvgSwRasterCore.h"
/************************************************************************/
/* Gaussian Blur Implementation */
@@ -35,14 +34,6 @@ struct SwGaussianBlur
int extends;
};
-
-static inline int _gaussianEdgeWrap(int end, int idx)
-{
- auto r = idx % (end + 1);
- return (r < 0) ? (end + 1) + r : r;
-}
-
-
static inline int _gaussianEdgeExtend(int end, int idx)
{
if (idx < 0) return 0;
@@ -50,64 +41,64 @@ static inline int _gaussianEdgeExtend(int end, int idx)
return idx;
}
-
-template<int border>
-static inline int _gaussianRemap(int end, int idx)
-{
- if (border == 1) return _gaussianEdgeWrap(end, idx);
- return _gaussianEdgeExtend(end, idx);
-}
-
-
-//TODO: SIMD OPTIMIZATION?
-template<int border = 0>
static void _gaussianFilter(uint8_t* dst, uint8_t* src, int32_t stride, int32_t w, int32_t h, const RenderRegion& bbox, int32_t dimension, bool flipped)
{
if (flipped) {
- src += (bbox.min.x * stride + bbox.min.y) << 2;
- dst += (bbox.min.x * stride + bbox.min.y) << 2;
+ src += (bbox.xMin * stride + bbox.yMin) << 2;
+ dst += (bbox.xMin * stride + bbox.yMin) << 2;
} else {
- src += (bbox.min.y * stride + bbox.min.x) << 2;
- dst += (bbox.min.y * stride + bbox.min.x) << 2;
+ src += (bbox.yMin * stride + bbox.xMin) << 2;
+ dst += (bbox.yMin * stride + bbox.xMin) << 2;
}
auto iarr = 1.0f / (dimension + dimension + 1);
- auto end = w - 1;
#pragma omp parallel for
for (int y = 0; y < h; ++y) {
- auto p = y * stride;
- auto i = p * 4; //current index
- auto l = -(dimension + 1); //left index
- auto r = dimension; //right index
- int acc[4] = {0, 0, 0, 0}; //sliding accumulator
+ rasterGaussianFilterRow(dst + y * stride * 4, src + y * stride * 4, w, dimension, iarr);
+ }
+}
- //initial accumulation
- for (int x = l; x < r; ++x) {
- auto id = (_gaussianRemap<border>(end, x) + p) * 4;
- acc[0] += src[id++];
- acc[1] += src[id++];
- acc[2] += src[id++];
- acc[3] += src[id];
- }
- //perform filtering
- for (int x = 0; x < w; ++x, ++r, ++l) {
- auto rid = (_gaussianRemap<border>(end, r) + p) * 4;
- auto lid = (_gaussianRemap<border>(end, l) + p) * 4;
- acc[0] += src[rid++] - src[lid++];
- acc[1] += src[rid++] - src[lid++];
- acc[2] += src[rid++] - src[lid++];
- acc[3] += src[rid] - src[lid];
- //ignored rounding for the performance. It should be originally: acc[idx] * iarr + 0.5f
- dst[i++] = static_cast<uint8_t>(acc[0] * iarr);
- dst[i++] = static_cast<uint8_t>(acc[1] * iarr);
- dst[i++] = static_cast<uint8_t>(acc[2] * iarr);
- dst[i++] = static_cast<uint8_t>(acc[3] * iarr);
+static void _gaussianXYFlip(uint32_t* src, uint32_t* dst, int32_t stride, int32_t w, int32_t h, const RenderRegion& bbox, bool flipped)
+{
+ constexpr int32_t BLOCK = 8; // experimental decision
+
+ if (flipped) {
+ src += ((bbox.xMin * stride) + bbox.yMin);
+ dst += ((bbox.yMin * stride) + bbox.xMin);
+ } else {
+ src += ((bbox.yMin * stride) + bbox.xMin);
+ dst += ((bbox.xMin * stride) + bbox.yMin);
+ }
+
+ #pragma omp parallel for
+ for (int32_t x = 0; x < w; x += BLOCK) {
+ auto bx = std::min(w, x + BLOCK) - x;
+ auto in = &src[x];
+ auto out = &dst[x * stride];
+ for (int32_t y = 0; y < h; y += BLOCK) {
+ auto p = &in[y * stride];
+ auto q = &out[y];
+ auto by = std::min(h, y + BLOCK) - y;
+#if defined(THORVG_AVX_SUPPORT) || defined(THORVG_NEON_SUPPORT)
+ if (bx == BLOCK && by == BLOCK && rasterGaussianXYFlipBlock) {
+ rasterGaussianXYFlipBlock(p, q, stride);
+ continue;
+ }
+#endif
+ for (int32_t xx = 0; xx < bx; ++xx) {
+ for (int32_t yy = 0; yy < by; ++yy) {
+ *q = *p;
+ p += stride;
+ ++q;
+ }
+ p += 1 - by * stride;
+ q += stride - by;
+ }
}
}
}
-
//Fast Almost-Gaussian Filtering Method by Peter Kovesi
static int _gaussianInit(SwGaussianBlur* data, float sigma, int quality)
{
@@ -133,7 +124,6 @@ static int _gaussianInit(SwGaussianBlur* data, float sigma, int quality)
return extends;
}
-
bool effectGaussianBlurRegion(RenderEffectGaussianBlur* params)
{
//region expansion for feathering
@@ -141,50 +131,42 @@ bool effectGaussianBlurRegion(RenderEffectGaussianBlur* params)
auto extra = static_cast<SwGaussianBlur*>(params->rd)->extends;
if (params->direction != 2) {
- bbox.min.x = -extra;
- bbox.max.x = extra;
+ bbox.xMin = -extra;
+ bbox.xMax = extra;
}
if (params->direction != 1) {
- bbox.min.y = -extra;
- bbox.max.y = extra;
+ bbox.yMin = -extra;
+ bbox.yMax = extra;
}
return true;
}
-
void effectGaussianBlurUpdate(RenderEffectGaussianBlur* params, const Matrix& transform)
{
if (!params->rd) params->rd = tvg::malloc<SwGaussianBlur>(sizeof(SwGaussianBlur));
auto rd = static_cast<SwGaussianBlur*>(params->rd);
//compute box kernel sizes
- auto scale = sqrt(transform.e11 * transform.e11 + transform.e12 * transform.e12);
- rd->extends = _gaussianInit(rd, std::pow(params->sigma * scale, 2), params->quality);
+ auto scaleSquared = transform.e11 * transform.e11 + transform.e12 * transform.e12;
+ rd->extends = _gaussianInit(rd, params->sigma * params->sigma * scaleSquared, params->quality);
- //invalid
- if (rd->extends == 0) {
- params->valid = false;
- return;
- }
-
- params->valid = true;
+ params->valid = (rd->extends > 0);
}
-
bool effectGaussianBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffectGaussianBlur* params)
{
auto& buffer = surface->compositor->image;
auto data = static_cast<SwGaussianBlur*>(params->rd);
auto& bbox = cmp->bbox;
- auto w = (bbox.max.x - bbox.min.x);
- auto h = (bbox.max.y - bbox.min.y);
+ auto w = (bbox.xMax - bbox.xMin);
+ auto h = (bbox.yMax - bbox.yMin);
auto stride = cmp->image.stride;
auto front = cmp->image.buf32;
auto back = buffer.buf32;
auto swapped = false;
- TVGLOG("SW_ENGINE", "GaussianFilter region(%d, %d, %d, %d) params(%f %d %d), level(%d)", bbox.min.x, bbox.min.y, bbox.max.x, bbox.max.y, params->sigma, params->direction, params->border, data->level);
+ TVGLOG("SW_ENGINE", "GaussianFilter region(%d, %d, %d, %d) params(%f %d), level(%d)", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax, params->sigma, params->direction, data->level);
/* It is best to take advantage of the Gaussian blur’s separable property
by dividing the process into two passes. horizontal and vertical.
@@ -201,7 +183,7 @@ bool effectGaussianBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffec
//vertical. x/y flipping and horionztal access is pretty compatible with the memory architecture.
if (params->direction != 1) {
- rasterXYFlip(front, back, stride, w, h, bbox, false);
+ _gaussianXYFlip(front, back, stride, w, h, bbox, false);
std::swap(front, back);
for (int i = 0; i < data->level; ++i) {
@@ -210,7 +192,7 @@ bool effectGaussianBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffec
swapped = !swapped;
}
- rasterXYFlip(front, back, stride, h, w, bbox, true);
+ _gaussianXYFlip(front, back, stride, h, w, bbox, true);
std::swap(front, back);
}
@@ -219,6 +201,122 @@ bool effectGaussianBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffec
return true;
}
+/************************************************************************/
+/* Motion Blur Implementation */
+/************************************************************************/
+
+struct SwMotionBlur
+{
+ static constexpr int MAX_TAPS = 4 * 257;
+
+ // integer pixel offsets with accumulated bilinear weights scaled by 65536.
+ struct Tap
+ {
+ int32_t x, y;
+ uint32_t weight;
+ } taps[MAX_TAPS];
+
+ int count; // sample count, before merging bilinear taps
+ int tapCount;
+ SwPoint extent;
+};
+
+void effectMotionBlurUpdate(RenderEffectMotionBlur* params, const Matrix& transform)
+{
+ Point offset;
+ int samples;
+ if (!params->update(transform, offset, samples)) return;
+
+ if (!params->rd) params->rd = tvg::malloc<SwMotionBlur>(sizeof(SwMotionBlur));
+ auto data = static_cast<SwMotionBlur*>(params->rd);
+ data->extent = {int32_t(ceilf(fabsf(offset.x) * 0.5f)), int32_t(ceilf(fabsf(offset.y) * 0.5f))};
+ data->count = samples;
+
+ // flatten bilinear samples into nonzero integer taps.
+ data->tapCount = 0;
+ for (int i = 0; i < data->count; ++i) {
+ auto pt = offset * ((i + 0.5f) / data->count - 0.5f);
+ auto x = int32_t(floorf(pt.x));
+ auto y = int32_t(floorf(pt.y));
+ auto fx = uint32_t((pt.x - x) * 256.0f + 0.5f);
+ auto fy = uint32_t((pt.y - y) * 256.0f + 0.5f);
+ uint32_t weights[] = {(256 - fx) * (256 - fy), fx * (256 - fy), (256 - fx) * fy, fx * fy};
+ for (int k = 0; k < 4; ++k) {
+ if (weights[k]) data->taps[data->tapCount++] = {x + (k & 1), y + (k >> 1), weights[k]};
+ }
+ }
+
+ // merge repeated coordinates without changing the total integer weight.
+ std::qsort(data->taps, data->tapCount, sizeof(SwMotionBlur::Tap), [](const void* lhs, const void* rhs) {
+ auto a = static_cast<const SwMotionBlur::Tap*>(lhs);
+ auto b = static_cast<const SwMotionBlur::Tap*>(rhs);
+ if (a->y != b->y) return (a->y > b->y) ? 1 : -1;
+ return (a->x > b->x) - (a->x < b->x);
+ });
+ int merged = 0;
+ for (int i = 0; i < data->tapCount; ++i) {
+ auto& tap = data->taps[i];
+ if (merged > 0 && data->taps[merged - 1].x == tap.x && data->taps[merged - 1].y == tap.y) {
+ data->taps[merged - 1].weight += tap.weight;
+ } else {
+ data->taps[merged++] = tap;
+ }
+ }
+ data->tapCount = merged;
+ params->valid = true;
+}
+
+bool effectMotionBlurRegion(RenderEffectMotionBlur* params)
+{
+ auto data = static_cast<SwMotionBlur*>(params->rd);
+ params->extend = {-data->extent.x, -data->extent.y, data->extent.x, data->extent.y};
+ return true;
+}
+
+bool effectMotionBlur(SwCompositor* cmp, SwSurface* surface, const RenderEffectMotionBlur* params)
+{
+ auto& buffer = surface->compositor->image;
+ auto data = static_cast<SwMotionBlur*>(params->rd);
+ auto& bbox = cmp->bbox;
+ auto stride = cmp->image.stride;
+ auto w = bbox.xMax - bbox.xMin;
+ auto h = bbox.yMax - bbox.yMin;
+ auto divisor = uint64_t(data->count) * 65536;
+ auto src = cmp->image.buf32 + bbox.yMin * stride + bbox.xMin;
+ auto dst = buffer.buf32 + bbox.yMin * stride + bbox.xMin;
+
+ #pragma omp parallel for
+ for (int32_t y = 0; y < h; ++y) {
+ // Y clamping and row addressing are shared by all pixels in this row.
+ const uint32_t* tapRows[SwMotionBlur::MAX_TAPS];
+ for (int i = 0; i < data->tapCount; ++i) {
+ auto sy = _gaussianEdgeExtend(h - 1, y + data->taps[i].y);
+ tapRows[i] = src + sy * stride;
+ }
+ // Accumulate weighted taps with X coordinates clamped to the row edges.
+ // Each sample contributes 65536 total weight; normalize with rounding.
+ auto row = (uint8_t*)(dst + y * stride);
+ for (int32_t x = 0; x < w; ++x) {
+ uint64_t acc[4] = {};
+ for (int i = 0; i < data->tapCount; ++i) {
+ auto& tap = data->taps[i];
+ auto sx = _gaussianEdgeExtend(w - 1, x + tap.x);
+ auto pixel = (uint8_t*)(tapRows[i] + sx);
+ // Filter premultiplied channels together to preserve alpha.
+ for (int c = 0; c < 4; ++c) {
+ acc[c] += uint64_t(pixel[c]) * tap.weight;
+ }
+ }
+ for (int c = 0; c < 4; ++c) {
+ row[x * 4 + c] = uint8_t((acc[c] + divisor / 2) / divisor);
+ }
+ }
+ }
+
+ std::swap(cmp->image.buf8, buffer.buf8);
+ return true;
+}
+
/************************************************************************/
/* Drop Shadow Implementation */
/************************************************************************/
@@ -228,16 +326,15 @@ struct SwDropShadow : SwGaussianBlur
SwPoint offset;
};
-
//TODO: SIMD OPTIMIZATION?
static void _dropShadowFilter(uint32_t* dst, uint32_t* src, int stride, int w, int h, const RenderRegion& bbox, int32_t dimension, uint32_t color, bool flipped)
{
if (flipped) {
- src += (bbox.min.x * stride + bbox.min.y);
- dst += (bbox.min.x * stride + bbox.min.y);
+ src += (bbox.xMin * stride + bbox.yMin);
+ dst += (bbox.xMin * stride + bbox.yMin);
} else {
- src += (bbox.min.y * stride + bbox.min.x);
- dst += (bbox.min.y * stride + bbox.min.x);
+ src += (bbox.yMin * stride + bbox.xMin);
+ dst += (bbox.yMin * stride + bbox.xMin);
}
auto iarr = 1.0f / (dimension + dimension + 1);
auto end = w - 1;
@@ -268,8 +365,8 @@ static void _dropShadowFilter(uint32_t* dst, uint32_t* src, int stride, int w, i
static void _shift(uint32_t** dst, uint32_t** src, int dstride, int sstride, int wmax, int hmax, const RenderRegion& bbox, SwPoint offset, SwSize& size)
{
- size.w = bbox.max.x - bbox.min.x;
- size.h = bbox.max.y - bbox.min.y;
+ size.w = bbox.xMax - bbox.xMin;
+ size.h = bbox.yMax - bbox.yMin;
//shift
if (offset.x < 0) {
@@ -289,11 +386,11 @@ static void _shift(uint32_t** dst, uint32_t** src, int dstride, int sstride, int
}
}
-
+// TODO: simd & openmp optimization?
static void _dropShadowNoFilter(uint32_t* dst, uint32_t* src, int dstride, int sstride, int dw, int dh, const RenderRegion& bbox, const SwPoint& offset, uint32_t color, uint8_t opacity, bool direct)
{
- src += (bbox.min.y * sstride + bbox.min.x);
- dst += (bbox.min.y * dstride + bbox.min.x);
+ src += (bbox.yMin * sstride + bbox.xMin);
+ dst += (bbox.yMin * dstride + bbox.xMin);
SwSize size;
_shift(&dst, &src, dstride, sstride, dw, dh, bbox, offset, size);
@@ -311,7 +408,6 @@ static void _dropShadowNoFilter(uint32_t* dst, uint32_t* src, int dstride, int s
}
}
-
static void _dropShadowNoFilter(SwImage* dimg, SwImage* simg, const RenderRegion& bbox, const SwPoint& offset, uint32_t color)
{
int dstride = dimg->stride;
@@ -321,38 +417,34 @@ static void _dropShadowNoFilter(SwImage* dimg, SwImage* simg, const RenderRegion
_dropShadowNoFilter(dimg->buf32, simg->buf32, dstride, sstride, dimg->w, dimg->h, bbox, offset, color, 255, false);
//original image
- auto src = simg->buf32 + (bbox.min.y * sstride + bbox.min.x);
- auto dst = dimg->buf32 + (bbox.min.y * dstride + bbox.min.x);
-
- for (auto y = 0; y < (bbox.max.y - bbox.min.y); ++y) {
- auto s = src;
- auto d = dst;
- for (int x = 0; x < (bbox.max.x - bbox.min.x); ++x, ++d, ++s) {
- *d = *s + ALPHA_BLEND(*d, IA(*s));
- }
+ auto src = simg->buf32 + (bbox.yMin * sstride + bbox.xMin);
+ auto dst = dimg->buf32 + (bbox.yMin * dstride + bbox.xMin);
+
+ // TODO: openmp optimization?
+ for (auto y = 0; y < (bbox.yMax - bbox.yMin); ++y) {
+ rasterTranslucentPixels(dst, src, bbox.xMax - bbox.xMin, 255);
src += sstride;
dst += dstride;
}
}
-
static void _dropShadowShift(uint32_t* dst, uint32_t* src, int dstride, int sstride, int dw, int dh, const RenderRegion& bbox, const SwPoint& offset, uint8_t opacity, bool direct)
{
- src += (bbox.min.y * sstride + bbox.min.x);
- dst += (bbox.min.y * dstride + bbox.min.x);
+ src += (bbox.yMin * sstride + bbox.xMin);
+ dst += (bbox.yMin * dstride + bbox.xMin);
SwSize size;
_shift(&dst, &src, dstride, sstride, dw, dh, bbox, offset, size);
+ // TODO: openmp optimization?
for (auto y = 0; y < size.h; ++y) {
- if (direct) rasterTranslucentPixel32(dst, src, size.w, opacity);
- else rasterPixel32(dst, src, size.w, opacity);
+ if (direct) rasterTranslucentPixels(dst, src, size.w, opacity);
+ else rasterSolidPixels(dst, src, size.w, opacity);
src += sstride;
dst += dstride;
}
}
-
bool effectDropShadowRegion(RenderEffectDropShadow* params)
{
//region expansion for feathering
@@ -360,42 +452,35 @@ bool effectDropShadowRegion(RenderEffectDropShadow* params)
auto& offset = static_cast<SwDropShadow*>(params->rd)->offset;
auto extra = static_cast<SwDropShadow*>(params->rd)->extends;
- bbox.min = {-extra, -extra};
- bbox.max = {extra, extra};
+ bbox.xMin = -extra;
+ bbox.yMin = -extra;
+ bbox.xMax = extra;
+ bbox.yMax = extra;
- if (offset.x < 0) bbox.min.x += (int32_t) offset.x;
- else bbox.max.x += offset.x;
+ if (offset.x < 0) bbox.xMin += (int32_t)offset.x;
+ else bbox.xMax += offset.x;
- if (offset.y < 0) bbox.min.y += (int32_t) offset.y;
- else bbox.max.y += offset.y;
+ if (offset.y < 0) bbox.yMin += (int32_t)offset.y;
+ else bbox.yMax += offset.y;
return true;
}
-
void effectDropShadowUpdate(RenderEffectDropShadow* params, const Matrix& transform)
{
+ Point offset;
+ if (!params->update(transform, offset)) return;
+
if (!params->rd) params->rd = tvg::malloc<SwDropShadow>(sizeof(SwDropShadow));
auto rd = static_cast<SwDropShadow*>(params->rd);
- //compute box kernel sizes
- auto scale = sqrt(transform.e11 * transform.e11 + transform.e12 * transform.e12);
- rd->extends = _gaussianInit(rd, std::pow(params->sigma * scale, 2), params->quality);
-
- //invalid
- if (params->color[3] == 0) {
- params->valid = false;
- return;
- }
-
- //offset
- auto radian = tvg::deg2rad(90.0f - params->angle) - tvg::radian(transform);
- rd->offset = {(int32_t)((params->distance * scale) * cosf(radian)), (int32_t)(-1.0f * (params->distance * scale) * sinf(radian))};
+ // The sum of the box radii covers the full blur support.
+ auto scaleSquared = transform.e11 * transform.e11 + transform.e12 * transform.e12;
+ rd->extends = _gaussianInit(rd, params->sigma * params->sigma * scaleSquared, params->quality);
- params->valid = true;
+ rd->offset = {(int32_t)offset.x, (int32_t)offset.y};
}
-
//A quite same integration with effectGaussianBlur(). See it for detailed comments.
//surface[0]: the original image, to overlay it into the filtered image.
//surface[1]: temporary buffer for generating the filtered image.
@@ -405,8 +490,8 @@ bool effectDropShadow(SwCompositor* cmp, SwSurface* surface[2], const RenderEffe
auto data = static_cast<SwDropShadow*>(params->rd);
auto& bbox = cmp->bbox;
- auto w = (bbox.max.x - bbox.min.x);
- auto h = (bbox.max.y - bbox.min.y);
+ auto w = (bbox.xMax - bbox.xMin);
+ auto h = (bbox.yMax - bbox.yMin);
//outside the screen
if (abs(data->offset.x) >= w || abs(data->offset.y) >= h) return true;
@@ -419,7 +504,7 @@ bool effectDropShadow(SwCompositor* cmp, SwSurface* surface[2], const RenderEffe
auto opacity = direct ? MULTIPLY(params->color[3], cmp->opacity) : params->color[3];
- TVGLOG("SW_ENGINE", "DropShadow region(%d, %d, %d, %d) params(%f %f %f), level(%d)", bbox.min.x, bbox.min.y, bbox.max.x, bbox.max.y, params->angle, params->distance, params->sigma, data->level);
+ TVGLOG("SW_ENGINE", "DropShadow region(%d, %d, %d, %d) params(%f %f %f), level(%d)", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax, params->angle, params->distance, params->sigma, data->level);
//no filter required
if (data->extends == 0) {
@@ -444,7 +529,7 @@ bool effectDropShadow(SwCompositor* cmp, SwSurface* surface[2], const RenderEffe
}
//vertical
- rasterXYFlip(front, back, stride, w, h, bbox, false);
+ _gaussianXYFlip(front, back, stride, w, h, bbox, false);
std::swap(front, back);
for (int i = 0; i < data->level; ++i) {
@@ -452,7 +537,7 @@ bool effectDropShadow(SwCompositor* cmp, SwSurface* surface[2], const RenderEffe
std::swap(front, back);
}
- rasterXYFlip(front, back, stride, h, w, bbox, true);
+ _gaussianXYFlip(front, back, stride, h, w, bbox, true);
std::swap(cmp->image.buf32, back);
//draw to the main surface directly
@@ -463,16 +548,17 @@ bool effectDropShadow(SwCompositor* cmp, SwSurface* surface[2], const RenderEffe
}
//draw to the intermediate surface
- rasterClear(surface[1], bbox.min.x, bbox.min.y, w, h);
+ rasterClear(surface[1], bbox.xMin, bbox.yMin, w, h);
_dropShadowShift(buffer[1]->buf32, cmp->image.buf32, buffer[1]->stride, cmp->image.stride, buffer[1]->w, buffer[1]->h, bbox, data->offset, opacity, direct);
std::swap(cmp->image.buf32, buffer[1]->buf32);
//compositing shadow and body
- auto s = buffer[0]->buf32 + (bbox.min.y * buffer[0]->stride + bbox.min.x);
- auto d = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto s = buffer[0]->buf32 + (bbox.yMin * buffer[0]->stride + bbox.xMin);
+ auto d = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
+ // TODO: openmp optimization?
for (auto y = 0; y < h; ++y) {
- rasterTranslucentPixel32(d, s, w, 255);
+ rasterTranslucentPixels(d, s, w, 255);
s += buffer[0]->stride;
d += cmp->image.stride;
}
@@ -480,7 +566,6 @@ bool effectDropShadow(SwCompositor* cmp, SwSurface* surface[2], const RenderEffe
return true;
}
-
/************************************************************************/
/* Fill Implementation */
/************************************************************************/
@@ -490,21 +575,21 @@ void effectFillUpdate(RenderEffectFill* params)
params->valid = true;
}
-
+// TODO: simd & openmp optimization?
bool effectFill(SwCompositor* cmp, const RenderEffectFill* params, bool direct)
{
auto opacity = direct ? MULTIPLY(params->color[3], cmp->opacity) : params->color[3];
auto& bbox = cmp->bbox;
- auto w = size_t(bbox.max.x - bbox.min.x);
- auto h = size_t(bbox.max.y - bbox.min.y);
+ auto w = size_t(bbox.xMax - bbox.xMin);
+ auto h = size_t(bbox.yMax - bbox.yMin);
auto color = cmp->recoverSfc->join(params->color[0], params->color[1], params->color[2], 255);
- TVGLOG("SW_ENGINE", "Fill region(%d, %d, %d, %d), param(%d %d %d %d)", bbox.min.x, bbox.min.y, bbox.max.x, bbox.max.y, params->color[0], params->color[1], params->color[2], params->color[3]);
+ TVGLOG("SW_ENGINE", "Fill region(%d, %d, %d, %d), param(%d %d %d %d)", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax, params->color[0], params->color[1], params->color[2], params->color[3]);
if (direct) {
- auto dbuffer = cmp->recoverSfc->buf32 + (bbox.min.y * cmp->recoverSfc->stride + bbox.min.x);
- auto sbuffer = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto dbuffer = cmp->recoverSfc->buf32 + (bbox.yMin * cmp->recoverSfc->stride + bbox.xMin);
+ auto sbuffer = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
for (size_t y = 0; y < h; ++y) {
auto dst = dbuffer;
auto src = sbuffer;
@@ -513,12 +598,12 @@ bool effectFill(SwCompositor* cmp, const RenderEffectFill* params, bool direct)
auto tmp = ALPHA_BLEND(color, a);
*dst = tmp + ALPHA_BLEND(*dst, 255 - a);
}
- dbuffer += cmp->image.stride;
- sbuffer += cmp->recoverSfc->stride;
+ dbuffer += cmp->recoverSfc->stride;
+ sbuffer += cmp->image.stride;
}
cmp->valid = true; //no need the subsequent composition
} else {
- auto dbuffer = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto dbuffer = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
for (size_t y = 0; y < h; ++y) {
auto dst = dbuffer;
for (size_t x = 0; x < w; ++x, ++dst) {
@@ -530,7 +615,6 @@ bool effectFill(SwCompositor* cmp, const RenderEffectFill* params, bool direct)
return true;
}
-
/************************************************************************/
/* Tint Implementation */
/************************************************************************/
@@ -540,22 +624,22 @@ void effectTintUpdate(RenderEffectTint* params)
params->valid = (params->intensity > 0);
}
-
+// TODO: simd & openmp optimization?
bool effectTint(SwCompositor* cmp, const RenderEffectTint* params, bool direct)
{
auto& bbox = cmp->bbox;
- auto w = size_t(bbox.max.x - bbox.min.x);
- auto h = size_t(bbox.max.y - bbox.min.y);
+ auto w = size_t(bbox.xMax - bbox.xMin);
+ auto h = size_t(bbox.yMax - bbox.yMin);
auto black = cmp->recoverSfc->join(params->black[0], params->black[1], params->black[2], 255);
auto white = cmp->recoverSfc->join(params->white[0], params->white[1], params->white[2], 255);
auto opacity = cmp->opacity;
auto luma = cmp->recoverSfc->alphas[2]; //luma function
- TVGLOG("SW_ENGINE", "Tint region(%d, %d, %d, %d), param(%d %d %d, %d %d %d, %d)", bbox.min.x, bbox.min.y, bbox.max.x, bbox.max.y, params->black[0], params->black[1], params->black[2], params->white[0], params->white[1], params->white[2], params->intensity);
+ TVGLOG("SW_ENGINE", "Tint region(%d, %d, %d, %d), param(%d %d %d, %d %d %d, %d)", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax, params->black[0], params->black[1], params->black[2], params->white[0], params->white[1], params->white[2], params->intensity);
if (direct) {
- auto dbuffer = cmp->recoverSfc->buf32 + (bbox.min.y * cmp->recoverSfc->stride + bbox.min.x);
- auto sbuffer = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto dbuffer = cmp->recoverSfc->buf32 + (bbox.yMin * cmp->recoverSfc->stride + bbox.xMin);
+ auto sbuffer = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
for (size_t y = 0; y < h; ++y) {
auto dst = dbuffer;
auto src = sbuffer;
@@ -564,16 +648,16 @@ bool effectTint(SwCompositor* cmp, const RenderEffectTint* params, bool direct)
if (params->intensity < 255) val = INTERPOLATE(val, *src, params->intensity);
*dst = INTERPOLATE(val, *dst, MULTIPLY(opacity, A(*src)));
}
- dbuffer += cmp->image.stride;
- sbuffer += cmp->recoverSfc->stride;
+ dbuffer += cmp->recoverSfc->stride;
+ sbuffer += cmp->image.stride;
}
cmp->valid = true; //no need the subsequent composition
} else {
- auto dbuffer = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto dbuffer = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
for (size_t y = 0; y < h; ++y) {
auto dst = dbuffer;
for (size_t x = 0; x < w; ++x, ++dst) {
- auto val = INTERPOLATE(white, black, luma((uint8_t*)&dst));
+ auto val = INTERPOLATE(white, black, luma((uint8_t*)dst));
if (params->intensity < 255) val = INTERPOLATE(val, *dst, params->intensity);
*dst = ALPHA_BLEND(val, MULTIPLY(opacity, A(*dst)));
}
@@ -584,7 +668,6 @@ bool effectTint(SwCompositor* cmp, const RenderEffectTint* params, bool direct)
return true;
}
-
/************************************************************************/
/* Tritone Implementation */
/************************************************************************/
@@ -600,29 +683,28 @@ static uint32_t _trintone(uint32_t s, uint32_t m, uint32_t h, int l)
}
}
-
void effectTritoneUpdate(RenderEffectTritone* params)
{
params->valid = (params->blender < 255);
}
-
+// TODO: simd & openmp optimization?
bool effectTritone(SwCompositor* cmp, const RenderEffectTritone* params, bool direct)
{
auto& bbox = cmp->bbox;
- auto w = size_t(bbox.max.x - bbox.min.x);
- auto h = size_t(bbox.max.y - bbox.min.y);
+ auto w = size_t(bbox.xMax - bbox.xMin);
+ auto h = size_t(bbox.yMax - bbox.yMin);
auto shadow = cmp->recoverSfc->join(params->shadow[0], params->shadow[1], params->shadow[2], 255);
auto midtone = cmp->recoverSfc->join(params->midtone[0], params->midtone[1], params->midtone[2], 255);
auto highlight = cmp->recoverSfc->join(params->highlight[0], params->highlight[1], params->highlight[2], 255);
auto opacity = cmp->opacity;
auto luma = cmp->recoverSfc->alphas[2]; //luma function
- TVGLOG("SW_ENGINE", "Tritone region(%d, %d, %d, %d), param(%d %d %d, %d %d %d, %d %d %d, %d)", bbox.min.x, bbox.min.y, bbox.max.x, bbox.max.y, params->shadow[0], params->shadow[1], params->shadow[2], params->midtone[0], params->midtone[1], params->midtone[2], params->highlight[0], params->highlight[1], params->highlight[2], params->blender);
+ TVGLOG("SW_ENGINE", "Tritone region(%d, %d, %d, %d), param(%d %d %d, %d %d %d, %d %d %d, %d)", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax, params->shadow[0], params->shadow[1], params->shadow[2], params->midtone[0], params->midtone[1], params->midtone[2], params->highlight[0], params->highlight[1], params->highlight[2], params->blender);
if (direct) {
- auto dbuffer = cmp->recoverSfc->buf32 + (bbox.min.y * cmp->recoverSfc->stride + bbox.min.x);
- auto sbuffer = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto dbuffer = cmp->recoverSfc->buf32 + (bbox.yMin * cmp->recoverSfc->stride + bbox.xMin);
+ auto sbuffer = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
for (size_t y = 0; y < h; ++y) {
auto dst = dbuffer;
auto src = sbuffer;
@@ -635,12 +717,12 @@ bool effectTritone(SwCompositor* cmp, const RenderEffectTritone* params, bool di
*dst = INTERPOLATE(INTERPOLATE(*src, _trintone(shadow, midtone, highlight, luma((uint8_t*)src)), params->blender), *dst, MULTIPLY(opacity, A(*src)));
}
}
- dbuffer += cmp->image.stride;
- sbuffer += cmp->recoverSfc->stride;
+ dbuffer += cmp->recoverSfc->stride;
+ sbuffer += cmp->image.stride;
}
cmp->valid = true; //no need the subsequent composition
} else {
- auto dbuffer = cmp->image.buf32 + (bbox.min.y * cmp->image.stride + bbox.min.x);
+ auto dbuffer = cmp->image.buf32 + (bbox.yMin * cmp->image.stride + bbox.xMin);
for (size_t y = 0; y < h; ++y) {
auto dst = dbuffer;
if (params->blender == 0) {
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRaster.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRaster.cpp
similarity index 57%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwRaster.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRaster.cpp
index 63c965625e3..2c91f188611 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRaster.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRaster.cpp
@@ -20,118 +20,49 @@
* SOFTWARE.
*/
-#include "tvgMath.h"
-#include "tvgRender.h"
-#include "tvgSwCommon.h"
+#include "tvgSwRasterCore.h"
/************************************************************************/
-/* Internal Class Implementation */
+/* Helpers */
/************************************************************************/
-constexpr auto DOWN_SCALE_TOLERANCE = 0.5f;
-
-struct FillLinear
-{
- void operator()(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask op, uint8_t a)
- {
- fillLinear(fill, dst, y, x, len, op, a);
- }
-
- void operator()(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask op, uint8_t a)
- {
- fillLinear(fill, dst, y, x, len, cmp, op, a);
- }
-
- void operator()(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
- {
- fillLinear(fill, dst, y, x, len, op, a);
- }
-
- void operator()(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
- {
- fillLinear(fill, dst, y, x, len, cmp, alpha, csize, opacity);
- }
-
- void operator()(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
- {
- fillLinear(fill, dst, y, x, len, op, op2, a);
- }
-
-};
-
-struct FillRadial
-{
- void operator()(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, SwMask op, uint8_t a)
- {
- fillRadial(fill, dst, y, x, len, op, a);
- }
-
- void operator()(const SwFill* fill, uint8_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwMask op, uint8_t a)
- {
- fillRadial(fill, dst, y, x, len, cmp, op, a);
- }
-
- void operator()(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, uint8_t a)
- {
- fillRadial(fill, dst, y, x, len, op, a);
- }
-
- void operator()(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, uint8_t* cmp, SwAlpha alpha, uint8_t csize, uint8_t opacity)
- {
- fillRadial(fill, dst, y, x, len, cmp, alpha, csize, opacity);
- }
-
- void operator()(const SwFill* fill, uint32_t* dst, uint32_t y, uint32_t x, uint32_t len, SwBlenderA op, SwBlender op2, uint8_t a)
- {
- fillRadial(fill, dst, y, x, len, op, op2, a);
- }
-};
-
-
static inline uint8_t _alpha(uint8_t* a)
{
return *a;
}
-
static inline uint8_t _ialpha(uint8_t* a)
{
return ~(*a);
}
-
static inline uint8_t _abgrLuma(uint8_t* c)
{
auto v = *(uint32_t*)c;
return ((((v&0xff)*54) + (((v>>8)&0xff)*182) + (((v>>16)&0xff)*19))) >> 8; //0.2126*R + 0.7152*G + 0.0722*B
}
-
static inline uint8_t _argbLuma(uint8_t* c)
{
auto v = *(uint32_t*)c;
return ((((v&0xff)*19) + (((v>>8)&0xff)*182) + (((v>>16)&0xff)*54))) >> 8; //0.0722*B + 0.7152*G + 0.2126*R
}
-
static inline uint8_t _abgrInvLuma(uint8_t* c)
{
return ~_abgrLuma(c);
}
-
static inline uint8_t _argbInvLuma(uint8_t* c)
{
return ~_argbLuma(c);
}
-
static inline uint32_t _abgrJoin(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
return (a << 24 | b << 16 | g << 8 | r);
}
-
static inline uint32_t _argbJoin(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
return (a << 24 | r << 16 | g << 8 | b);
@@ -142,25 +73,16 @@ static inline bool _blending(const SwSurface* surface)
return (surface->blender) ? true : false;
}
-
/* OPTIMIZE_ME: Probably, we can separate masking(8bits) / composition(32bits)
This would help to enhance the performance by avoiding the unnecessary matting from the composition */
static inline bool _compositing(const SwSurface* surface)
{
- if (!surface->compositor || surface->compositor->method == MaskMethod::None) return false;
- return true;
+ return surface->compositor && surface->compositor->method != MaskMethod::None;
}
-
static inline bool _matting(const SwSurface* surface)
{
- if ((int)surface->compositor->method < (int)MaskMethod::Add) return true;
- else return false;
-}
-
-static inline uint8_t _opMaskNone(uint8_t s, TVG_UNUSED uint8_t d, TVG_UNUSED uint8_t a)
-{
- return s;
+ return ((int)surface->compositor->method < (int)MaskMethod::Add);
}
static inline uint8_t _opMaskAdd(uint8_t s, uint8_t d, uint8_t a)
@@ -168,44 +90,36 @@ static inline uint8_t _opMaskAdd(uint8_t s, uint8_t d, uint8_t a)
return s + MULTIPLY(d, a);
}
-
static inline uint8_t _opMaskSubtract(uint8_t s, uint8_t d, TVG_UNUSED uint8_t a)
{
return MULTIPLY(s, 255 - d);
}
-
static inline uint8_t _opMaskIntersect(uint8_t s, uint8_t d, TVG_UNUSED uint8_t a)
{
return MULTIPLY(s, d);
}
-
static inline uint8_t _opMaskDifference(uint8_t s, uint8_t d, uint8_t a)
{
return MULTIPLY(s, 255 - d) + MULTIPLY(d, a);
}
-
static inline uint8_t _opMaskLighten(uint8_t s, uint8_t d, uint8_t a)
{
return (s > d) ? s : d;
}
-
static inline uint8_t _opMaskDarken(uint8_t s, uint8_t d, uint8_t a)
{
return (s < d) ? s : d;
}
-
static inline bool _direct(MaskMethod method)
{
- if (method == MaskMethod::Subtract || method == MaskMethod::Intersect || method == MaskMethod::Darken) return true;
- return false;
+ return (method == MaskMethod::Subtract || method == MaskMethod::Intersect || method == MaskMethod::Darken);
}
-
static inline SwMask _getMaskOp(MaskMethod method)
{
switch (method) {
@@ -219,16 +133,15 @@ static inline SwMask _getMaskOp(MaskMethod method)
}
}
-
static bool _compositeMaskImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox)
{
- auto dbuffer = &surface->buf8[bbox.min.y * surface->stride + bbox.min.x];
- auto sbuffer = image.buf8 + (bbox.min.y + image.oy) * image.stride + (bbox.min.x + image.ox);
+ auto dbuffer = &surface->buf8[bbox.yMin * surface->stride + bbox.xMin];
+ auto sbuffer = image.buf8 + (bbox.yMin + image.oy) * image.stride + (bbox.xMin + image.ox);
- for (auto y = bbox.min.y; y < bbox.max.y; ++y) {
+ for (auto y = bbox.yMin; y < bbox.yMax; ++y) {
auto dst = dbuffer;
auto src = sbuffer;
- for (auto x = bbox.min.x; x < bbox.max.x; x++, dst++, src++) {
+ for (auto x = bbox.xMin; x < bbox.xMax; x++, dst++, src++) {
*dst = *src + MULTIPLY(*dst, ~*src);
}
dbuffer += surface->stride;
@@ -237,12 +150,16 @@ static bool _compositeMaskImage(SwSurface* surface, const SwImage& image, const
return true;
}
+static inline void _rasterPixel8(uint8_t *dst, uint8_t val, uint32_t offset, int32_t len)
+{
+ memset(dst + offset, val, len);
+}
#include "tvgSwRasterTexmap.h"
-#include "tvgSwRasterC.h"
-#include "tvgSwRasterAvx.h"
-#include "tvgSwRasterNeon.h"
+/************************************************************************/
+/* Image Sampling */
+/************************************************************************/
static inline uint32_t _sampleSize(float scale)
{
@@ -251,14 +168,12 @@ static inline uint32_t _sampleSize(float scale)
return sampleSize;
}
-
//Nearest Interpolation
static uint32_t _interpNoScaler(const uint32_t *img, uint32_t stride, TVG_UNUSED uint32_t w, TVG_UNUSED uint32_t h, float sx, float sy, TVG_UNUSED int32_t miny, TVG_UNUSED int32_t maxy, TVG_UNUSED int32_t n)
{
return img[uint32_t(sx) + uint32_t(sy) * stride];
}
-
//Bilinear Interpolation
//OPTIMIZE_ME: Skip the function pointer access
static uint32_t _interpUpScaler(const uint32_t *img, uint32_t stride, uint32_t w, uint32_t h, float sx, float sy, TVG_UNUSED int32_t miny, TVG_UNUSED int32_t maxy, TVG_UNUSED int32_t n)
@@ -281,55 +196,14 @@ static uint32_t _interpUpScaler(const uint32_t *img, uint32_t stride, uint32_t w
return INTERPOLATE(INTERPOLATE(c4, c3, dx), INTERPOLATE(c2, c1, dx), dy);
}
-
-//2n x 2n Mean Kernel
-//OPTIMIZE_ME: Skip the function pointer access
-static uint32_t _interpDownScaler(const uint32_t *img, uint32_t stride, uint32_t w, uint32_t h, float sx, TVG_UNUSED float sy, int32_t miny, int32_t maxy, int32_t n)
-{
- size_t c[4] = {0, 0, 0, 0};
-
- int32_t minx = (int32_t)sx - n;
- if (minx < 0) minx = 0;
-
- int32_t maxx = (int32_t)sx + n;
- if (maxx >= (int32_t)w) maxx = w;
-
- int32_t inc = (n / 2) + 1;
- n = 0;
-
- auto src = img + minx + miny * stride;
-
- for (auto y = miny; y < maxy; y += inc) {
- auto p = src;
- for (auto x = minx; x < maxx; x += inc, p += inc) {
- c[0] += A(*p);
- c[1] += C1(*p);
- c[2] += C2(*p);
- c[3] += C3(*p);
- ++n;
- }
- src += (stride * inc);
- }
-
- c[0] /= n;
- c[1] /= n;
- c[2] /= n;
- c[3] /= n;
-
- return (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3];
-}
-
-
using ImageScaleFilter = uint32_t (*)(const uint32_t* img, uint32_t stride, uint32_t w, uint32_t h, float sx, float sy, int32_t miny, int32_t maxy, int32_t n);
-
static ImageScaleFilter _scaleMethod(const SwImage& image)
{
- if (image.filter == FilterMethod::Bilinear) return image.scale < DOWN_SCALE_TOLERANCE ? _interpDownScaler : _interpUpScaler;
+ if (image.filter == FilterMethod::Bilinear) return image.scale < 0.5f ? rasterDownScaler : _interpUpScaler;
return _interpNoScaler;
}
-
/************************************************************************/
/* Rect */
/************************************************************************/
@@ -337,7 +211,7 @@ static ImageScaleFilter _scaleMethod(const SwImage& image)
static bool _rasterCompositeMaskedRect(SwSurface* surface, const RenderRegion& bbox, SwMask maskOp, uint8_t a)
{
auto cstride = surface->compositor->image.stride;
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * cstride + bbox.min.x); //compositor buffer
+ auto cbuffer = surface->compositor->image.buf8 + (bbox.yMin * cstride + bbox.xMin); // compositor buffer
auto ialpha = 255 - a;
for (uint32_t y = 0; y < bbox.h(); ++y) {
@@ -350,11 +224,10 @@ static bool _rasterCompositeMaskedRect(SwSurface* surface, const RenderRegion& b
return _compositeMaskImage(surface, surface->compositor->image, surface->compositor->bbox);
}
-
static bool _rasterDirectMaskedRect(SwSurface* surface, const RenderRegion& bbox, SwMask maskOp, uint8_t a)
{
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * surface->compositor->image.stride + bbox.min.x); //compositor buffer
- auto dbuffer = surface->buf8 + (bbox.min.y * surface->stride + bbox.min.x); //destination buffer
+ auto cbuffer = surface->compositor->image.buf8 + (bbox.yMin * surface->compositor->image.stride + bbox.xMin); // compositor buffer
+ auto dbuffer = surface->buf8 + (bbox.yMin * surface->stride + bbox.xMin); // destination buffer
for (uint32_t y = 0; y < bbox.h(); ++y) {
auto cmp = cbuffer;
@@ -369,13 +242,13 @@ static bool _rasterDirectMaskedRect(SwSurface* surface, const RenderRegion& bbox
return true;
}
-
static bool _rasterMaskedRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
{
//8bit masking channels composition
- if (surface->channelSize != sizeof(uint8_t)) return false;
-
- TVGLOG("SW_ENGINE", "Masked(%d) Rect [Region: %d %d %d %d]", (int)surface->compositor->method, bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y);
+ if (surface->channelSize != sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "channel size is not 8bits?");
+ return false;
+ }
auto maskOp = _getMaskOp(surface->compositor->method);
if (_direct(surface->compositor->method)) return _rasterDirectMaskedRect(surface, bbox, maskOp, c.a);
@@ -383,19 +256,16 @@ static bool _rasterMaskedRect(SwSurface* surface, const RenderRegion& bbox, cons
return false;
}
-
static bool _rasterMattedRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
{
auto csize = surface->compositor->image.channelSize;
- auto cbuffer = surface->compositor->image.buf8 + ((bbox.min.y * surface->compositor->image.stride + bbox.min.x) * csize); //compositor buffer
+ auto cbuffer = surface->compositor->image.buf8 + ((bbox.yMin * surface->compositor->image.stride + bbox.xMin) * csize); // compositor buffer
auto alpha = surface->alpha(surface->compositor->method);
- TVGLOG("SW_ENGINE", "Matted(%d) Rect [Region: %u %u %u %u]", (int)surface->compositor->method, bbox.x(), bbox.y(), bbox.w(), bbox.h());
-
//32bits channels
if (surface->channelSize == sizeof(uint32_t)) {
auto color = surface->join(c.r, c.g, c.b, c.a);
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
for (uint32_t y = 0; y < bbox.h(); ++y) {
auto dst = &buffer[y * surface->stride];
auto cmp = &cbuffer[y * surface->compositor->image.stride * csize];
@@ -406,7 +276,7 @@ static bool _rasterMattedRect(SwSurface* surface, const RenderRegion& bbox, cons
}
//8bits grayscale
} else if (surface->channelSize == sizeof(uint8_t)) {
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
+ auto buffer = surface->buf8 + (bbox.yMin * surface->stride) + bbox.xMin;
for (uint32_t y = 0; y < bbox.h(); ++y) {
auto dst = &buffer[y * surface->stride];
auto cmp = &cbuffer[y * surface->compositor->image.stride * csize];
@@ -418,73 +288,57 @@ static bool _rasterMattedRect(SwSurface* surface, const RenderRegion& bbox, cons
return true;
}
-
static bool _rasterBlendingRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
{
- if (surface->channelSize != sizeof(uint32_t)) return false;
+ if (surface->channelSize != sizeof(uint32_t)) {
+ TVGERR("SW_ENGINE", "channel size is not 32bits?");
+ return false;
+ }
auto color = surface->join(c.r, c.g, c.b, c.a);
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
for (uint32_t y = 0; y < bbox.h(); ++y) {
auto dst = &buffer[y * surface->stride];
for (uint32_t x = 0; x < bbox.w(); ++x, ++dst) {
- *dst = surface->blender(color, *dst);
+ *dst = surface->blender(surface, color, *dst);
}
}
return true;
}
-
-static bool _rasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
-{
-#if defined(THORVG_AVX_VECTOR_SUPPORT)
- return avxRasterTranslucentRect(surface, bbox, c);
-#elif defined(THORVG_NEON_VECTOR_SUPPORT)
- return neonRasterTranslucentRect(surface, bbox, c);
-#else
- return cRasterTranslucentRect(surface, bbox, c);
-#endif
-}
-
-
static bool _rasterSolidRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
{
//32bits channels
if (surface->channelSize == sizeof(uint32_t)) {
auto color = surface->join(c.r, c.g, c.b, 255);
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride);
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride);
for (uint32_t y = 0; y < bbox.h(); ++y) {
- rasterPixel32(buffer + y * surface->stride, color, bbox.min.x, bbox.w());
+ rasterSolidPixel32(buffer + y * surface->stride, color, bbox.xMin, bbox.w());
}
return true;
}
//8bits grayscale
if (surface->channelSize == sizeof(uint8_t)) {
for (uint32_t y = 0; y < bbox.h(); ++y) {
- rasterGrayscale8(surface->buf8, 255, (y + bbox.min.y) * surface->stride + bbox.min.x, bbox.w());
+ _rasterPixel8(surface->buf8, 255, (y + bbox.yMin) * surface->stride + bbox.xMin, bbox.w());
}
return true;
}
return false;
}
-
static bool _rasterRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
{
if (_compositing(surface)) {
if (_matting(surface)) return _rasterMattedRect(surface, bbox, c);
- else return _rasterMaskedRect(surface, bbox, c);
- } else if (_blending(surface)) {
- return _rasterBlendingRect(surface, bbox, c);
- } else {
- if (c.a == 255) return _rasterSolidRect(surface, bbox, c);
- else return _rasterTranslucentRect(surface, bbox, c);
+ return _rasterMaskedRect(surface, bbox, c);
}
- return false;
+ if (_blending(surface)) return _rasterBlendingRect(surface, bbox, c);
+ if (c.a == 255) return _rasterSolidRect(surface, bbox, c);
+ return rasterTranslucentRect(surface, bbox, c);
}
-
/************************************************************************/
/* Rle */
/************************************************************************/
@@ -510,7 +364,6 @@ static bool _rasterCompositeMaskedRle(SwSurface* surface, SwRle* rle, const Rend
return _compositeMaskImage(surface, surface->compositor->image, surface->compositor->bbox);
}
-
static bool _rasterDirectMaskedRle(SwSurface* surface, SwRle* rle, const RenderRegion& bbox, SwMask maskOp, uint8_t a)
{
auto cbuffer = surface->compositor->image.buf8;
@@ -533,13 +386,13 @@ static bool _rasterDirectMaskedRle(SwSurface* surface, SwRle* rle, const RenderR
return true;
}
-
static bool _rasterMaskedRle(SwSurface* surface, SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
{
- TVGLOG("SW_ENGINE", "Masked(%d) Rle", (int)surface->compositor->method);
-
//8bit masking channels composition
- if (surface->channelSize != sizeof(uint8_t)) return false;
+ if (surface->channelSize != sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "channel size is not 8bits?");
+ return false;
+ }
auto maskOp = _getMaskOp(surface->compositor->method);
if (_direct(surface->compositor->method)) return _rasterDirectMaskedRle(surface, rle, bbox, maskOp, c.a);
@@ -547,11 +400,8 @@ static bool _rasterMaskedRle(SwSurface* surface, SwRle* rle, const RenderRegion&
return false;
}
-
static bool _rasterMattedRle(SwSurface* surface, SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
{
- TVGLOG("SW_ENGINE", "Matted(%d) Rle", (int)surface->compositor->method);
-
auto cbuffer = surface->compositor->image.buf8;
auto csize = surface->compositor->image.channelSize;
auto alpha = surface->alpha(surface->compositor->method);
@@ -590,10 +440,12 @@ static bool _rasterMattedRle(SwSurface* surface, SwRle* rle, const RenderRegion&
return true;
}
-
static bool _rasterBlendingRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
{
- if (surface->channelSize != sizeof(uint32_t)) return false;
+ if (surface->channelSize != sizeof(uint32_t)) {
+ TVGERR("SW_ENGINE", "channel size is not 32bits?");
+ return false;
+ }
auto color = surface->join(c.r, c.g, c.b, c.a);
const SwSpan* end;
@@ -604,30 +456,17 @@ static bool _rasterBlendingRle(SwSurface* surface, const SwRle* rle, const Rende
auto dst = &surface->buf32[span->y * surface->stride + x];
if (span->coverage == 255) {
for (auto x = 0; x < len; ++x, ++dst) {
- *dst = surface->blender(color, *dst);
+ *dst = surface->blender(surface, color, *dst);
}
} else {
for (auto x = 0; x < len; ++x, ++dst) {
- *dst = INTERPOLATE(surface->blender(color, *dst), *dst, span->coverage);
+ *dst = INTERPOLATE(surface->blender(surface, color, *dst), *dst, span->coverage);
}
}
}
return true;
}
-
-static bool _rasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
-{
-#if defined(THORVG_AVX_VECTOR_SUPPORT)
- return avxRasterTranslucentRle(surface, rle, bbox, c);
-#elif defined(THORVG_NEON_VECTOR_SUPPORT)
- return neonRasterTranslucentRle(surface, rle, bbox, c);
-#else
- return cRasterTranslucentRle(surface, rle, bbox, c);
-#endif
-}
-
-
static bool _rasterSolidRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
{
const SwSpan* end;
@@ -638,7 +477,7 @@ static bool _rasterSolidRle(SwSurface* surface, const SwRle* rle, const RenderRe
auto color = surface->join(c.r, c.g, c.b, 255);
for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
if (!span->fetch(bbox, x, len)) continue;
- if (span->coverage == 255) rasterPixel32(surface->buf32 + span->y * surface->stride, color, x, len);
+ if (span->coverage == 255) rasterSolidPixel32(surface->buf32 + span->y * surface->stride, color, x, len);
else {
auto dst = &surface->buf32[span->y * surface->stride + x];
auto src = ALPHA_BLEND(color, span->coverage);
@@ -652,7 +491,7 @@ static bool _rasterSolidRle(SwSurface* surface, const SwRle* rle, const RenderRe
} else if (surface->channelSize == sizeof(uint8_t)) {
for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
if (!span->fetch(bbox, x, len)) continue;
- if (span->coverage == 255) rasterGrayscale8(surface->buf8, span->coverage, span->y * surface->stride + x, len);
+ if (span->coverage == 255) _rasterPixel8(surface->buf8, span->coverage, span->y * surface->stride + x, len);
else {
auto dst = &surface->buf8[span->y * surface->stride + x];
auto ialpha = 255 - span->coverage;
@@ -665,32 +504,27 @@ static bool _rasterSolidRle(SwSurface* surface, const SwRle* rle, const RenderRe
return true;
}
-
static bool _rasterRle(SwSurface* surface, SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
{
if (!rle || rle->invalid()) return false;
if (_compositing(surface)) {
if (_matting(surface)) return _rasterMattedRle(surface, rle, bbox, c);
- else return _rasterMaskedRle(surface, rle, bbox, c);
- } else if (_blending(surface)) {
- return _rasterBlendingRle(surface, rle, bbox, c);
- } else {
- if (c.a == 255) return _rasterSolidRle(surface, rle, bbox, c);
- else return _rasterTranslucentRle(surface, rle, bbox, c);
+ return _rasterMaskedRle(surface, rle, bbox, c);
}
- return false;
+ if (_blending(surface)) return _rasterBlendingRle(surface, rle, bbox, c);
+ if (c.a == 255) return _rasterSolidRle(surface, rle, bbox, c);
+ return rasterTranslucentRle(surface, rle, bbox, c);
}
-
/************************************************************************/
-/* RLE Scaled Image */
+/* Scaled Image */
/************************************************************************/
#define SCALED_IMAGE_RANGE_Y(y) \
auto sy = (y) * itransform->e22 + itransform->e23 - 0.49f; \
if (sy <= -0.5f || (uint32_t)(sy + 0.5f) >= image.h) continue; \
- if (scaleMethod == _interpDownScaler) { \
+ if (scaleMethod == rasterDownScaler) { \
auto my = (int32_t)nearbyint(sy); \
miny = my - (int32_t)sampleSize; \
if (miny < 0) miny = 0; \
@@ -702,16 +536,134 @@ static bool _rasterRle(SwSurface* surface, SwRle* rle, const RenderRegion& bbox,
auto sx = (x) * itransform->e11 + itransform->e13 - 0.49f; \
if (sx <= -0.5f || (uint32_t)(sx + 0.5f) >= image.w) continue; \
+static bool _rasterScaledMaskedImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
+{
+ TVGERR("SW_ENGINE", "Not Supported Scaled Masked Image!");
+ return false;
+}
+
+static bool _rasterScaledMattedImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
+{
+ if (surface->channelSize == sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "Not supported grayscale scaled matted image!");
+ return false;
+ }
+
+ auto csize = surface->compositor->image.channelSize;
+ auto alpha = surface->alpha(surface->compositor->method);
+ auto scaleMethod = _scaleMethod(image);
+ auto sampleSize = _sampleSize(image.scale);
+
+ #pragma omp parallel for
+ for (auto y = bbox.yMin; y < bbox.yMax; ++y) {
+ int32_t miny = 0, maxy = 0;
+ SCALED_IMAGE_RANGE_Y(y)
+ auto dst = surface->buf32 + y * surface->stride + bbox.xMin;
+ auto cmp = surface->compositor->image.buf8 + (y * surface->compositor->image.stride + bbox.xMin) * csize;
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst, cmp += csize) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ auto tmp = ALPHA_BLEND(src, opacity == 255 ? alpha(cmp) : MULTIPLY(opacity, alpha(cmp)));
+ *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
+ }
+ }
+ return true;
+}
+
+static bool _rasterScaledBlendingImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
+{
+ if (surface->channelSize == sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "Not supported grayscale scaled blending image!");
+ return false;
+ }
+
+ auto scaleMethod = _scaleMethod(image);
+ auto sampleSize = _sampleSize(image.scale);
+
+ #pragma omp parallel for
+ for (auto y = bbox.yMin; y < bbox.yMax; ++y) {
+ int32_t miny = 0, maxy = 0;
+ SCALED_IMAGE_RANGE_Y(y)
+ auto dst = surface->buf32 + y * surface->stride + bbox.xMin;
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ *dst = INTERPOLATE(surface->blender(surface, UNPREMULTIPLY(src), *dst), *dst, MULTIPLY(opacity, A(src)));
+ }
+ }
+ return true;
+}
+
+static bool _rasterScaledImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
+{
+ auto scaleMethod = _scaleMethod(image);
+ auto sampleSize = _sampleSize(image.scale);
+
+ // 32bits channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ #pragma omp parallel for
+ for (auto y = bbox.yMin; y < bbox.yMax; ++y) {
+ int32_t miny = 0, maxy = 0;
+ SCALED_IMAGE_RANGE_Y(y)
+ auto dst = surface->buf32 + y * surface->stride + bbox.xMin;
+ if (image.alphaIgnored) {
+ if (opacity == 255) {
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ *dst = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ }
+ } else {
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ *dst = INTERPOLATE(src, *dst, opacity);
+ }
+ }
+ } else {
+ if (opacity == 255) {
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ *dst = src + ALPHA_BLEND(*dst, IA(src));
+ }
+ } else {
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ src = ALPHA_BLEND(src, opacity);
+ *dst = src + ALPHA_BLEND(*dst, IA(src));
+ }
+ }
+ }
+ }
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ #pragma omp parallel for
+ for (auto y = bbox.yMin; y < bbox.yMax; ++y) {
+ int32_t miny = 0, maxy = 0;
+ SCALED_IMAGE_RANGE_Y(y)
+ auto dst = surface->buf8 + y * surface->stride + bbox.xMin;
+ for (auto x = bbox.xMin; x < bbox.xMax; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ *dst = MULTIPLY(A(src), opacity);
+ }
+ }
+ }
+ return true;
+}
+
static bool _rasterScaledMaskedRleImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
{
TVGERR("SW_ENGINE", "Not Supported Scaled Masked(%d) Rle Image", (int)surface->compositor->method);
return false;
}
-
static bool _rasterScaledMattedRleImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
{
- TVGLOG("SW_ENGINE", "Scaled Matted(%d) Rle Image", (int)surface->compositor->method);
+ if (surface->channelSize == sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "Not supported grayscale scaled matted rle image!");
+ return false;
+ }
auto csize = surface->compositor->image.channelSize;
auto alpha = surface->alpha(surface->compositor->method);
@@ -734,9 +686,13 @@ static bool _rasterScaledMattedRleImage(SwSurface* surface, const SwImage& image
return true;
}
-
static bool _rasterScaledBlendingRleImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
{
+ if (surface->channelSize == sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "Not supported grayscale scaled blending rle image!");
+ return false;
+ }
+
auto scaleMethod = _scaleMethod(image);
auto sampleSize = _sampleSize(image.scale);
int32_t miny = 0, maxy = 0;
@@ -749,40 +705,65 @@ static bool _rasterScaledBlendingRleImage(SwSurface* surface, const SwImage& ima
for (uint32_t x = static_cast<uint32_t>(span->x); x < static_cast<uint32_t>(span->x) + span->len; ++x, ++dst) {
SCALED_IMAGE_RANGE_X
auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- *dst = INTERPOLATE(surface->blender(rasterUnpremultiply(src), *dst), *dst, A(src));
+ *dst = INTERPOLATE(surface->blender(surface, UNPREMULTIPLY(src), *dst), *dst, A(src));
}
} else {
for (uint32_t x = static_cast<uint32_t>(span->x); x < static_cast<uint32_t>(span->x) + span->len; ++x, ++dst) {
SCALED_IMAGE_RANGE_X
auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- *dst = INTERPOLATE(surface->blender(rasterUnpremultiply(src), *dst), *dst, MULTIPLY(alpha, A(src)));
+ *dst = INTERPOLATE(surface->blender(surface, UNPREMULTIPLY(src), *dst), *dst, MULTIPLY(alpha, A(src)));
}
}
}
return true;
}
-
static bool _rasterScaledRleImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
{
auto scaleMethod = _scaleMethod(image);
auto sampleSize = _sampleSize(image.scale);
int32_t miny = 0, maxy = 0;
- ARRAY_FOREACH(span, image.rle->spans) {
- SCALED_IMAGE_RANGE_Y(span->y)
- auto dst = &surface->buf32[span->y * surface->stride + span->x];
- auto alpha = MULTIPLY(span->coverage, opacity);
- for (uint32_t x = static_cast<uint32_t>(span->x); x < static_cast<uint32_t>(span->x) + span->len; ++x, ++dst) {
- SCALED_IMAGE_RANGE_X
- auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- if (alpha < 255) src = ALPHA_BLEND(src, alpha);
- *dst = src + ALPHA_BLEND(*dst, IA(src));
+ if (surface->channelSize == sizeof(uint32_t)) {
+ ARRAY_FOREACH(span, image.rle->spans) {
+ SCALED_IMAGE_RANGE_Y(span->y)
+ auto dst = &surface->buf32[span->y * surface->stride + span->x];
+ auto alpha = MULTIPLY(span->coverage, opacity);
+ for (uint32_t x = static_cast<uint32_t>(span->x); x < static_cast<uint32_t>(span->x) + span->len; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ if (alpha < 255) src = ALPHA_BLEND(src, alpha);
+ *dst = src + ALPHA_BLEND(*dst, IA(src));
+ }
+ }
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ ARRAY_FOREACH(span, image.rle->spans) {
+ SCALED_IMAGE_RANGE_Y(span->y)
+ auto dst = &surface->buf8[span->y * surface->stride + span->x];
+ auto alpha = MULTIPLY(span->coverage, opacity);
+ for (uint32_t x = static_cast<uint32_t>(span->x); x < static_cast<uint32_t>(span->x) + span->len; ++x, ++dst) {
+ SCALED_IMAGE_RANGE_X
+ auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
+ *dst = MULTIPLY(A(src), alpha);
+ }
}
}
return true;
}
+template<bool Rle>
+static bool _rasterScaledImageDispatch(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity)
+{
+ Matrix itransform;
+ if (!inverse(&transform, &itransform)) return true;
+
+ if (_compositing(surface)) {
+ if (_matting(surface)) return (Rle ? _rasterScaledMattedRleImage : _rasterScaledMattedImage)(surface, image, &itransform, bbox, opacity);
+ return (Rle ? _rasterScaledMaskedRleImage : _rasterScaledMaskedImage)(surface, image, &itransform, bbox, opacity);
+ }
+ if (_blending(surface)) return (Rle ? _rasterScaledBlendingRleImage : _rasterScaledBlendingImage)(surface, image, &itransform, bbox, opacity);
+ return (Rle ? _rasterScaledRleImage : _rasterScaledImage)(surface, image, &itransform, bbox, opacity);
+}
/************************************************************************/
/* RLE Direct Image */
@@ -790,8 +771,6 @@ static bool _rasterScaledRleImage(SwSurface* surface, const SwImage& image, cons
static bool _rasterDirectMattedRleImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, uint8_t opacity)
{
- TVGLOG("SW_ENGINE", "Direct Matted(%d) Rle Image", (int)surface->compositor->method);
-
auto csize = surface->compositor->image.channelSize;
auto cbuffer = surface->compositor->image.buf8;
auto alpha = surface->alpha(surface->compositor->method);
@@ -819,7 +798,6 @@ static bool _rasterDirectMattedRleImage(SwSurface* surface, const SwImage& image
return true;
}
-
static bool _rasterDirectBlendingRleImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, uint8_t opacity)
{
const SwSpan* end;
@@ -832,18 +810,17 @@ static bool _rasterDirectBlendingRleImage(SwSurface* surface, const SwImage& ima
auto alpha = MULTIPLY(span->coverage, opacity);
if (alpha == 255) {
for (auto x = 0; x < len; ++x, ++dst, ++src) {
- *dst = surface->blender(rasterUnpremultiply(*src), *dst);
+ *dst = surface->blender(surface, UNPREMULTIPLY(*src), *dst);
}
} else {
for (auto x = 0; x < len; ++x, ++dst, ++src) {
- *dst = INTERPOLATE(surface->blender(rasterUnpremultiply(*src), *dst), *dst, MULTIPLY(alpha, A(*src)));
+ *dst = INTERPOLATE(surface->blender(surface, UNPREMULTIPLY(*src), *dst), *dst, MULTIPLY(alpha, A(*src)));
}
}
}
return true;
}
-
static bool _rasterDirectRleImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, uint8_t opacity)
{
const SwSpan* end;
@@ -854,7 +831,7 @@ static bool _rasterDirectRleImage(SwSurface* surface, const SwImage& image, cons
auto dst = &surface->buf32[span->y * surface->stride + x];
auto img = image.buf32 + (span->y + image.oy) * image.stride + (x + image.ox);
auto alpha = MULTIPLY(span->coverage, opacity);
- rasterTranslucentPixel32(dst, img, len, alpha);
+ rasterTranslucentPixels(dst, img, len, alpha);
}
return true;
}
@@ -866,188 +843,87 @@ static bool _rasterDirectMaskedRleImage(SwSurface* surface, const SwImage& image
return false;
}
-
/************************************************************************/
-/*Scaled Image */
+/* Direct Image */
/************************************************************************/
-static bool _rasterScaledMaskedImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
+static bool _rasterDirectMaskedImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
{
- TVGERR("SW_ENGINE", "Not Supported Scaled Masked Image!");
+ TVGERR("SW_ENGINE", "Not Supported: Direct Masked Image");
return false;
}
-
-static bool _rasterScaledMattedImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
+static bool _rasterDirectMattedGrayscale(SwSurface* surface, const SwImage& image, SwCompositor* compositor, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
{
- if (surface->channelSize == sizeof(uint8_t)) {
- TVGERR("SW_ENGINE", "Not supported grayscale scaled matted image!");
- return false;
+ auto csize = compositor->image.channelSize;
+ auto alpha = surface->alpha(compositor->method);
+ auto sbuffer = image.buf32 + (bbox.yMin + image.oy) * image.stride + (bbox.xMin + image.ox);
+ auto cbuffer = compositor->image.buf8 + (bbox.yMin * compositor->image.stride + bbox.xMin) * csize; // compositor buffer
+ auto dbuffer = surface->buf8 + (bbox.yMin * surface->stride) + bbox.xMin;
+
+ for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
+ auto cmp = cbuffer;
+ auto src = sbuffer;
+ if (opacity == 255) {
+ for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
+ auto tmp = MULTIPLY(A(*src), alpha(cmp));
+ *dst = tmp + MULTIPLY(*dst, 255 - tmp);
+ }
+ } else {
+ for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
+ auto tmp = MULTIPLY(A(*src), MULTIPLY(opacity, alpha(cmp)));
+ *dst = tmp + MULTIPLY(*dst, 255 - tmp);
+ }
+ }
+ cbuffer += compositor->image.stride * csize;
}
+ return true;
+}
+
+static bool _rasterDirectMattedImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
+{
+ if (surface->channelSize == sizeof(uint8_t)) return _rasterDirectMattedGrayscale(surface, image, surface->compositor, bbox, w, h, opacity);
- auto dbuffer = surface->buf32 + (bbox.min.y * surface->stride + bbox.min.x);
auto csize = surface->compositor->image.channelSize;
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * surface->compositor->image.stride + bbox.min.x) * csize;
auto alpha = surface->alpha(surface->compositor->method);
+ auto sbuffer = image.buf32 + (bbox.yMin + image.oy) * image.stride + (bbox.xMin + image.ox);
+ auto cbuffer = surface->compositor->image.buf8 + (bbox.yMin * surface->compositor->image.stride + bbox.xMin) * csize; // compositor buffer
+ auto dbuffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
- TVGLOG("SW_ENGINE", "Scaled Matted(%d) Image [Region: %d %d %d %d]", (int)surface->compositor->method, bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y);
-
- auto scaleMethod = _scaleMethod(image);
- auto sampleSize = _sampleSize(image.scale);
- int32_t miny = 0, maxy = 0;
-
- for (auto y = bbox.min.y; y < bbox.max.y; ++y) {
- SCALED_IMAGE_RANGE_Y(y)
- auto dst = dbuffer;
+ for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
auto cmp = cbuffer;
- for (auto x = bbox.min.x; x < bbox.max.x; ++x, ++dst, cmp += csize) {
- SCALED_IMAGE_RANGE_X
- auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- auto tmp = ALPHA_BLEND(src, opacity == 255 ? alpha(cmp) : MULTIPLY(opacity, alpha(cmp)));
- *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
- }
- dbuffer += surface->stride;
- cbuffer += surface->compositor->image.stride * csize;
- }
- return true;
-}
-
-
-static bool _rasterScaledBlendingImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
-{
- if (surface->channelSize == sizeof(uint8_t)) {
- TVGERR("SW_ENGINE", "Not supported grayscale scaled blending image!");
- return false;
- }
-
- auto dbuffer = surface->buf32 + (bbox.min.y * surface->stride + bbox.min.x);
- auto scaleMethod = _scaleMethod(image);
- auto sampleSize = _sampleSize(image.scale);
- int32_t miny = 0, maxy = 0;
-
- for (auto y = bbox.min.y; y < bbox.max.y; ++y, dbuffer += surface->stride) {
- SCALED_IMAGE_RANGE_Y(y)
- auto dst = dbuffer;
- for (auto x = bbox.min.x; x < bbox.max.x; ++x, ++dst) {
- SCALED_IMAGE_RANGE_X
- auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- *dst = INTERPOLATE(surface->blender(rasterUnpremultiply(src), *dst), *dst, MULTIPLY(opacity, A(src)));
- }
- }
- return true;
-}
-
-
-static bool _rasterScaledImage(SwSurface* surface, const SwImage& image, const Matrix* itransform, const RenderRegion& bbox, uint8_t opacity)
-{
- auto scaleMethod = _scaleMethod(image);
- auto sampleSize = _sampleSize(image.scale);
- int32_t miny = 0, maxy = 0;
-
- //32bits channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride + bbox.min.x);
- for (auto y = bbox.min.y; y < bbox.max.y; ++y, buffer += surface->stride) {
- SCALED_IMAGE_RANGE_Y(y)
- auto dst = buffer;
- for (auto x = bbox.min.x; x < bbox.max.x; ++x, ++dst) {
- SCALED_IMAGE_RANGE_X
- auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- if (opacity < 255) src = ALPHA_BLEND(src, opacity);
- *dst = src + ALPHA_BLEND(*dst, IA(src));
- }
- }
- } else if (surface->channelSize == sizeof(uint8_t)) {
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride + bbox.min.x);
- for (auto y = bbox.min.y; y < bbox.max.y; ++y, buffer += surface->stride) {
- SCALED_IMAGE_RANGE_Y(y)
- auto dst = buffer;
- for (auto x = bbox.min.x; x < bbox.max.x; ++x, ++dst) {
- SCALED_IMAGE_RANGE_X
- auto src = scaleMethod(image.buf32, image.stride, image.w, image.h, sx, sy, miny, maxy, sampleSize);
- *dst = MULTIPLY(A(src), opacity);
- }
- }
- }
- return true;
-}
-
-
-/************************************************************************/
-/* Direct Image */
-/************************************************************************/
-
-static bool _rasterDirectMaskedImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
-{
- TVGERR("SW_ENGINE", "Not Supported: Direct Masked Image");
- return false;
-}
-
-static bool _rasterDirectMattedImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
-{
- auto csize = surface->compositor->image.channelSize;
- auto alpha = surface->alpha(surface->compositor->method);
- auto sbuffer = image.buf32 + (bbox.min.y + image.oy) * image.stride + (bbox.min.x + image.ox);
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * surface->compositor->image.stride + bbox.min.x) * csize; //compositor buffer
-
- TVGLOG("SW_ENGINE", "Direct Matted(%d) Image [Region: %u %u %u %u]", (int)surface->compositor->method, bbox.x(), bbox.y(), bbox.w(), bbox.h());
-
- //32 bits
- if (surface->channelSize == sizeof(uint32_t)) {
- auto dbuffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
- for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
- auto cmp = cbuffer;
- auto src = sbuffer;
- if (opacity == 255) {
- for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
- auto tmp = ALPHA_BLEND(*src, alpha(cmp));
- *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
- }
- } else {
- for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
- auto tmp = ALPHA_BLEND(*src, MULTIPLY(opacity, alpha(cmp)));
- *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
- }
+ auto src = sbuffer;
+ if (opacity == 255) {
+ for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
+ auto tmp = ALPHA_BLEND(*src, alpha(cmp));
+ *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
}
- cbuffer += surface->compositor->image.stride * csize;
- }
- //8 bits
- } else if (surface->channelSize == sizeof(uint8_t)) {
- auto dbuffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
- for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
- auto cmp = cbuffer;
- auto src = sbuffer;
- if (opacity == 255) {
- for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
- auto tmp = MULTIPLY(A(*src), alpha(cmp));
- *dst = tmp + MULTIPLY(*dst, 255 - tmp);
- }
- } else {
- for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
- auto tmp = MULTIPLY(A(*src), MULTIPLY(opacity, alpha(cmp)));
- *dst = tmp + MULTIPLY(*dst, 255 - tmp);
- }
+ } else {
+ for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
+ auto tmp = ALPHA_BLEND(*src, MULTIPLY(opacity, alpha(cmp)));
+ *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
}
- cbuffer += surface->compositor->image.stride * csize;
}
+ cbuffer += surface->compositor->image.stride * csize;
}
return true;
}
static bool _rasterDirectImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
{
- auto sbuffer = image.buf32 + (bbox.min.y + image.oy) * image.stride + (bbox.min.x + image.ox);
+ auto sbuffer = image.buf32 + (bbox.yMin + image.oy) * image.stride + (bbox.xMin + image.ox);
//32bits channels
if (surface->channelSize == sizeof(uint32_t)) {
- auto dbuffer = &surface->buf32[bbox.min.y * surface->stride + bbox.min.x];
+ auto dbuffer = &surface->buf32[bbox.yMin * surface->stride + bbox.xMin];
for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
- rasterTranslucentPixel32(dbuffer, sbuffer, w, opacity);
+ if (image.alphaIgnored) rasterSolidPixels(dbuffer, sbuffer, w, opacity);
+ else rasterTranslucentPixels(dbuffer, sbuffer, w, opacity);
}
//8bits grayscale
//32 -> 8 direct converting seems an avoidable stage. maybe draw to a masking image after an intermediate scene. Can get rid of this?
} else if (surface->channelSize == sizeof(uint8_t)) {
- auto dbuffer = &surface->buf8[bbox.min.y * surface->stride + bbox.min.x];
+ auto dbuffer = &surface->buf8[bbox.yMin * surface->stride + bbox.xMin];
for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
auto src = sbuffer;
if (opacity == 255) {
@@ -1066,27 +942,25 @@ static bool _rasterDirectImage(SwSurface* surface, const SwImage& image, const R
static bool _rasterDirectMattedBlendingImage(SwSurface* surface, const SwImage& image, SwCompositor* compositor, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
{
- if (surface->channelSize == sizeof(uint8_t)) {
- TVGERR("SW_ENGINE", "Not supported grayscale image!");
- return false;
- }
+ // blending doesn't work for grayscale
+ if (surface->channelSize == sizeof(uint8_t)) return _rasterDirectMattedGrayscale(surface, image, compositor, bbox, w, h, opacity);
auto csize = compositor->image.channelSize;
auto alpha = surface->alpha(compositor->method);
- auto sbuffer = image.buf32 + (bbox.min.y + image.oy) * image.stride + (bbox.min.x + image.ox);
- auto cbuffer = compositor->image.buf8 + (bbox.min.y * compositor->image.stride + bbox.min.x) * csize; // compositor buffer
- auto dbuffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
+ auto sbuffer = image.buf32 + (bbox.yMin + image.oy) * image.stride + (bbox.xMin + image.ox);
+ auto cbuffer = compositor->image.buf8 + (bbox.yMin * compositor->image.stride + bbox.xMin) * csize; // compositor buffer
+ auto dbuffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
auto cmp = cbuffer;
auto src = sbuffer;
if (opacity == 255) {
for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
- *dst = INTERPOLATE(surface->blender(*src, *dst), *dst, MULTIPLY(A(*src), alpha(cmp)));
+ *dst = INTERPOLATE(surface->blender(surface, *src, *dst), *dst, MULTIPLY(A(*src), alpha(cmp)));
}
} else {
for (auto dst = dbuffer; dst < dbuffer + w; ++dst, ++src, cmp += csize) {
- *dst = INTERPOLATE(surface->blender(*src, *dst), *dst, MULTIPLY(MULTIPLY(A(*src), alpha(cmp)), opacity));
+ *dst = INTERPOLATE(surface->blender(surface, *src, *dst), *dst, MULTIPLY(MULTIPLY(A(*src), alpha(cmp)), opacity));
}
}
cbuffer += compositor->image.stride * csize;
@@ -1096,10 +970,8 @@ static bool _rasterDirectMattedBlendingImage(SwSurface* surface, const SwImage&
static bool _rasterDirectBlendingImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int32_t w, int32_t h, uint8_t opacity)
{
- if (surface->channelSize == sizeof(uint8_t)) {
- TVGERR("SW_ENGINE", "Not supported grayscale image!");
- return false;
- }
+ // blending doesn't work for grayscale
+ if (surface->channelSize == sizeof(uint8_t)) return _rasterDirectImage(surface, image, bbox, w, h, opacity);
// fast-track: mix the blending & masking composition
auto injecting = [](const SwCompositor* cmp) {
@@ -1108,18 +980,18 @@ static bool _rasterDirectBlendingImage(SwSurface* surface, const SwImage& image,
if (injecting(surface->compositor)) return _rasterDirectMattedBlendingImage(surface, image, surface->compositor->recoverCmp, bbox, w, h, opacity);
- auto dbuffer = &surface->buf32[bbox.min.y * surface->stride + bbox.min.x];
- auto sbuffer = image.buf32 + (bbox.min.y + image.oy) * image.stride + (bbox.min.x + image.ox);
+ auto dbuffer = &surface->buf32[bbox.yMin * surface->stride + bbox.xMin];
+ auto sbuffer = image.buf32 + (bbox.yMin + image.oy) * image.stride + (bbox.xMin + image.ox);
for (auto y = 0; y < h; ++y, dbuffer += surface->stride, sbuffer += image.stride) {
auto src = sbuffer;
if (opacity == 255) {
for (auto dst = dbuffer; dst < dbuffer + w; dst++, src++) {
- *dst = INTERPOLATE(surface->blender(rasterUnpremultiply(*src), *dst), *dst, A(*src));
+ *dst = INTERPOLATE(surface->blender(surface, UNPREMULTIPLY(*src), *dst), *dst, A(*src));
}
} else {
for (auto dst = dbuffer; dst < dbuffer + w; dst++, src++) {
- *dst = INTERPOLATE(surface->blender(rasterUnpremultiply(*src), *dst), *dst, MULTIPLY(opacity, A(*src)));
+ *dst = INTERPOLATE(surface->blender(surface, UNPREMULTIPLY(*src), *dst), *dst, MULTIPLY(opacity, A(*src)));
}
}
}
@@ -1131,167 +1003,130 @@ static bool _rasterDirectBlendingImage(SwSurface* surface, const SwImage& image,
/* Rect Gradient */
/************************************************************************/
-template<typename fillMethod>
static bool _rasterCompositeGradientMaskedRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill, SwMask maskOp)
{
auto cstride = surface->compositor->image.stride;
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * cstride + bbox.min.x);
+ auto cbuffer = surface->compositor->image.buf8 + (bbox.yMin * cstride + bbox.xMin);
for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, cbuffer, bbox.min.y + y, bbox.min.x, bbox.w(), maskOp, 255);
- cbuffer += surface->stride;
+ fillRaster(fill, cbuffer, bbox.yMin + y, bbox.xMin, bbox.w(), maskOp, 255);
+ cbuffer += cstride;
}
return _compositeMaskImage(surface, surface->compositor->image, surface->compositor->bbox);
}
-
-template<typename fillMethod>
static bool _rasterDirectGradientMaskedRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill, SwMask maskOp)
{
auto cstride = surface->compositor->image.stride;
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * cstride + bbox.min.x);
- auto dbuffer = surface->buf8 + (bbox.min.y * surface->stride + bbox.min.x);
+ auto cbuffer = surface->compositor->image.buf8 + (bbox.yMin * cstride + bbox.xMin);
+ auto dbuffer = surface->buf8 + (bbox.yMin * surface->stride + bbox.xMin);
for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, dbuffer, bbox.min.y + y, bbox.min.x, bbox.w(), cbuffer, maskOp, 255);
+ fillRaster(fill, dbuffer, bbox.yMin + y, bbox.xMin, bbox.w(), cbuffer, maskOp, 255);
cbuffer += cstride;
dbuffer += surface->stride;
}
return true;
}
-
-template<typename fillMethod>
static bool _rasterGradientMaskedRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
{
auto method = surface->compositor->method;
-
- TVGLOG("SW_ENGINE", "Masked(%d) Gradient [Region: %d %d %d %d]", (int)method, bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y);
-
auto maskOp = _getMaskOp(method);
- if (_direct(method)) return _rasterDirectGradientMaskedRect<fillMethod>(surface, bbox, fill, maskOp);
- else return _rasterCompositeGradientMaskedRect<fillMethod>(surface, bbox, fill, maskOp);
+ if (_direct(method)) return _rasterDirectGradientMaskedRect(surface, bbox, fill, maskOp);
+ else return _rasterCompositeGradientMaskedRect(surface, bbox, fill, maskOp);
return false;
}
-
-template<typename fillMethod>
static bool _rasterGradientMattedRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
{
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
+ if (surface->channelSize == sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "Not supported grayscale gradient!");
+ return false;
+ }
+
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
auto csize = surface->compositor->image.channelSize;
- auto cbuffer = surface->compositor->image.buf8 + (bbox.min.y * surface->compositor->image.stride + bbox.min.x) * csize;
+ auto cbuffer = surface->compositor->image.buf8 + (bbox.yMin * surface->compositor->image.stride + bbox.xMin) * csize;
+ auto cstride = surface->compositor->image.stride * csize;
auto alpha = surface->alpha(surface->compositor->method);
- TVGLOG("SW_ENGINE", "Matted(%d) Gradient [Region: %u %u %u %u]", (int)surface->compositor->method, bbox.x(), bbox.y(), bbox.w(), bbox.h());
-
for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer, bbox.min.y + y, bbox.min.x, bbox.w(), cbuffer, alpha, csize, 255);
+ fillRaster(fill, buffer, bbox.yMin + y, bbox.xMin, bbox.w(), cbuffer, alpha, csize, 255);
buffer += surface->stride;
- cbuffer += surface->stride * csize;
+ cbuffer += cstride;
}
return true;
}
+static bool _rasterGradientRect8(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
+{
+ auto buffer = surface->buf8 + (bbox.yMin * surface->stride) + bbox.xMin;
+
+ for (uint32_t y = 0; y < bbox.h(); ++y) {
+ fillRaster(fill, buffer, bbox.yMin + y, bbox.xMin, bbox.w(), _opMaskAdd, 255);
+ buffer += surface->stride;
+ }
+ return true;
+}
-template<typename fillMethod>
static bool _rasterBlendingGradientRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
{
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
if (fill->translucent) {
for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer + y * surface->stride, bbox.min.y + y, bbox.min.x, bbox.w(), opBlendPreNormal, surface->blender, 255);
+ fillRaster(surface, fill, buffer + y * surface->stride, bbox.yMin + y, bbox.xMin, bbox.w(), opBlendPreNormal, surface->blender, 255);
}
} else {
for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer + y * surface->stride, bbox.min.y + y, bbox.min.x, bbox.w(), opBlendSrcOver, surface->blender, 255);
+ fillRaster(surface, fill, buffer + y * surface->stride, bbox.yMin + y, bbox.xMin, bbox.w(), opBlendSrcOver, surface->blender, 255);
}
}
return true;
}
-template<typename fillMethod>
static bool _rasterTranslucentGradientRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
{
- //32 bits
- if (surface->channelSize == sizeof(uint32_t)) {
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
- for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer, bbox.min.y + y, bbox.min.x, bbox.w(), opBlendPreNormal, 255);
- buffer += surface->stride;
- }
- //8 bits
- } else if (surface->channelSize == sizeof(uint8_t)) {
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
- for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer, bbox.min.y + y, bbox.min.x, bbox.w(), _opMaskAdd, 255);
- buffer += surface->stride;
- }
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
+
+ for (uint32_t y = 0; y < bbox.h(); ++y) {
+ fillRaster(fill, buffer, bbox.yMin + y, bbox.xMin, bbox.w(), opBlendPreNormal, 255);
+ buffer += surface->stride;
}
return true;
}
-
-template<typename fillMethod>
static bool _rasterSolidGradientRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
{
- //32 bits
- if (surface->channelSize == sizeof(uint32_t)) {
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
- for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer, bbox.min.y + y, bbox.min.x, bbox.w(), opBlendSrcOver, 255);
- buffer += surface->stride;
- }
- //8 bits
- } else if (surface->channelSize == sizeof(uint8_t)) {
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
- for (uint32_t y = 0; y < bbox.h(); ++y) {
- fillMethod()(fill, buffer, bbox.min.y + y, bbox.min.x, bbox.w(), _opMaskNone, 255);
- buffer += surface->stride;
- }
- }
- return true;
-}
-
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
-static bool _rasterLinearGradientRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
-{
- if (_compositing(surface)) {
- if (_matting(surface)) return _rasterGradientMattedRect<FillLinear>(surface, bbox, fill);
- else return _rasterGradientMaskedRect<FillLinear>(surface, bbox, fill);
- } else if (_blending(surface)) {
- return _rasterBlendingGradientRect<FillLinear>(surface, bbox, fill);
- } else {
- if (fill->translucent) return _rasterTranslucentGradientRect<FillLinear>(surface, bbox, fill);
- else _rasterSolidGradientRect<FillLinear>(surface, bbox, fill);
+ for (uint32_t y = 0; y < bbox.h(); ++y) {
+ fillRaster(fill, buffer, bbox.yMin + y, bbox.xMin, bbox.w(), opBlendSrcOver, 255);
+ buffer += surface->stride;
}
- return false;
+ return true;
}
-
-static bool _rasterRadialGradientRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
+static bool _rasterGradientRect(SwSurface* surface, const RenderRegion& bbox, const SwFill* fill)
{
if (_compositing(surface)) {
- if (_matting(surface)) return _rasterGradientMattedRect<FillRadial>(surface, bbox, fill);
- else return _rasterGradientMaskedRect<FillRadial>(surface, bbox, fill);
- } else if (_blending(surface)) {
- return _rasterBlendingGradientRect<FillRadial>(surface, bbox, fill);
- } else {
- if (fill->translucent) return _rasterTranslucentGradientRect<FillRadial>(surface, bbox, fill);
- else _rasterSolidGradientRect<FillRadial>(surface, bbox, fill);
+ if (_matting(surface)) return _rasterGradientMattedRect(surface, bbox, fill);
+ return _rasterGradientMaskedRect(surface, bbox, fill);
}
- return false;
+ //Rasterize 8-bit masks before dispatching to the 32-bit color paths.
+ if (surface->channelSize == sizeof(uint8_t)) return _rasterGradientRect8(surface, bbox, fill);
+ if (_blending(surface)) return _rasterBlendingGradientRect(surface, bbox, fill);
+ if (fill->translucent) return _rasterTranslucentGradientRect(surface, bbox, fill);
+ return _rasterSolidGradientRect(surface, bbox, fill);
}
-
/************************************************************************/
/* Rle Gradient */
/************************************************************************/
-template<typename fillMethod>
static bool _rasterCompositeGradientMaskedRle(SwSurface* surface, const SwRle* rle, const SwFill* fill, SwMask maskOp)
{
auto span = rle->data();
@@ -1300,13 +1135,11 @@ static bool _rasterCompositeGradientMaskedRle(SwSurface* surface, const SwRle* r
for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
auto cmp = &cbuffer[span->y * cstride + span->x];
- fillMethod()(fill, cmp, span->y, span->x, span->len, maskOp, span->coverage);
+ fillRaster(fill, cmp, span->y, span->x, span->len, maskOp, span->coverage);
}
return _compositeMaskImage(surface, surface->compositor->image, surface->compositor->bbox);
}
-
-template<typename fillMethod>
static bool _rasterDirectGradientMaskedRle(SwSurface* surface, const SwRle* rle, const SwFill* fill, SwMask maskOp)
{
auto span = rle->data();
@@ -1317,31 +1150,27 @@ static bool _rasterDirectGradientMaskedRle(SwSurface* surface, const SwRle* rle,
for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
auto cmp = &cbuffer[span->y * cstride + span->x];
auto dst = &dbuffer[span->y * surface->stride + span->x];
- fillMethod()(fill, dst, span->y, span->x, span->len, cmp, maskOp, span->coverage);
+ fillRaster(fill, dst, span->y, span->x, span->len, cmp, maskOp, span->coverage);
}
return true;
}
-
-template<typename fillMethod>
static bool _rasterGradientMaskedRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
{
auto method = surface->compositor->method;
-
- TVGLOG("SW_ENGINE", "Masked(%d) Rle Linear Gradient", (int)method);
-
auto maskOp = _getMaskOp(method);
- if (_direct(method)) return _rasterDirectGradientMaskedRle<fillMethod>(surface, rle, fill, maskOp);
- else return _rasterCompositeGradientMaskedRle<fillMethod>(surface, rle, fill, maskOp);
+ if (_direct(method)) return _rasterDirectGradientMaskedRle(surface, rle, fill, maskOp);
+ else return _rasterCompositeGradientMaskedRle(surface, rle, fill, maskOp);
return false;
}
-
-template<typename fillMethod>
static bool _rasterGradientMattedRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
{
- TVGLOG("SW_ENGINE", "Matted(%d) Rle Linear Gradient", (int)surface->compositor->method);
+ if (surface->channelSize == sizeof(uint8_t)) {
+ TVGERR("SW_ENGINE", "Not supported grayscale gradient!");
+ return false;
+ }
auto span = rle->data();
auto csize = surface->compositor->image.channelSize;
@@ -1351,148 +1180,77 @@ static bool _rasterGradientMattedRle(SwSurface* surface, const SwRle* rle, const
for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
auto dst = &surface->buf32[span->y * surface->stride + span->x];
auto cmp = &cbuffer[(span->y * surface->compositor->image.stride + span->x) * csize];
- fillMethod()(fill, dst, span->y, span->x, span->len, cmp, alpha, csize, span->coverage);
+ fillRaster(fill, dst, span->y, span->x, span->len, cmp, alpha, csize, span->coverage);
}
return true;
}
+static bool _rasterGradientRle8(SwSurface* surface, const SwRle* rle, const SwFill* fill)
+{
+ auto span = rle->data();
+
+ for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
+ auto dst = &surface->buf8[span->y * surface->stride + span->x];
+ fillRaster(fill, dst, span->y, span->x, span->len, _opMaskAdd, span->coverage);
+ }
+ return true;
+}
-template<typename fillMethod>
static bool _rasterBlendingGradientRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
{
auto span = rle->data();
for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
auto dst = &surface->buf32[span->y * surface->stride + span->x];
- fillMethod()(fill, dst, span->y, span->x, span->len, opBlendPreNormal, surface->blender, span->coverage);
+ fillRaster(surface, fill, dst, span->y, span->x, span->len, opBlendPreNormal, surface->blender, span->coverage);
}
return true;
}
-
-template<typename fillMethod>
static bool _rasterTranslucentGradientRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
{
auto span = rle->data();
- //32 bits
- if (surface->channelSize == sizeof(uint32_t)) {
- for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
- auto dst = &surface->buf32[span->y * surface->stride + span->x];
- if (span->coverage == 255) fillMethod()(fill, dst, span->y, span->x, span->len, opBlendPreNormal, 255);
- else fillMethod()(fill, dst, span->y, span->x, span->len, opBlendNormal, span->coverage);
- }
- //8 bits
- } else if (surface->channelSize == sizeof(uint8_t)) {
- for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
- auto dst = &surface->buf8[span->y * surface->stride + span->x];
- fillMethod()(fill, dst, span->y, span->x, span->len, _opMaskAdd, span->coverage);
- }
+ for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
+ auto dst = &surface->buf32[span->y * surface->stride + span->x];
+ if (span->coverage == 255) fillRaster(fill, dst, span->y, span->x, span->len, opBlendPreNormal, 255);
+ else fillRaster(fill, dst, span->y, span->x, span->len, opBlendNormal, span->coverage);
}
return true;
}
-
-template<typename fillMethod>
static bool _rasterSolidGradientRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
{
auto span = rle->data();
- //32 bits
- if (surface->channelSize == sizeof(uint32_t)) {
- for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
- auto dst = &surface->buf32[span->y * surface->stride + span->x];
- if (span->coverage == 255) fillMethod()(fill, dst, span->y, span->x, span->len, opBlendSrcOver, 255);
- else fillMethod()(fill, dst, span->y, span->x, span->len, opBlendInterp, span->coverage);
- }
- //8 bits
- } else if (surface->channelSize == sizeof(uint8_t)) {
- for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
- auto dst = &surface->buf8[span->y * surface->stride + span->x];
- if (span->coverage == 255) fillMethod()(fill, dst, span->y, span->x, span->len, _opMaskNone, 255);
- else fillMethod()(fill, dst, span->y, span->x, span->len, _opMaskAdd, span->coverage);
- }
+ for (uint32_t i = 0; i < rle->size(); ++i, ++span) {
+ auto dst = &surface->buf32[span->y * surface->stride + span->x];
+ if (span->coverage == 255) fillRaster(fill, dst, span->y, span->x, span->len, opBlendSrcOver, 255);
+ else fillRaster(fill, dst, span->y, span->x, span->len, opBlendInterp, span->coverage);
}
return true;
}
-
-static bool _rasterLinearGradientRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
+static bool _rasterGradientRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
{
if (_compositing(surface)) {
- if (_matting(surface)) return _rasterGradientMattedRle<FillLinear>(surface, rle, fill);
- else return _rasterGradientMaskedRle<FillLinear>(surface, rle, fill);
- } else if (_blending(surface)) {
- return _rasterBlendingGradientRle<FillLinear>(surface, rle, fill);
- } else {
- if (fill->translucent) return _rasterTranslucentGradientRle<FillLinear>(surface, rle, fill);
- else return _rasterSolidGradientRle<FillLinear>(surface, rle, fill);
+ if (_matting(surface)) return _rasterGradientMattedRle(surface, rle, fill);
+ return _rasterGradientMaskedRle(surface, rle, fill);
}
- return false;
+ //Rasterize 8-bit masks before dispatching to the 32-bit color paths.
+ if (surface->channelSize == sizeof(uint8_t)) return _rasterGradientRle8(surface, rle, fill);
+ if (_blending(surface)) return _rasterBlendingGradientRle(surface, rle, fill);
+ if (fill->translucent) return _rasterTranslucentGradientRle(surface, rle, fill);
+ return _rasterSolidGradientRle(surface, rle, fill);
}
-
-static bool _rasterRadialGradientRle(SwSurface* surface, const SwRle* rle, const SwFill* fill)
-{
- if (_compositing(surface)) {
- if (_matting(surface)) return _rasterGradientMattedRle<FillRadial>(surface, rle, fill);
- else return _rasterGradientMaskedRle<FillRadial>(surface, rle, fill);
- } else if (_blending(surface)) {
- return _rasterBlendingGradientRle<FillRadial>(surface, rle, fill);
- } else {
- if (fill->translucent) return _rasterTranslucentGradientRle<FillRadial>(surface, rle, fill);
- else return _rasterSolidGradientRle<FillRadial>(surface, rle, fill);
- }
- return false;
-}
-
-
/************************************************************************/
-/* External Class Implementation */
+/* External Interfaces */
/************************************************************************/
-void rasterTranslucentPixel32(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
-{
- //TODO: Support SIMD accelerations
- cRasterTranslucentPixels(dst, src, len, opacity);
-}
-
-
-void rasterPixel32(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
-{
- //TODO: Support SIMD accelerations
- cRasterPixels(dst, src, len, opacity);
-}
-
-
-void rasterGrayscale8(uint8_t *dst, uint8_t val, uint32_t offset, int32_t len)
-{
-#if defined(THORVG_AVX_VECTOR_SUPPORT)
- avxRasterGrayscale8(dst, val, offset, len);
-#elif defined(THORVG_NEON_VECTOR_SUPPORT)
- neonRasterGrayscale8(dst, val, offset, len);
-#else
- cRasterPixels(dst, val, offset, len);
-#endif
-}
-
-
-void rasterPixel32(uint32_t *dst, uint32_t val, uint32_t offset, int32_t len)
+Result rasterCompositor(SwSurface* surface)
{
-#if defined(THORVG_AVX_VECTOR_SUPPORT)
- avxRasterPixel32(dst, val, offset, len);
-#elif defined(THORVG_NEON_VECTOR_SUPPORT)
- neonRasterPixel32(dst, val, offset, len);
-#else
- cRasterPixels(dst, val, offset, len);
-#endif
-}
-
-
-bool rasterCompositor(SwSurface* surface)
-{
- //See MaskMethod, Alpha:1, InvAlpha:2, Luma:3, InvLuma:4
surface->alphas[0] = _alpha;
surface->alphas[1] = _ialpha;
@@ -1506,12 +1264,11 @@ bool rasterCompositor(SwSurface* surface)
surface->alphas[3] = _argbInvLuma;
} else {
TVGERR("SW_ENGINE", "Unsupported Colorspace(%d) is expected!", (int)surface->cs);
- return false;
+ return Result::NonSupport;
}
- return true;
+ return Result::Success;
}
-
bool rasterClear(SwSurface* surface, uint32_t x, uint32_t y, uint32_t w, uint32_t h)
{
if (!surface || !surface->buf32 || surface->stride == 0 || surface->w == 0 || surface->h == 0) return false;
@@ -1521,60 +1278,42 @@ bool rasterClear(SwSurface* surface, uint32_t x, uint32_t y, uint32_t w, uint32_
uint32_t val = 0;
//full clear
if (w == surface->stride) {
- rasterPixel32(surface->buf32, val, surface->stride * y, w * h);
+ rasterSolidPixel32(surface->buf32, val, surface->stride * y, w * h);
//partial clear
} else {
for (uint32_t i = 0; i < h; i++) {
- rasterPixel32(surface->buf32, val, (surface->stride * y + x) + (surface->stride * i), w);
+ rasterSolidPixel32(surface->buf32, val, (surface->stride * y + x) + (surface->stride * i), w);
}
}
//8 bits
} else if (surface->channelSize == sizeof(uint8_t)) {
//full clear
if (w == surface->stride) {
- rasterGrayscale8(surface->buf8, 0x00, surface->stride * y, w * h);
+ _rasterPixel8(surface->buf8, 0x00, surface->stride * y, w * h);
//partial clear
} else {
for (uint32_t i = 0; i < h; i++) {
- rasterGrayscale8(surface->buf8, 0x00, (surface->stride * y + x) + (surface->stride * i), w);
+ _rasterPixel8(surface->buf8, 0x00, (surface->stride * y + x) + (surface->stride * i), w);
}
}
}
return true;
}
-
-uint32_t rasterUnpremultiply(uint32_t data)
-{
- auto a = A(data);
- if (a == 255 || a == 0) return data;
-
- uint8_t r = std::min(C1(data) * 255u / a, 255u);
- uint8_t g = std::min(C2(data) * 255u / a, 255u);
- uint8_t b = std::min(C3(data) * 255u / a, 255u);
-
- return JOIN(a, r, g, b);
-}
-
-
-void rasterUnpremultiply(RenderSurface* surface)
+void rasterUnpremultiplySurface(RenderSurface* surface)
{
if (surface->channelSize != sizeof(uint32_t)) return;
TVGLOG("SW_ENGINE", "Unpremultiply [Size: %d x %d]", surface->w, surface->h);
- //OPTIMIZE_ME: +SIMD
- for (uint32_t y = 0; y < surface->h; y++) {
- auto buffer = surface->buf32 + surface->stride * y;
- for (uint32_t x = 0; x < surface->w; ++x) {
- buffer[x] = rasterUnpremultiply(buffer[x]);
- }
+ #pragma omp parallel for
+ for (int32_t y = 0; y < (int32_t)surface->h; y++) {
+ rasterUnpremultiply(surface->buf32 + surface->stride * uint32_t(y), surface->w);
}
surface->premultiplied = false;
}
-
-void rasterPremultiply(RenderSurface* surface)
+void rasterPremultiplySurface(RenderSurface* surface)
{
ScopedLock lock(surface->key);
if (surface->premultiplied || (surface->channelSize != sizeof(uint32_t))) return;
@@ -1582,80 +1321,39 @@ void rasterPremultiply(RenderSurface* surface)
TVGLOG("SW_ENGINE", "Premultiply [Size: %d x %d]", surface->w, surface->h);
- //OPTIMIZE_ME: +SIMD
- auto buffer = surface->buf32;
- for (uint32_t y = 0; y < surface->h; ++y, buffer += surface->stride) {
- auto dst = buffer;
- for (uint32_t x = 0; x < surface->w; ++x, ++dst) {
- auto c = *dst;
- if (A(c) == 255) continue;
- *dst = PREMULTIPLY(c, A(c));
- }
+ #pragma omp parallel for
+ for (int32_t y = 0; y < (int32_t)surface->h; ++y) {
+ rasterPremultiply(surface->buf32 + surface->stride * uint32_t(y), surface->w);
}
}
-
bool rasterScaledImage(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity)
{
- Matrix itransform;
-
- if (!inverse(&transform, &itransform)) return true;
-
- if (_compositing(surface)) {
- if (_matting(surface)) return _rasterScaledMattedImage(surface, image, &itransform, bbox, opacity);
- else return _rasterScaledMaskedImage(surface, image, &itransform, bbox, opacity);
- } else if (_blending(surface)) {
- return _rasterScaledBlendingImage(surface, image, &itransform, bbox, opacity);
- } else {
- return _rasterScaledImage(surface, image, &itransform, bbox, opacity);
- }
- return false;
+ return _rasterScaledImageDispatch<false>(surface, image, transform, bbox, opacity);
}
+bool rasterScaledRleImage(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity)
+{
+ return _rasterScaledImageDispatch<true>(surface, image, transform, bbox, opacity);
+}
bool rasterDirectImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, uint8_t opacity)
{
//calculate an actual drawing image size
- auto w = std::min(bbox.max.x - bbox.min.x, int32_t(image.w) - (bbox.min.x + image.ox));
- auto h = std::min(bbox.max.y - bbox.min.y, int32_t(image.h) - (bbox.min.y + image.oy));
+ auto w = std::min(bbox.xMax - bbox.xMin, int32_t(image.w) - (bbox.xMin + image.ox));
+ auto h = std::min(bbox.yMax - bbox.yMin, int32_t(image.h) - (bbox.yMin + image.oy));
if (_compositing(surface)) {
if (_matting(surface)) {
if (_blending(surface)) return _rasterDirectMattedBlendingImage(surface, image, surface->compositor, bbox, w, h, opacity);
- else return _rasterDirectMattedImage(surface, image, bbox, w, h, opacity);
- } else return _rasterDirectMaskedImage(surface, image, bbox, w, h, opacity);
- } else if (_blending(surface)) {
- return _rasterDirectBlendingImage(surface, image, bbox, w, h, opacity);
- } else {
- return _rasterDirectImage(surface, image, bbox, w, h, opacity);
- }
- return false;
-}
-
-
-bool rasterScaledRleImage(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity)
-{
- if (surface->channelSize == sizeof(uint8_t)) {
- TVGERR("SW_ENGINE", "Not supported scaled rle image!");
- return false;
- }
-
- Matrix itransform;
-
- if (!inverse(&transform, &itransform)) return true;
-
- if (_compositing(surface)) {
- if (_matting(surface)) return _rasterScaledMattedRleImage(surface, image, &itransform, bbox, opacity);
- else return _rasterScaledMaskedRleImage(surface, image, &itransform, bbox, opacity);
- } else if (_blending(surface)) {
- return _rasterScaledBlendingRleImage(surface, image, &itransform, bbox, opacity);
- } else {
- return _rasterScaledRleImage(surface, image, &itransform, bbox, opacity);
+ return _rasterDirectMattedImage(surface, image, bbox, w, h, opacity);
+ }
+ return _rasterDirectMaskedImage(surface, image, bbox, w, h, opacity);
}
- return false;
+ if (_blending(surface)) return _rasterDirectBlendingImage(surface, image, bbox, w, h, opacity);
+ return _rasterDirectImage(surface, image, bbox, w, h, opacity);
}
-
bool rasterDirectRleImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, uint8_t opacity)
{
if (surface->channelSize == sizeof(uint8_t)) {
@@ -1665,16 +1363,12 @@ bool rasterDirectRleImage(SwSurface* surface, const SwImage& image, const Render
if (_compositing(surface)) {
if (_matting(surface)) return _rasterDirectMattedRleImage(surface, image, bbox, opacity);
- else return _rasterDirectMaskedRleImage(surface, image, bbox, opacity);
- } else if (_blending(surface)) {
- return _rasterDirectBlendingRleImage(surface, image, bbox, opacity);
- } else {
- return _rasterDirectRleImage(surface, image, bbox, opacity);
+ return _rasterDirectMaskedRleImage(surface, image, bbox, opacity);
}
- return false;
+ if (_blending(surface)) return _rasterDirectBlendingRleImage(surface, image, bbox, opacity);
+ return _rasterDirectRleImage(surface, image, bbox, opacity);
}
-
bool rasterGradientShape(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, const Fill* fdata, uint8_t opacity)
{
if (!shape->fill) return false;
@@ -1685,17 +1379,11 @@ bool rasterGradientShape(SwSurface* surface, SwShape* shape, const RenderRegion&
return a > 0 ? rasterShape(surface, shape, bbox, c) : true;
}
- auto type = fdata->type();
- if (shape->fastTrack) {
- if (type == Type::LinearGradient) return _rasterLinearGradientRect(surface, bbox, shape->fill);
- else if (type == Type::RadialGradient)return _rasterRadialGradientRect(surface, bbox, shape->fill);
- } else if (shape->rle && shape->rle->valid()) {
- if (type == Type::LinearGradient) return _rasterLinearGradientRle(surface, shape->rle, shape->fill);
- else if (type == Type::RadialGradient) return _rasterRadialGradientRle(surface, shape->rle, shape->fill);
- } return false;
+ if (shape->fastTrack) return _rasterGradientRect(surface, bbox, shape->fill);
+ else if (shape->rle && shape->rle->valid()) return _rasterGradientRle(surface, shape->rle, shape->fill);
+ return false;
}
-
bool rasterGradientStroke(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, const Fill* fdata, uint8_t opacity)
{
if (!shape->stroke || !shape->stroke->fill || !shape->strokeRle || shape->strokeRle->invalid()) return false;
@@ -1705,14 +1393,9 @@ bool rasterGradientStroke(SwSurface* surface, SwShape* shape, const RenderRegion
c.a = MULTIPLY(c.a, opacity);
return c.a > 0 ? rasterStroke(surface, shape, bbox, c) : true;
}
-
- auto type = fdata->type();
- if (type == Type::LinearGradient) return _rasterLinearGradientRle(surface, shape->strokeRle, shape->stroke->fill);
- else if (type == Type::RadialGradient) return _rasterRadialGradientRle(surface, shape->strokeRle, shape->stroke->fill);
- return false;
+ return _rasterGradientRle(surface, shape->strokeRle, shape->stroke->fill);
}
-
bool rasterShape(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, RenderColor& c)
{
if (c.a < 255) {
@@ -1724,7 +1407,6 @@ bool rasterShape(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, R
else return _rasterRle(surface, shape->rle, bbox, c);
}
-
bool rasterStroke(SwSurface* surface, SwShape* shape, const RenderRegion& bbox, RenderColor& c)
{
if (c.a < 255) {
@@ -1736,94 +1418,20 @@ bool rasterStroke(SwSurface* surface, SwShape* shape, const RenderRegion& bbox,
return _rasterRle(surface, shape->strokeRle, bbox, c);
}
-
bool rasterConvertCS(RenderSurface* surface, ColorSpace to)
{
ScopedLock lock(surface->key);
if (surface->cs == to) return true;
- //TODO: Support SIMD accelerations
auto from = surface->cs;
if (((from == ColorSpace::ABGR8888) || (from == ColorSpace::ABGR8888S)) && ((to == ColorSpace::ARGB8888) || (to == ColorSpace::ARGB8888S))) {
surface->cs = to;
- return cRasterABGRtoARGB(surface);
+ return rasterABGRtoARGB(surface);
}
if (((from == ColorSpace::ARGB8888) || (from == ColorSpace::ARGB8888S)) && ((to == ColorSpace::ABGR8888) || (to == ColorSpace::ABGR8888S))) {
surface->cs = to;
- return cRasterARGBtoABGR(surface);
+ return rasterABGRtoARGB(surface);
}
return false;
}
-
-
-//TODO: SIMD OPTIMIZATION?
-void rasterXYFlip(uint32_t* src, uint32_t* dst, int32_t stride, int32_t w, int32_t h, const RenderRegion& bbox, bool flipped)
-{
- constexpr int32_t BLOCK = 8; //experimental decision
-
- if (flipped) {
- src += ((bbox.min.x * stride) + bbox.min.y);
- dst += ((bbox.min.y * stride) + bbox.min.x);
- } else {
- src += ((bbox.min.y * stride) + bbox.min.x);
- dst += ((bbox.min.x * stride) + bbox.min.y);
- }
-
- #pragma omp parallel for
- for (int32_t x = 0; x < w; x += BLOCK) {
- auto bx = std::min(w, x + BLOCK) - x;
- auto in = &src[x];
- auto out = &dst[x * stride];
- for (int32_t y = 0; y < h; y += BLOCK) {
- auto p = &in[y * stride];
- auto q = &out[y];
- auto by = std::min(h, y + BLOCK) - y;
- for (int32_t xx = 0; xx < bx; ++xx) {
- for (int32_t yy = 0; yy < by; ++yy) {
- *q = *p;
- p += stride;
- ++q;
- }
- p += 1 - by * stride;
- q += stride - by;
- }
- }
- }
-}
-
-
-//TODO: can be moved in tvgColor
-void rasterRGB2HSL(uint8_t r, uint8_t g, uint8_t b, float* h, float* s, float* l)
-{
- auto rf = r / 255.0f;
- auto gf = g / 255.0f;
- auto bf = b / 255.0f;
- auto maxVal = std::max(std::max(rf, gf), bf);
- auto minVal = std::min(std::min(rf, gf), bf);
- auto delta = maxVal - minVal;
-
- //lightness
- float t = 0.0f;
- if (l || s) {
- t = (maxVal + minVal) * 0.5f;
- if (l) *l = t;
- }
-
- if (tvg::zero(delta)) {
- if (h) *h = 0.0f;
- if (s) *s = 0.0f;
- } else {
- //saturation
- if (s) {
- *s = (t < 0.5f) ? (delta / (maxVal + minVal)) : (delta / (2.0f - maxVal - minVal));
- }
- //hue
- if (h) {
- if (maxVal == rf) *h = (gf - bf) / delta + (gf < bf ? 6.0f : 0.0f);
- else if (maxVal == gf) *h = (bf - rf) / delta + 2.0f;
- else *h = (rf - gf) / delta + 4.0f;
- *h *= 60.0f; //directly convert to degrees
- }
- }
-}
diff --git a/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterCore.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterCore.cpp
new file mode 100644
index 00000000000..76625f72b8f
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterCore.cpp
@@ -0,0 +1,321 @@
+/*
+ * Copyright (c) 2021 - 2026 ThorVG project. All rights reserved.
+
+ * 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 "tvgSwRasterCore.h"
+
+/************************************************************************/
+/* See tvgSwRasterSimd.cpp */
+/************************************************************************/
+
+#ifdef THORVG_AVX_SUPPORT
+ #if defined(_MSC_VER)
+ #include <intrin.h>
+ #endif
+ uint32_t avxRasterDownScaler(const uint32_t* img, uint32_t stride, uint32_t w, TVG_UNUSED uint32_t h, float sx, TVG_UNUSED float sy, int32_t miny, int32_t maxy, int32_t n);
+ void avxRasterTranslucentPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity);
+ void avxRasterSolidPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity);
+ void avxRasterSolidPixel32(uint32_t* dst, uint32_t val, uint32_t offset, int32_t len);
+ bool avxRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c);
+ bool avxRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c);
+ void avxRasterUnpremultiply(uint32_t* buffer, uint32_t width);
+ void avxRasterPremultiply(uint32_t* buffer, uint32_t width);
+ bool avxRasterABGRtoARGB(RenderSurface* surface);
+ void avxRasterGaussianFilterRow(uint8_t* dst, const uint8_t* src, int32_t w, int32_t dimension, float iarr);
+ void avxRasterGaussianXYFlipBlock(const uint32_t* src, uint32_t* dst, int32_t stride);
+#elif defined(THORVG_NEON_SUPPORT)
+ #if defined(__linux__) && defined(__arm__)
+ #include <sys/auxv.h>
+ #include <asm/hwcap.h>
+ #endif
+ void neonRasterUnpremultiply(uint32_t* buffer, uint32_t width);
+ void neonRasterPremultiply(uint32_t* buffer, uint32_t width);
+ uint32_t neonRasterDownScaler(const uint32_t* img, uint32_t stride, uint32_t w, TVG_UNUSED uint32_t h, float sx, TVG_UNUSED float sy, int32_t miny, int32_t maxy, int32_t n);
+ void neonRasterTranslucentPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity);
+ void neonRasterSolidPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity);
+ void neonRasterSolidPixel32(uint32_t* dst, uint32_t val, uint32_t offset, int32_t len);
+ bool neonRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c);
+ bool neonRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c);
+ bool neonRasterABGRtoARGB(RenderSurface* surface);
+ void neonRasterGaussianFilterRow(uint8_t* dst, const uint8_t* src, int32_t w, int32_t dimension, float iarr);
+ void neonRasterGaussianXYFlipBlock(const uint32_t* src, uint32_t* dst, int32_t stride);
+#endif
+
+/************************************************************************/
+/* Scalar */
+/************************************************************************/
+
+void cRasterGaussianFilterRow(uint8_t* dst, const uint8_t* src, int32_t w, int32_t dimension, float iarr)
+{
+ auto end = w - 1;
+ auto i = 0; // current index
+ auto l = -(dimension + 1); // left index
+ auto r = dimension; // right index
+ int acc[4] = {0, 0, 0, 0}; // sliding accumulator
+
+ // initial accumulation
+ for (int x = l; x < r; ++x) {
+ auto id = tvg::clamp(x, 0, end) * 4;
+ acc[0] += src[id++];
+ acc[1] += src[id++];
+ acc[2] += src[id++];
+ acc[3] += src[id];
+ }
+ // perform filtering
+ for (int x = 0; x < w; ++x, ++r, ++l) {
+ auto rid = tvg::clamp(r, 0, end) * 4;
+ auto lid = tvg::clamp(l, 0, end) * 4;
+ acc[0] += src[rid++] - src[lid++];
+ acc[1] += src[rid++] - src[lid++];
+ acc[2] += src[rid++] - src[lid++];
+ acc[3] += src[rid] - src[lid];
+ // ignored rounding for the performance. It should be originally: acc[idx] * iarr + 0.5f
+ dst[i++] = static_cast<uint8_t>(acc[0] * iarr);
+ dst[i++] = static_cast<uint8_t>(acc[1] * iarr);
+ dst[i++] = static_cast<uint8_t>(acc[2] * iarr);
+ dst[i++] = static_cast<uint8_t>(acc[3] * iarr);
+ }
+}
+
+void cRasterUnpremultiply(uint32_t* buffer, uint32_t width)
+{
+ for (uint32_t x = 0; x < width; ++x) {
+ buffer[x] = UNPREMULTIPLY(buffer[x]);
+ }
+}
+
+void cRasterPremultiply(uint32_t* buffer, uint32_t width)
+{
+ for (uint32_t x = 0; x < width; ++x) {
+ auto c = buffer[x];
+ if (A(c) != 255) buffer[x] = PREMULTIPLY(c, A(c));
+ }
+}
+
+uint32_t cRasterDownScaler(const uint32_t* img, uint32_t stride, uint32_t w, TVG_UNUSED uint32_t h, float sx, TVG_UNUSED float sy, int32_t miny, int32_t maxy, int32_t n)
+{
+ size_t c[4] = {0, 0, 0, 0};
+
+ auto minx = static_cast<int32_t>(sx) - n;
+ if (minx < 0) minx = 0;
+
+ auto maxx = static_cast<int32_t>(sx) + n;
+ if (maxx >= static_cast<int32_t>(w)) maxx = w;
+
+ auto inc = (n / 2) + 1;
+ n = 0;
+
+ auto src = img + minx + miny * stride;
+
+ for (auto y = miny; y < maxy; y += inc) {
+ auto p = src;
+ for (auto x = minx; x < maxx; x += inc, p += inc) {
+ c[0] += A(*p);
+ c[1] += C1(*p);
+ c[2] += C2(*p);
+ c[3] += C3(*p);
+ ++n;
+ }
+ src += (stride * inc);
+ }
+
+ c[0] /= n;
+ c[1] /= n;
+ c[2] /= n;
+ c[3] /= n;
+
+ return (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3];
+}
+
+void cRasterTranslucentPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
+{
+ if (opacity == 255) {
+ for (uint32_t x = 0; x < len; ++x, ++dst, ++src) {
+ *dst = *src + ALPHA_BLEND(*dst, IA(*src));
+ }
+ } else {
+ for (uint32_t x = 0; x < len; ++x, ++dst, ++src) {
+ auto tmp = ALPHA_BLEND(*src, opacity);
+ *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
+ }
+ }
+}
+
+void cRasterSolidPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
+{
+ if (opacity == 255) memcpy(dst, src, size_t(len) * sizeof(uint32_t));
+ else cRasterTranslucentPixels(dst, src, len, opacity);
+}
+
+void cRasterSolidPixel32(uint32_t* dst, uint32_t val, uint32_t offset, int32_t len)
+{
+ dst += offset;
+ for (int32_t x = 0; x < len; ++x) *dst++ = val;
+}
+
+bool cRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
+{
+ const SwSpan* end;
+ int32_t x, len;
+
+ //32bit channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ auto color = surface->join(c.r, c.g, c.b, c.a);
+ uint32_t src;
+ for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
+ if (!span->fetch(bbox, x, len)) continue;
+ auto dst = &surface->buf32[span->y * surface->stride + x];
+ if (span->coverage < 255) src = ALPHA_BLEND(color, span->coverage);
+ else src = color;
+ auto ialpha = IA(src);
+ for (auto x = 0; x < len; ++x, ++dst) {
+ *dst = src + ALPHA_BLEND(*dst, ialpha);
+ }
+ }
+ //8bit grayscale
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ uint8_t src;
+ for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
+ if (!span->fetch(bbox, x, len)) continue;
+ auto dst = &surface->buf8[span->y * surface->stride + x];
+ if (span->coverage < 255) src = MULTIPLY(span->coverage, c.a);
+ else src = c.a;
+ auto ialpha = ~c.a;
+ for (auto x = 0; x < len; ++x, ++dst) {
+ *dst = src + MULTIPLY(*dst, ialpha);
+ }
+ }
+ }
+ return true;
+}
+
+bool cRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
+{
+ //32bits channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ auto color = surface->join(c.r, c.g, c.b, c.a);
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
+ auto ialpha = 255 - c.a;
+ for (uint32_t y = 0; y < bbox.h(); ++y) {
+ auto dst = &buffer[y * surface->stride];
+ for (uint32_t x = 0; x < bbox.w(); ++x, ++dst) {
+ *dst = color + ALPHA_BLEND(*dst, ialpha);
+ }
+ }
+ //8bit grayscale
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ auto buffer = surface->buf8 + (bbox.yMin * surface->stride) + bbox.xMin;
+ auto ialpha = ~c.a;
+ for (uint32_t y = 0; y < bbox.h(); ++y) {
+ auto dst = &buffer[y * surface->stride];
+ for (uint32_t x = 0; x < bbox.w(); ++x, ++dst) {
+ *dst = c.a + MULTIPLY(*dst, ialpha);
+ }
+ }
+ }
+ return true;
+}
+
+bool cRasterABGRtoARGB(RenderSurface* surface)
+{
+ TVGLOG("SW_ENGINE", "Convert ColorSpace ABGR - ARGB [Size: %d x %d]", surface->w, surface->h);
+
+ auto buffer = surface->buf32;
+ #pragma omp parallel for
+ for (int32_t y = 0; y < (int32_t)surface->h; ++y) {
+ auto dst = buffer + uint32_t(y) * surface->stride;
+ for (uint32_t x = 0; x < surface->w; ++x, ++dst) {
+ auto c = *dst;
+ //flip Blue, Red channels
+ *dst = (c & 0xff000000) + ((c & 0x00ff0000) >> 16) + (c & 0x0000ff00) + ((c & 0x000000ff) << 16);
+ }
+ }
+
+ return true;
+}
+
+/************************************************************************/
+/* Runtime Dispatch */
+/************************************************************************/
+
+#if defined(THORVG_AVX_SUPPORT) || defined(THORVG_NEON_SUPPORT)
+ uint32_t (*rasterDownScaler)(const uint32_t*, uint32_t, uint32_t, uint32_t, float, float, int32_t, int32_t, int32_t) = cRasterDownScaler;
+ void (*rasterUnpremultiply)(uint32_t*, uint32_t) = cRasterUnpremultiply;
+ void (*rasterPremultiply)(uint32_t*, uint32_t) = cRasterPremultiply;
+ void (*rasterTranslucentPixels)(uint32_t*, uint32_t*, uint32_t, uint8_t) = cRasterTranslucentPixels;
+ void (*rasterSolidPixels)(uint32_t*, uint32_t*, uint32_t, uint8_t) = cRasterSolidPixels;
+ void (*rasterSolidPixel32)(uint32_t*, uint32_t, uint32_t, int32_t) = cRasterSolidPixel32;
+ bool (*rasterTranslucentRle)(SwSurface*, const SwRle*, const RenderRegion&, const RenderColor&) = cRasterTranslucentRle;
+ bool (*rasterTranslucentRect)(SwSurface*, const RenderRegion&, const RenderColor&) = cRasterTranslucentRect;
+ bool (*rasterABGRtoARGB)(RenderSurface*) = cRasterABGRtoARGB;
+ void (*rasterGaussianFilterRow)(uint8_t*, const uint8_t*, int32_t, int32_t, float) = cRasterGaussianFilterRow;
+ void (*rasterGaussianXYFlipBlock)(const uint32_t*, uint32_t*, int32_t) = nullptr; // A null keeps the scalar path in the caller.
+#endif
+
+void rasterInit()
+{
+#if defined(THORVG_AVX_SUPPORT)
+ // AVX2 also requires OS support for saving XMM/YMM state.
+ #if defined(_MSC_VER)
+ int info[4];
+ __cpuid(info, 0);
+ if (info[0] < 7) return;
+ __cpuidex(info, 1, 0);
+ if ((info[2] & 0x18000000) != 0x18000000) return;
+ if ((_xgetbv(0) & 6) != 6) return;
+ __cpuidex(info, 7, 0);
+ if (!(info[1] & (1 << 5))) return;
+ #elif defined(__GNUC__) || defined(__clang__)
+ __builtin_cpu_init();
+ if (!__builtin_cpu_supports("avx2")) return;
+ #else
+ return;
+ #endif
+ rasterDownScaler = avxRasterDownScaler;
+ rasterUnpremultiply = avxRasterUnpremultiply;
+ rasterPremultiply = avxRasterPremultiply;
+ rasterTranslucentPixels = avxRasterTranslucentPixels;
+ rasterSolidPixels = avxRasterSolidPixels;
+ rasterSolidPixel32 = avxRasterSolidPixel32;
+ rasterTranslucentRle = avxRasterTranslucentRle;
+ rasterTranslucentRect = avxRasterTranslucentRect;
+ rasterABGRtoARGB = avxRasterABGRtoARGB;
+ rasterGaussianFilterRow = avxRasterGaussianFilterRow;
+ rasterGaussianXYFlipBlock = avxRasterGaussianXYFlipBlock;
+ TVGLOG("SW_ENGINE", "Run AVX Vectorization.");
+#elif defined(THORVG_NEON_SUPPORT)
+ #if defined(__linux__) && defined(__arm__)
+ if (!(getauxval(AT_HWCAP) & HWCAP_NEON)) return;
+ #endif
+ rasterDownScaler = neonRasterDownScaler;
+ rasterUnpremultiply = neonRasterUnpremultiply;
+ rasterPremultiply = neonRasterPremultiply;
+ rasterTranslucentPixels = neonRasterTranslucentPixels;
+ rasterSolidPixels = neonRasterSolidPixels;
+ rasterSolidPixel32 = neonRasterSolidPixel32;
+ rasterTranslucentRle = neonRasterTranslucentRle;
+ rasterTranslucentRect = neonRasterTranslucentRect;
+ rasterABGRtoARGB = neonRasterABGRtoARGB;
+ rasterGaussianFilterRow = neonRasterGaussianFilterRow;
+ rasterGaussianXYFlipBlock = neonRasterGaussianXYFlipBlock;
+ TVGLOG("SW_ENGINE", "Run NEON Vectorization.");
+#endif
+}
diff --git a/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterCore.h b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterCore.h
new file mode 100644
index 00000000000..953ec7a789e
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterCore.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2021 - 2026 ThorVG project. All rights reserved.
+
+ * 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.
+ */
+
+#ifndef _TVG_SW_RASTER_CORE_H_
+#define _TVG_SW_RASTER_CORE_H_
+
+#include "tvgSwCommon.h"
+
+uint32_t cRasterDownScaler(const uint32_t*, uint32_t, uint32_t, uint32_t, float, float, int32_t, int32_t, int32_t);
+void cRasterUnpremultiply(uint32_t*, uint32_t);
+void cRasterPremultiply(uint32_t*, uint32_t);
+void cRasterTranslucentPixels(uint32_t*, uint32_t*, uint32_t, uint8_t);
+void cRasterSolidPixels(uint32_t*, uint32_t*, uint32_t, uint8_t);
+void cRasterSolidPixel32(uint32_t*, uint32_t, uint32_t, int32_t);
+bool cRasterTranslucentRle(SwSurface*, const SwRle*, const RenderRegion&, const RenderColor&);
+bool cRasterTranslucentRect(SwSurface*, const RenderRegion&, const RenderColor&);
+bool cRasterABGRtoARGB(RenderSurface*);
+void cRasterGaussianFilterRow(uint8_t*, const uint8_t*, int32_t, int32_t, float);
+
+#if defined(THORVG_AVX_SUPPORT) || defined(THORVG_NEON_SUPPORT)
+ extern uint32_t (*rasterDownScaler)(const uint32_t*, uint32_t, uint32_t, uint32_t, float, float, int32_t, int32_t, int32_t);
+ extern void (*rasterUnpremultiply)(uint32_t*, uint32_t);
+ extern void (*rasterPremultiply)(uint32_t*, uint32_t);
+ extern void (*rasterTranslucentPixels)(uint32_t*, uint32_t*, uint32_t, uint8_t);
+ extern void (*rasterSolidPixels)(uint32_t*, uint32_t*, uint32_t, uint8_t);
+ extern void (*rasterSolidPixel32)(uint32_t*, uint32_t, uint32_t, int32_t);
+ extern bool (*rasterTranslucentRle)(SwSurface*, const SwRle*, const RenderRegion&, const RenderColor&);
+ extern bool (*rasterTranslucentRect)(SwSurface*, const RenderRegion&, const RenderColor&);
+ extern bool (*rasterABGRtoARGB)(RenderSurface*);
+ extern void (*rasterGaussianFilterRow)(uint8_t*, const uint8_t*, int32_t, int32_t, float);
+ extern void (*rasterGaussianXYFlipBlock)(const uint32_t*, uint32_t*, int32_t);
+#else
+ // Resolve scalar calls directly when SIMD dispatch is not built.
+ #define rasterDownScaler cRasterDownScaler
+ #define rasterUnpremultiply cRasterUnpremultiply
+ #define rasterPremultiply cRasterPremultiply
+ #define rasterTranslucentPixels cRasterTranslucentPixels
+ #define rasterSolidPixels cRasterSolidPixels
+ #define rasterSolidPixel32 cRasterSolidPixel32
+ #define rasterTranslucentRle cRasterTranslucentRle
+ #define rasterTranslucentRect cRasterTranslucentRect
+ #define rasterABGRtoARGB cRasterABGRtoARGB
+ #define rasterGaussianFilterRow cRasterGaussianFilterRow
+#endif
+
+#endif // _TVG_SW_RASTER_CORE_H_
diff --git a/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterSimd.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterSimd.cpp
new file mode 100644
index 00000000000..4a7af685c24
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterSimd.cpp
@@ -0,0 +1,715 @@
+/*
+ * Copyright (c) 2021 - 2026 ThorVG project. All rights reserved.
+
+ * 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 "tvgSwRasterCore.h"
+
+/************************************************************************/
+/* AVX2 */
+/************************************************************************/
+
+#ifdef THORVG_AVX_SUPPORT
+
+#include <immintrin.h>
+
+#define N_32BITS_IN_256REG 8
+
+static __m256i avxScalePixels(__m256i pixels, __m256i factors)
+{
+ // Each 32-bit lane contains one pixel and a factor in [0, 256].
+ // Scale alternating channels in 16-bit lanes without unpacking the pixels.
+ const auto mask = _mm256_set1_epi32(0x00ff00ff);
+ factors = _mm256_or_si256(factors, _mm256_slli_epi32(factors, 16));
+ auto even = _mm256_mullo_epi16(_mm256_and_si256(pixels, mask), factors);
+ auto odd = _mm256_mullo_epi16(_mm256_srli_epi16(pixels, 8), factors);
+ return _mm256_or_si256(_mm256_srli_epi16(even, 8), _mm256_andnot_si256(mask, odd));
+}
+
+uint32_t avxRasterDownScaler(const uint32_t* img, uint32_t stride, uint32_t w, TVG_UNUSED uint32_t h, float sx, TVG_UNUSED float sy, int32_t miny, int32_t maxy, int32_t n)
+{
+ // At most 4*4 pixels contribute, so each channel sum fits in uint16_t.
+ auto sum = _mm_setzero_si128();
+
+ auto minx = static_cast<int32_t>(sx) - n;
+ if (minx < 0) minx = 0;
+
+ auto maxx = static_cast<int32_t>(sx) + n;
+ if (maxx >= static_cast<int32_t>(w)) maxx = w;
+
+ auto inc = (n / 2) + 1;
+ n = 0;
+
+ auto src = img + minx + miny * stride;
+
+ for (auto y = miny; y < maxy; y += inc) {
+ auto p = src;
+ for (auto x = minx; x < maxx; x += inc, p += inc) {
+ sum = _mm_add_epi16(sum, _mm_cvtepu8_epi16(_mm_cvtsi32_si128(*p)));
+ ++n;
+ }
+ src += (stride * inc);
+ }
+
+ auto c0 = _mm_extract_epi16(sum, 0) / n;
+ auto c1 = _mm_extract_epi16(sum, 1) / n;
+ auto c2 = _mm_extract_epi16(sum, 2) / n;
+ auto c3 = static_cast<uint32_t>(_mm_extract_epi16(sum, 3)) / n;
+
+ return (c3 << 24) | (c2 << 16) | (c1 << 8) | c0;
+}
+
+void avxRasterTranslucentPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
+{
+ const auto opacityVec = _mm256_set1_epi32(opacity + 1);
+ const auto full = _mm256_set1_epi32(256);
+ uint32_t i = 0;
+ for (; len - i >= 8; i += 8) {
+ auto source = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src + i));
+ if (opacity != 255) source = avxScalePixels(source, opacityVec);
+ auto inverse = _mm256_sub_epi32(full, _mm256_srli_epi32(source, 24));
+ auto target = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(dst + i));
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + i), _mm256_add_epi32(source, avxScalePixels(target, inverse)));
+ }
+ cRasterTranslucentPixels(dst + i, src + i, len - i, opacity);
+}
+
+void avxRasterSolidPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
+{
+ if (opacity == 255) memcpy(dst, src, size_t(len) * sizeof(uint32_t));
+ else avxRasterTranslucentPixels(dst, src, len, opacity);
+}
+
+void avxRasterSolidPixel32(uint32_t* dst, uint32_t val, uint32_t offset, int32_t len)
+{
+ if (len <= 0) return;
+ // 1. calculate how many iterations we need to cover the length
+ uint32_t iterations = len / N_32BITS_IN_256REG;
+ uint32_t avxFilled = iterations * N_32BITS_IN_256REG;
+
+ // 2. set the beginning of the array
+ dst += offset;
+
+ // 3. fill the octets
+ for (uint32_t i = 0; i < iterations; ++i, dst += N_32BITS_IN_256REG) {
+ _mm256_storeu_si256((__m256i*)dst, _mm256_set1_epi32(val));
+ }
+
+ // 4. fill leftovers (in the first step we have to set the pointer to the place where the avx job is done)
+ int32_t leftovers = len - avxFilled;
+ while (leftovers--) *dst++ = val;
+}
+
+bool avxRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
+{
+ auto h = bbox.h();
+ auto w = bbox.w();
+
+ // 32bits channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ auto color = surface->join(c.r, c.g, c.b, c.a);
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
+ uint32_t ialpha = 255 - c.a;
+ auto avxColor = _mm256_set1_epi32(color);
+ auto avxIalpha = _mm256_set1_epi32(ialpha + 1);
+ for (uint32_t y = 0; y < h; ++y) {
+ auto dst = &buffer[y * surface->stride];
+ uint32_t x = 0;
+ for (; w - x >= 8; x += 8) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(dst + x));
+ auto result = _mm256_add_epi32(avxColor, avxScalePixels(pixels, avxIalpha));
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + x), result);
+ }
+ for (; x < w; ++x) {
+ dst[x] = color + ALPHA_BLEND(dst[x], ialpha);
+ }
+ }
+ // 8bit grayscale
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ auto buffer = surface->buf8 + (bbox.yMin * surface->stride) + bbox.xMin;
+ const auto ialpha = static_cast<uint8_t>(~c.a);
+ const auto mask = _mm256_set1_epi16(0x00ff);
+ const auto avxIalpha = _mm256_set1_epi16(ialpha);
+ const auto avxAlpha = _mm256_set1_epi8(c.a);
+ for (uint32_t y = 0; y < h; ++y) {
+ auto dst = &buffer[y * surface->stride];
+ uint32_t x = 0;
+ for (; w - x >= 32; x += 32) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(dst + x));
+ auto even = _mm256_mullo_epi16(_mm256_and_si256(pixels, mask), avxIalpha);
+ auto odd = _mm256_mullo_epi16(_mm256_srli_epi16(pixels, 8), avxIalpha);
+ even = _mm256_srli_epi16(_mm256_add_epi16(even, mask), 8);
+ odd = _mm256_andnot_si256(mask, _mm256_add_epi16(odd, mask));
+ auto result = _mm256_add_epi8(avxAlpha, _mm256_or_si256(even, odd));
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + x), result);
+ }
+ for (; x < w; ++x) {
+ dst[x] = c.a + MULTIPLY(dst[x], ialpha);
+ }
+ }
+ }
+ return true;
+}
+
+bool avxRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
+{
+ const SwSpan* end;
+ int32_t x, len;
+
+ // 32bit channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ auto color = surface->join(c.r, c.g, c.b, c.a);
+ uint32_t src;
+
+ for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
+ if (!span->fetch(bbox, x, len)) continue;
+ if (span->coverage < 255) src = ALPHA_BLEND(color, span->coverage);
+ else src = color;
+ auto dst = &surface->buf32[span->y * surface->stride + x];
+ auto ialpha = IA(src);
+ auto avxSrc = _mm256_set1_epi32(src);
+ auto avxIalpha = _mm256_set1_epi32(ialpha + 1);
+ int32_t i = 0;
+ for (; i <= len - 8; i += 8) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(dst + i));
+ auto result = _mm256_add_epi32(avxSrc, avxScalePixels(pixels, avxIalpha));
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + i), result);
+ }
+ for (; i < len; ++i) {
+ dst[i] = src + ALPHA_BLEND(dst[i], ialpha);
+ }
+ }
+ // 8bit grayscale
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ const auto mask = _mm256_set1_epi16(0x00ff);
+ const auto ialpha = static_cast<uint8_t>(~c.a);
+ const auto avxIalpha = _mm256_set1_epi16(ialpha);
+ uint8_t src;
+ for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
+ if (!span->fetch(bbox, x, len)) continue;
+ auto dst = &surface->buf8[span->y * surface->stride + x];
+ if (span->coverage < 255) src = MULTIPLY(span->coverage, c.a);
+ else src = c.a;
+ const auto avxSrc = _mm256_set1_epi8(src);
+ int32_t i = 0;
+ for (; i <= len - 32; i += 32) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(dst + i));
+ auto even = _mm256_mullo_epi16(_mm256_and_si256(pixels, mask), avxIalpha);
+ auto odd = _mm256_mullo_epi16(_mm256_srli_epi16(pixels, 8), avxIalpha);
+ even = _mm256_srli_epi16(_mm256_add_epi16(even, mask), 8);
+ odd = _mm256_andnot_si256(mask, _mm256_add_epi16(odd, mask));
+ auto result = _mm256_add_epi8(avxSrc, _mm256_or_si256(even, odd));
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + i), result);
+ }
+ for (; i < len; ++i) {
+ dst[i] = src + MULTIPLY(dst[i], ialpha);
+ }
+ }
+ }
+ return true;
+}
+
+void avxRasterUnpremultiply(uint32_t* buffer, uint32_t width)
+{
+ const auto mask = _mm256_set1_epi32(0xff);
+ const auto full = _mm256_set1_epi32(255);
+ const auto one = _mm256_set1_epi32(1);
+ uint32_t x = 0;
+ for (; width - x >= 8; x += 8) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(buffer + x));
+ auto alpha = _mm256_srli_epi32(pixels, 24);
+ auto unchanged = _mm256_or_si256(_mm256_cmpeq_epi32(alpha, full), _mm256_cmpeq_epi32(alpha, _mm256_setzero_si256()));
+ if (_mm256_movemask_epi8(unchanged) == -1) continue;
+ auto divisor = _mm256_cvtepi32_ps(_mm256_max_epi32(alpha, one));
+ auto result = _mm256_slli_epi32(alpha, 24);
+ for (int shift = 0; shift < 24; shift += 8) {
+ auto bits = _mm_cvtsi32_si128(shift);
+ auto channel = _mm256_and_si256(_mm256_srl_epi32(pixels, bits), mask);
+ auto scaled = _mm256_mullo_epi32(channel, full);
+ auto quotient = _mm256_cvttps_epi32(_mm256_div_ps(_mm256_cvtepi32_ps(scaled), divisor));
+ result = _mm256_or_si256(result, _mm256_sll_epi32(_mm256_min_epi32(quotient, full), bits));
+ }
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(buffer + x), _mm256_blendv_epi8(result, pixels, unchanged));
+ }
+ cRasterUnpremultiply(buffer + x, width - x);
+}
+
+void avxRasterPremultiply(uint32_t* buffer, uint32_t width)
+{
+ const auto full = _mm256_set1_epi32(255);
+ const auto alphaMask = _mm256_set1_epi32(0xff000000);
+ uint32_t x = 0;
+ for (; width - x >= 8; x += 8) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(buffer + x));
+ auto alpha = _mm256_srli_epi32(pixels, 24);
+ // A factor of 256 preserves opaque pixels; other pixels use alpha / 256.
+ auto factors = _mm256_sub_epi32(alpha, _mm256_cmpeq_epi32(alpha, full));
+ auto result = avxScalePixels(pixels, factors);
+ result = _mm256_blendv_epi8(result, pixels, alphaMask);
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(buffer + x), result);
+ }
+ cRasterPremultiply(buffer + x, width - x);
+}
+
+bool avxRasterABGRtoARGB(RenderSurface* surface)
+{
+ const auto shuffle = _mm256_setr_epi8(2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15,
+ 2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15);
+ const auto end = surface->w & ~7u;
+ #pragma omp parallel for
+ for (int32_t y = 0; y < (int32_t)surface->h; ++y) {
+ auto dst = surface->buf32 + uint32_t(y) * surface->stride;
+ uint32_t x = 0;
+ for (; x < end; x += 8) {
+ auto pixels = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(dst + x));
+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + x), _mm256_shuffle_epi8(pixels, shuffle));
+ }
+ for (; x < surface->w; ++x) {
+ auto c = dst[x];
+ dst[x] = (c & 0xff00ff00) | ((c & 0x00ff0000) >> 16) | ((c & 0x000000ff) << 16);
+ }
+ }
+ return true;
+}
+
+void avxRasterGaussianFilterRow(uint8_t* dst, const uint8_t* src, int32_t w, int32_t dimension, float iarr)
+{
+ auto end = w - 1;
+ auto i = 0;
+ auto l = -(dimension + 1);
+ auto r = dimension;
+ auto acc = _mm_setzero_si128();
+ const auto zero = _mm_setzero_si128();
+ const auto scale = _mm_set1_ps(iarr);
+
+ for (int x = l; x < r; ++x) {
+ auto id = tvg::clamp(x, 0, end) * 4;
+ uint32_t pixel;
+ memcpy(&pixel, src + id, sizeof(pixel));
+ acc = _mm_add_epi32(acc, _mm_cvtepu8_epi32(_mm_cvtsi32_si128(pixel)));
+ }
+
+ for (int x = 0; x < w; ++x, ++r, ++l) {
+ auto rid = tvg::clamp(r, 0, end) * 4;
+ auto lid = tvg::clamp(l, 0, end) * 4;
+ uint32_t right, left;
+ memcpy(&right, src + rid, sizeof(right));
+ memcpy(&left, src + lid, sizeof(left));
+ auto added = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(right));
+ auto removed = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(left));
+ acc = _mm_add_epi32(acc, _mm_sub_epi32(added, removed));
+ auto values = _mm_cvttps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(acc), scale));
+ auto packed = _mm_packus_epi16(_mm_packs_epi32(values, zero), zero);
+ auto pixel = static_cast<uint32_t>(_mm_cvtsi128_si32(packed));
+ memcpy(dst + i, &pixel, sizeof(pixel));
+ i += 4;
+ }
+}
+
+void avxRasterGaussianXYFlipBlock(const uint32_t* src, uint32_t* dst, int32_t stride)
+{
+ // Transpose one complete 8x8 block using four 4x4 tiles.
+ for (int32_t x = 0; x < 8; x += 4) {
+ for (int32_t y = 0; y < 8; y += 4) {
+ auto s = src + x + y * stride;
+ auto d = dst + x * stride + y;
+ auto r0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s));
+ auto r1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + stride));
+ auto r2 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + 2 * stride));
+ auto r3 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + 3 * stride));
+ auto t0 = _mm_unpacklo_epi32(r0, r1);
+ auto t1 = _mm_unpackhi_epi32(r0, r1);
+ auto t2 = _mm_unpacklo_epi32(r2, r3);
+ auto t3 = _mm_unpackhi_epi32(r2, r3);
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(d), _mm_unpacklo_epi64(t0, t2));
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(d + stride), _mm_unpackhi_epi64(t0, t2));
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(d + 2 * stride), _mm_unpacklo_epi64(t1, t3));
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(d + 3 * stride), _mm_unpackhi_epi64(t1, t3));
+ }
+ }
+}
+
+#endif
+
+/************************************************************************/
+/* Neon */
+/************************************************************************/
+
+#ifdef THORVG_NEON_SUPPORT
+
+#include <arm_neon.h>
+
+// TODO: Verify MSVC ARM64 NEON header and intrinsic compatibility, including the Meson probe.
+#if defined(__ARM_64BIT_STATE) || defined(_M_ARM64)
+ #define TVG_AARCH64 1
+#else
+ #define TVG_AARCH64 0
+#endif
+
+static uint8x8_t ALPHA_BLEND(uint8x8_t c, uint8x8_t a)
+{
+ return vshrn_n_u16(vmull_u8(c, a), 8);
+}
+
+static uint8x8_t neonScalePixels(uint8x8_t pixels, uint32x2_t factors)
+{
+ auto expanded = vcombine_u16(vdup_n_u16(static_cast<uint16_t>(vget_lane_u32(factors, 0))),
+ vdup_n_u16(static_cast<uint16_t>(vget_lane_u32(factors, 1))));
+ return vmovn_u16(vshrq_n_u16(vmulq_u16(vmovl_u8(pixels), expanded), 8));
+}
+
+void neonRasterUnpremultiply(uint32_t* buffer, uint32_t width)
+{
+ const auto mask = vdupq_n_u32(255);
+ const auto one = vdupq_n_u32(1);
+ uint32_t x = 0;
+ for (; x + 4 <= width; x += 4) {
+ auto pixels = vld1q_u32(buffer + x);
+ auto alpha = vshrq_n_u32(pixels, 24);
+ auto unchanged = vorrq_u32(vceqq_u32(alpha, mask), vceqq_u32(alpha, vdupq_n_u32(0)));
+ if (vget_lane_u64(vreinterpret_u64_u32(vand_u32(vget_low_u32(unchanged), vget_high_u32(unchanged))), 0) == UINT64_MAX) continue;
+ auto divisor = vmaxq_u32(alpha, one);
+ auto divisorFloat = vcvtq_f32_u32(divisor);
+ auto reciprocal = vrecpeq_f32(divisorFloat);
+ reciprocal = vmulq_f32(reciprocal, vrecpsq_f32(divisorFloat, reciprocal));
+ reciprocal = vmulq_f32(reciprocal, vrecpsq_f32(divisorFloat, reciprocal));
+ auto result = vshlq_n_u32(alpha, 24);
+ for (int shift = 0; shift < 24; shift += 8) {
+ auto bits = vdupq_n_s32(shift);
+ auto channel = vandq_u32(vshlq_u32(pixels, vnegq_s32(bits)), mask);
+ auto numerator = vmulq_u32(channel, mask);
+ auto quotient = vcvtq_u32_f32(vmulq_f32(vcvtq_f32_u32(numerator), reciprocal));
+ auto product = vmulq_u32(quotient, divisor);
+ quotient = vsubq_u32(quotient, vandq_u32(vcgtq_u32(product, numerator), one));
+ product = vmulq_u32(quotient, divisor);
+ quotient = vaddq_u32(quotient, vandq_u32(vcgeq_u32(numerator, vaddq_u32(product, divisor)), one));
+ result = vorrq_u32(result, vshlq_u32(vminq_u32(quotient, mask), bits));
+ }
+ vst1q_u32(buffer + x, vbslq_u32(unchanged, pixels, result));
+ }
+ cRasterUnpremultiply(buffer + x, width - x);
+}
+
+void neonRasterPremultiply(uint32_t* buffer, uint32_t width)
+{
+ const auto mask = vdupq_n_u32(255);
+ uint32_t x = 0;
+ for (; x + 4 <= width; x += 4) {
+ auto pixels = vld1q_u32(buffer + x);
+ auto alpha = vshrq_n_u32(pixels, 24);
+ auto result = vshlq_n_u32(alpha, 24);
+ for (int shift = 0; shift < 24; shift += 8) {
+ auto bits = vdupq_n_s32(shift);
+ auto channel = vandq_u32(vshlq_u32(pixels, vnegq_s32(bits)), mask);
+ auto scaled = vshrq_n_u32(vmulq_u32(channel, alpha), 8);
+ result = vorrq_u32(result, vshlq_u32(scaled, bits));
+ }
+ auto opaque = vceqq_u32(alpha, mask);
+ vst1q_u32(buffer + x, vbslq_u32(opaque, pixels, result));
+ }
+ cRasterPremultiply(buffer + x, width - x);
+}
+
+uint32_t neonRasterDownScaler(const uint32_t* img, uint32_t stride, uint32_t w, TVG_UNUSED uint32_t h, float sx, TVG_UNUSED float sy, int32_t miny, int32_t maxy, int32_t n)
+{
+ // Each clipped span is at most 2*n; stepping by floor(n/2)+1 takes at most 4 samples per axis.
+ // At most 4*4 pixels contribute, so each channel sum is <= 16*255=4080 and fits in uint16_t.
+ // vaddw_u8 widens and accumulates 8-bit channels into uint16x8_t in one instruction.
+ uint16x8_t sum = vdupq_n_u16(0);
+
+ auto minx = static_cast<int32_t>(sx) - n;
+ if (minx < 0) minx = 0;
+
+ auto maxx = static_cast<int32_t>(sx) + n;
+ if (maxx >= static_cast<int32_t>(w)) maxx = w;
+
+ auto inc = (n / 2) + 1;
+ n = 0;
+
+ auto src = img + minx + miny * stride;
+
+ for (auto y = miny; y < maxy; y += inc) {
+ auto p = src;
+ for (auto x = minx; x < maxx; x += inc, p += inc) {
+ sum = vaddw_u8(sum, vreinterpret_u8_u32(vdup_n_u32(*p)));
+ ++n;
+ }
+ src += (stride * inc);
+ }
+
+ uint32_t c[4];
+ vst1q_u32(c, vmovl_u16(vrev64_u16(vget_low_u16(sum))));
+ c[0] /= n;
+ c[1] /= n;
+ c[2] /= n;
+ c[3] /= n;
+
+ return (c[0] << 24) | (c[1] << 16) | (c[2] << 8) | c[3];
+}
+
+void neonRasterTranslucentPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
+{
+ const auto opacityVec = vdup_n_u32(opacity + 1);
+ uint32_t i = 0;
+ for (; len - i >= 2; i += 2) {
+ auto source = vld1_u8(reinterpret_cast<const uint8_t*>(src + i));
+ if (opacity != 255) source = neonScalePixels(source, opacityVec);
+ auto inverse = vsub_u32(vdup_n_u32(256), vshr_n_u32(vreinterpret_u32_u8(source), 24));
+ auto target = vld1_u8(reinterpret_cast<const uint8_t*>(dst + i));
+ vst1_u8(reinterpret_cast<uint8_t*>(dst + i), vadd_u8(source, neonScalePixels(target, inverse)));
+ }
+ cRasterTranslucentPixels(dst + i, src + i, len - i, opacity);
+}
+
+void neonRasterSolidPixels(uint32_t* dst, uint32_t* src, uint32_t len, uint8_t opacity)
+{
+ if (opacity == 255) memcpy(dst, src, size_t(len) * sizeof(uint32_t));
+ else neonRasterTranslucentPixels(dst, src, len, opacity);
+}
+
+void neonRasterSolidPixel32(uint32_t* dst, uint32_t val, uint32_t offset, int32_t len)
+{
+ dst += offset;
+
+ uint32x4_t vecVal = vdupq_n_u32(val);
+
+#if TVG_AARCH64
+ uint32_t iterations = len / 16;
+ uint32_t neonFilled = iterations * 16;
+ uint32x4x4_t valQuad = {vecVal, vecVal, vecVal, vecVal};
+ for (uint32_t i = 0; i < iterations; ++i, dst += 16) {
+ vst4q_u32(dst, valQuad);
+ }
+#else
+ uint32_t iterations = len / 4;
+ uint32_t neonFilled = iterations * 4;
+ for (uint32_t i = 0; i < iterations; ++i, dst += 4) {
+ vst1q_u32(dst, vecVal);
+ }
+#endif
+ auto leftovers = len - neonFilled;
+ while (leftovers--) *dst++ = val;
+}
+
+bool neonRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
+{
+ const SwSpan* end;
+ int32_t x, len;
+
+ // 32bit channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ auto color = surface->join(c.r, c.g, c.b, c.a);
+ uint32_t src;
+ uint8x8_t* vDst = nullptr;
+ int32_t align;
+
+ for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
+ if (!span->fetch(bbox, x, len)) continue;
+ if (span->coverage < 255) src = ALPHA_BLEND(color, span->coverage);
+ else src = color;
+
+ auto dst = &surface->buf32[span->y * surface->stride + x];
+ auto ialpha = IA(src);
+
+ if ((((uintptr_t)dst) & 0x7) != 0) {
+ // fill not aligned byte
+ *dst = src + ALPHA_BLEND(*dst, ialpha);
+ vDst = (uint8x8_t*)(dst + 1);
+ align = 1;
+ } else {
+ vDst = (uint8x8_t*)dst;
+ align = 0;
+ }
+
+ uint8x8_t vSrc = (uint8x8_t)vdup_n_u32(src);
+ uint8x8_t vIalpha = vdup_n_u8((uint8_t)ialpha);
+
+ for (int32_t x = 0; x < (len - align) / 2; ++x) {
+ vDst[x] = vadd_u8(vSrc, ALPHA_BLEND(vDst[x], vIalpha));
+ }
+
+ auto leftovers = (len - align) % 2;
+ if (leftovers > 0) dst[len - 1] = src + ALPHA_BLEND(dst[len - 1], ialpha);
+ }
+ // 8bit grayscale
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ const auto ialpha = static_cast<uint8_t>(~c.a);
+ const auto vIalpha = vdup_n_u8(ialpha);
+ const auto bias = vdupq_n_u16(255);
+ uint8_t src;
+ for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
+ if (!span->fetch(bbox, x, len)) continue;
+ auto dst = &surface->buf8[span->y * surface->stride + x];
+ if (span->coverage < 255) src = MULTIPLY(span->coverage, c.a);
+ else src = c.a;
+ const auto vSrc = vdupq_n_u8(src);
+ int32_t i = 0;
+ for (; len - i >= 16; i += 16) {
+ auto pixels = vld1q_u8(dst + i);
+ auto low = vmlal_u8(bias, vget_low_u8(pixels), vIalpha);
+ auto high = vmlal_u8(bias, vget_high_u8(pixels), vIalpha);
+ auto scaled = vcombine_u8(vshrn_n_u16(low, 8), vshrn_n_u16(high, 8));
+ vst1q_u8(dst + i, vaddq_u8(vSrc, scaled));
+ }
+ for (; i < len; ++i) {
+ dst[i] = src + MULTIPLY(dst[i], ialpha);
+ }
+ }
+ }
+ return true;
+}
+
+bool neonRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
+{
+ auto h = bbox.h();
+ auto w = bbox.w();
+
+ // 32bits channels
+ if (surface->channelSize == sizeof(uint32_t)) {
+ auto color = surface->join(c.r, c.g, c.b, c.a);
+ auto buffer = surface->buf32 + (bbox.yMin * surface->stride) + bbox.xMin;
+ auto ialpha = 255 - c.a;
+ auto vColor = vdup_n_u32(color);
+ auto vIalpha = vdup_n_u8((uint8_t)ialpha);
+ uint8x8_t* vDst = nullptr;
+ uint32_t align;
+
+ for (uint32_t y = 0; y < h; ++y) {
+ auto dst = &buffer[y * surface->stride];
+
+ if ((((uintptr_t)dst) & 0x7) != 0) {
+ // fill not aligned byte
+ *dst = color + ALPHA_BLEND(*dst, ialpha);
+ vDst = (uint8x8_t*)(dst + 1);
+ align = 1;
+ } else {
+ vDst = (uint8x8_t*)dst;
+ align = 0;
+ }
+
+ for (uint32_t x = 0; x < (w - align) / 2; ++x) {
+ vDst[x] = vadd_u8((uint8x8_t)vColor, ALPHA_BLEND(vDst[x], vIalpha));
+ }
+
+ auto leftovers = (w - align) % 2;
+ if (leftovers > 0) dst[w - 1] = color + ALPHA_BLEND(dst[w - 1], ialpha);
+ }
+ // 8bit grayscale
+ } else if (surface->channelSize == sizeof(uint8_t)) {
+ auto buffer = surface->buf8 + (bbox.yMin * surface->stride) + bbox.xMin;
+ const auto ialpha = static_cast<uint8_t>(~c.a);
+ const auto vIalpha = vdup_n_u8(ialpha);
+ const auto vAlpha = vdupq_n_u8(c.a);
+ const auto bias = vdupq_n_u16(255);
+ for (uint32_t y = 0; y < h; ++y) {
+ auto dst = &buffer[y * surface->stride];
+ uint32_t x = 0;
+ for (; w - x >= 16; x += 16) {
+ auto pixels = vld1q_u8(dst + x);
+ auto low = vmlal_u8(bias, vget_low_u8(pixels), vIalpha);
+ auto high = vmlal_u8(bias, vget_high_u8(pixels), vIalpha);
+ auto scaled = vcombine_u8(vshrn_n_u16(low, 8), vshrn_n_u16(high, 8));
+ vst1q_u8(dst + x, vaddq_u8(vAlpha, scaled));
+ }
+ for (; x < w; ++x) {
+ dst[x] = c.a + MULTIPLY(dst[x], ialpha);
+ }
+ }
+ }
+ return true;
+}
+
+bool neonRasterABGRtoARGB(RenderSurface* surface)
+{
+ const auto mask = vdupq_n_u32(0xff00ff00);
+ const auto end = surface->w & ~3u;
+ #pragma omp parallel for
+ for (int32_t y = 0; y < (int32_t)surface->h; ++y) {
+ auto dst = surface->buf32 + uint32_t(y) * surface->stride;
+ uint32_t x = 0;
+ for (; x < end; x += 4) {
+ auto pixels = vld1q_u32(dst + x);
+ auto swapped = vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32(pixels)));
+ vst1q_u32(dst + x, vbslq_u32(mask, pixels, swapped));
+ }
+ for (; x < surface->w; ++x) {
+ auto c = dst[x];
+ dst[x] = (c & 0xff00ff00) | ((c & 0x00ff0000) >> 16) | ((c & 0x000000ff) << 16);
+ }
+ }
+ return true;
+}
+
+void neonRasterGaussianFilterRow(uint8_t* dst, const uint8_t* src, int32_t w, int32_t dimension, float iarr)
+{
+ auto end = w - 1;
+ auto i = 0;
+ auto l = -(dimension + 1);
+ auto r = dimension;
+ auto acc = vdupq_n_s32(0);
+ const auto scale = vdupq_n_f32(iarr);
+
+ for (int x = l; x < r; ++x) {
+ auto id = tvg::clamp(x, 0, end) * 4;
+ uint32_t pixel;
+ memcpy(&pixel, src + id, sizeof(pixel));
+ auto channels = vmovl_u16(vget_low_u16(vmovl_u8(vcreate_u8(pixel))));
+ acc = vaddq_s32(acc, vreinterpretq_s32_u32(channels));
+ }
+
+ for (int x = 0; x < w; ++x, ++r, ++l) {
+ auto rid = tvg::clamp(r, 0, end) * 4;
+ auto lid = tvg::clamp(l, 0, end) * 4;
+ uint32_t right, left;
+ memcpy(&right, src + rid, sizeof(right));
+ memcpy(&left, src + lid, sizeof(left));
+ auto added = vmovl_u16(vget_low_u16(vmovl_u8(vcreate_u8(right))));
+ auto removed = vmovl_u16(vget_low_u16(vmovl_u8(vcreate_u8(left))));
+ acc = vaddq_s32(acc, vsubq_s32(vreinterpretq_s32_u32(added), vreinterpretq_s32_u32(removed)));
+ auto values = vcvtq_s32_f32(vmulq_f32(vcvtq_f32_s32(acc), scale));
+ auto packed = vmovn_u16(vcombine_u16(vqmovun_s32(values), vdup_n_u16(0)));
+ auto pixel = vget_lane_u32(vreinterpret_u32_u8(packed), 0);
+ memcpy(dst + i, &pixel, sizeof(pixel));
+ i += 4;
+ }
+}
+
+void neonRasterGaussianXYFlipBlock(const uint32_t* src, uint32_t* dst, int32_t stride)
+{
+ // Transpose one complete 8x8 block using four 4x4 tiles.
+ for (int32_t x = 0; x < 8; x += 4) {
+ for (int32_t y = 0; y < 8; y += 4) {
+ auto s = src + x + y * stride;
+ auto d = dst + x * stride + y;
+ auto r0 = vld1q_u32(s);
+ auto r1 = vld1q_u32(s + stride);
+ auto r2 = vld1q_u32(s + 2 * stride);
+ auto r3 = vld1q_u32(s + 3 * stride);
+ auto t0 = vtrnq_u32(r0, r1);
+ auto t1 = vtrnq_u32(r2, r3);
+ vst1q_u32(d, vcombine_u32(vget_low_u32(t0.val[0]), vget_low_u32(t1.val[0])));
+ vst1q_u32(d + stride, vcombine_u32(vget_low_u32(t0.val[1]), vget_low_u32(t1.val[1])));
+ vst1q_u32(d + 2 * stride, vcombine_u32(vget_high_u32(t0.val[0]), vget_high_u32(t1.val[0])));
+ vst1q_u32(d + 3 * stride, vcombine_u32(vget_high_u32(t0.val[1]), vget_high_u32(t1.val[1])));
+ }
+ }
+}
+
+#endif
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterTexmap.h b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterTexmap.h
similarity index 57%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterTexmap.h
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterTexmap.h
index 3433251320e..c4db37d78ba 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterTexmap.h
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRasterTexmap.h
@@ -34,18 +34,24 @@ struct Polygon
Vertex vertex[3];
};
-//Careful! Shared resource, No support threading
-static float dudx, dvdx;
-static float dxdya, dxdyb, dudya, dvdya;
-static float xa, xb, ua, va;
-
+struct TexmapCtx
+{
+ SwSurface* surface;
+ const SwImage& image;
+ const RenderRegion& bbox;
+ uint8_t opacity;
+
+ // Each textured polygon owns its scan-converter ctx.
+ float dudx, dvdx;
+ float dxdya, dxdyb, dudya, dvdya;
+ float xa, xb, ua, va;
+};
static inline int32_t _modf(float v)
{
return 255 - ((int(v * 256.0f)) & 255);
}
-
static uint8_t _feathering(int iru, int irv, int ar, int ab, int sw, int sh)
{
if (irv == 1) {
@@ -63,50 +69,47 @@ static uint8_t _feathering(int iru, int irv, int ar, int ab, int sw, int sh)
return 255;
}
-
-static bool _rasterMaskedPolygonImageSegment(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int yStart, int yEnd, uint8_t opacity, bool needAA)
+static bool _rasterMaskedPolygonImageSegment(TexmapCtx& ctx, int yStart, int yEnd, bool needAA)
{
TVGERR("SW_ENGINE", "TODO: _rasterMaskedPolygonImageSegment()");
return false;
}
-
-static void _rasterBlendingPolygonImageSegment(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int yStart, int yEnd, uint8_t opacity, bool needAA)
+static void _rasterBlendingPolygonImageSegment(TexmapCtx& ctx, int yStart, int yEnd, bool needAA)
{
- if (surface->channelSize == sizeof(uint8_t)) {
+ if (ctx.surface->channelSize == sizeof(uint8_t)) {
TVGERR("SW_ENGINE", "Not supported grayscale Textmap polygon!");
return;
}
- auto _dudx = dudx, _dvdx = dvdx;
- auto _dxdya = dxdya, _dxdyb = dxdyb, _dudya = dudya, _dvdya = dvdya;
- auto _xa = xa, _xb = xb, _ua = ua, _va = va;
- auto sbuf = image.buf32;
- auto dbuf = surface->buf32;
- auto sw = static_cast<int32_t>(image.w);
- auto sh = static_cast<int32_t>(image.h);
+ auto _dudx = ctx.dudx, _dvdx = ctx.dvdx;
+ auto _dxdya = ctx.dxdya, _dxdyb = ctx.dxdyb, _dudya = ctx.dudya, _dvdya = ctx.dvdya;
+ auto _xa = ctx.xa, _xb = ctx.xb, _ua = ctx.ua, _va = ctx.va;
+ auto sbuf = ctx.image.buf32;
+ auto dbuf = ctx.surface->buf32;
+ auto sw = static_cast<int32_t>(ctx.image.w);
+ auto sh = static_cast<int32_t>(ctx.image.h);
int32_t x1, x2, x, y, ar, ab, iru, irv, px;
int32_t vv = 0, uu = 0;
float dx, u, v;
uint32_t* buf;
- if (yStart < bbox.min.y) yStart = bbox.min.y;
- if (yEnd > bbox.max.y) yEnd = bbox.max.y;
+ if (yStart < ctx.bbox.yMin) yStart = ctx.bbox.yMin;
+ if (yEnd > ctx.bbox.yMax) yEnd = ctx.bbox.yMax;
y = yStart;
while (y < yEnd) {
- x1 = std::max((int32_t)_xa, bbox.min.x);
- x2 = std::min((int32_t)_xb, bbox.max.x);
+ x1 = std::max((int32_t)_xa, ctx.bbox.xMin);
+ x2 = std::min((int32_t)_xb, ctx.bbox.xMax);
//Range allowed
- if ((x2 - x1) >= 1 && (x1 < bbox.max.x) && (x2 > bbox.min.x)) {
-
+ if ((x2 - x1) >= 1 && (x1 < ctx.bbox.xMax) && (x2 > ctx.bbox.xMin)) {
//Perform subtexel pre-stepping on UV
dx = 1 - (_xa - x1);
u = _ua + dx * _dudx;
v = _va + dx * _dvdx;
- buf = dbuf + ((y * surface->stride) + x1);
+ buf = dbuf + ((y * ctx.surface->stride) + x1);
x = x1;
//Draw horizontal line
@@ -114,27 +117,27 @@ static void _rasterBlendingPolygonImageSegment(SwSurface* surface, const SwImage
uu = (int) u;
vv = (int) v;
- if ((uint32_t) uu >= image.w || (uint32_t) vv >= image.h) continue;
+ if ((uint32_t)uu >= ctx.image.w || (uint32_t)vv >= ctx.image.h) continue;
ar = _modf(u);
ab = _modf(v);
iru = uu + 1;
irv = vv + 1;
- px = *(sbuf + (vv * image.stride) + uu);
+ px = *(sbuf + (vv * ctx.image.stride) + uu);
- if (image.filter == FilterMethod::Bilinear) {
+ if (ctx.image.filter == FilterMethod::Bilinear) {
// horizontal interpolate
if (iru < sw) {
- int px2 = *(sbuf + (vv * image.stride) + iru);
+ int px2 = *(sbuf + (vv * ctx.image.stride) + iru);
px = INTERPOLATE(px, px2, ar);
}
// vertical interpolate
if (irv < sh) {
- int px2 = *(sbuf + (irv * image.stride) + uu);
+ int px2 = *(sbuf + (irv * ctx.image.stride) + uu);
// horizontal interpolate
if (iru < sw) {
- int px3 = *(sbuf + (irv * image.stride) + iru);
+ int px3 = *(sbuf + (irv * ctx.image.stride) + iru);
px2 = INTERPOLATE(px2, px3, ar);
}
px = INTERPOLATE(px, px2, ab);
@@ -147,7 +150,7 @@ static void _rasterBlendingPolygonImageSegment(SwSurface* surface, const SwImage
if (feather < 255) px = ALPHA_BLEND(px, feather);
}
- *buf = INTERPOLATE(surface->blender(rasterUnpremultiply(px), *buf), *buf, MULTIPLY(opacity, A(px)));
+ *buf = INTERPOLATE(ctx.surface->blender(ctx.surface, UNPREMULTIPLY(px), *buf), *buf, MULTIPLY(ctx.opacity, A(px)));
++buf;
//Step UV horizontally
@@ -164,80 +167,78 @@ static void _rasterBlendingPolygonImageSegment(SwSurface* surface, const SwImage
++y;
}
- xa = _xa;
- xb = _xb;
- ua = _ua;
- va = _va;
+ ctx.xa = _xa;
+ ctx.xb = _xb;
+ ctx.ua = _ua;
+ ctx.va = _va;
}
-
-static void _rasterPolygonImageSegment32(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int yStart, int yEnd, uint8_t opacity, bool matting, bool needAA)
+static void _rasterPolygonImageSegment32(TexmapCtx& ctx, int yStart, int yEnd, bool matting, bool needAA)
{
- auto _dudx = dudx, _dvdx = dvdx;
- auto _dxdya = dxdya, _dxdyb = dxdyb, _dudya = dudya, _dvdya = dvdya;
- auto _xa = xa, _xb = xb, _ua = ua, _va = va;
- auto sbuf = image.buf32;
- auto dbuf = surface->buf32;
- auto sw = static_cast<int32_t>(image.w);
- auto sh = static_cast<int32_t>(image.h);
+ auto _dudx = ctx.dudx, _dvdx = ctx.dvdx;
+ auto _dxdya = ctx.dxdya, _dxdyb = ctx.dxdyb, _dudya = ctx.dudya, _dvdya = ctx.dvdya;
+ auto _xa = ctx.xa, _xb = ctx.xb, _ua = ctx.ua, _va = ctx.va;
+ auto sbuf = ctx.image.buf32;
+ auto dbuf = ctx.surface->buf32;
+ auto sw = static_cast<int32_t>(ctx.image.w);
+ auto sh = static_cast<int32_t>(ctx.image.h);
int32_t x1, x2, x, y, ar, ab, iru, irv, px;
int32_t vv = 0, uu = 0;
float dx, u, v;
uint32_t* buf;
- auto fullOpacity = (opacity == 255);
+ auto fullOpacity = (ctx.opacity == 255);
//for matting(composition)
- auto csize = matting ? surface->compositor->image.channelSize: 0;
- auto alpha = matting ? surface->alpha(surface->compositor->method) : nullptr;
+ auto csize = matting ? ctx.surface->compositor->image.channelSize : 0;
+ auto alpha = matting ? ctx.surface->alpha(ctx.surface->compositor->method) : nullptr;
uint8_t* cmp = nullptr;
- if (yStart < bbox.min.y) yStart = bbox.min.y;
- if (yEnd > bbox.max.y) yEnd = bbox.max.y;
+ if (yStart < ctx.bbox.yMin) yStart = ctx.bbox.yMin;
+ if (yEnd > ctx.bbox.yMax) yEnd = ctx.bbox.yMax;
y = yStart;
while (y < yEnd) {
- x1 = std::max((int32_t)_xa, bbox.min.x);
- x2 = std::min((int32_t)_xb, bbox.max.x);
+ x1 = std::max((int32_t)_xa, ctx.bbox.xMin);
+ x2 = std::min((int32_t)_xb, ctx.bbox.xMax);
//Range allowed
- if ((x2 - x1) >= 1 && (x1 < bbox.max.x) && (x2 > bbox.min.x)) {
-
+ if ((x2 - x1) >= 1 && (x1 < ctx.bbox.xMax) && (x2 > ctx.bbox.xMin)) {
//Perform subtexel pre-stepping on UV
dx = 1 - (_xa - x1);
u = _ua + dx * _dudx;
v = _va + dx * _dvdx;
- buf = dbuf + ((y * surface->stride) + x1);
+ buf = dbuf + ((y * ctx.surface->stride) + x1);
x = x1;
- if (matting) cmp = &surface->compositor->image.buf8[(y * surface->compositor->image.stride + x1) * csize];
+ if (matting) cmp = &ctx.surface->compositor->image.buf8[(y * ctx.surface->compositor->image.stride + x1) * csize];
//Draw horizontal line
while (x++ < x2) {
uu = (int) u;
vv = (int) v;
- if ((uint32_t) uu >= image.w || (uint32_t) vv >= image.h) continue;
+ if ((uint32_t)uu >= ctx.image.w || (uint32_t)vv >= ctx.image.h) continue;
ar = _modf(u);
ab = _modf(v);
iru = uu + 1;
irv = vv + 1;
- px = *(sbuf + (vv * image.stride) + uu);
+ px = *(sbuf + (vv * ctx.image.stride) + uu);
- if (image.filter == FilterMethod::Bilinear) {
+ if (ctx.image.filter == FilterMethod::Bilinear) {
// horizontal interpolate
if (iru < sw) {
- int px2 = *(sbuf + (vv * image.stride) + iru);
+ int px2 = *(sbuf + (vv * ctx.image.stride) + iru);
px = INTERPOLATE(px, px2, ar);
}
// vertical interpolate
if (irv < sh) {
- int px2 = *(sbuf + (irv * image.stride) + uu);
+ int px2 = *(sbuf + (irv * ctx.image.stride) + uu);
// horizontal interpolate
if (iru < sw) {
- int px3 = *(sbuf + (irv * image.stride) + iru);
+ int px3 = *(sbuf + (irv * ctx.image.stride) + iru);
px2 = INTERPOLATE(px2, px3, ar);
}
px = INTERPOLATE(px, px2, ab);
@@ -247,10 +248,10 @@ static void _rasterPolygonImageSegment32(SwSurface* surface, const SwImage& imag
uint32_t src;
if (matting) {
auto a = alpha(cmp);
- src = fullOpacity ? ALPHA_BLEND(px, a) : ALPHA_BLEND(px, MULTIPLY(opacity, a));
+ src = fullOpacity ? ALPHA_BLEND(px, a) : ALPHA_BLEND(px, MULTIPLY(ctx.opacity, a));
cmp += csize;
} else {
- src = fullOpacity ? px : ALPHA_BLEND(px, opacity);
+ src = fullOpacity ? px : ALPHA_BLEND(px, ctx.opacity);
}
// anti-aliasing
@@ -276,50 +277,50 @@ static void _rasterPolygonImageSegment32(SwSurface* surface, const SwImage& imag
++y;
}
- xa = _xa;
- xb = _xb;
- ua = _ua;
- va = _va;
+ ctx.xa = _xa;
+ ctx.xb = _xb;
+ ctx.ua = _ua;
+ ctx.va = _va;
}
// no anti-aliasing, no interpolation for the fastest cheap masking
-static void _rasterPolygonImageSegment8(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int yStart, int yEnd, uint8_t opacity, TVG_UNUSED bool needAA)
+static void _rasterPolygonImageSegment8(TexmapCtx& ctx, int yStart, int yEnd, TVG_UNUSED bool needAA)
{
- auto _dudx = dudx, _dvdx = dvdx;
- auto _dxdya = dxdya, _dxdyb = dxdyb, _dudya = dudya, _dvdya = dvdya;
- auto _xa = xa, _xb = xb, _ua = ua, _va = va;
- auto sbuf = image.buf32;
- auto dbuf = surface->buf8;
+ auto _dudx = ctx.dudx, _dvdx = ctx.dvdx;
+ auto _dxdya = ctx.dxdya, _dxdyb = ctx.dxdyb, _dudya = ctx.dudya, _dvdya = ctx.dvdya;
+ auto _xa = ctx.xa, _xb = ctx.xb, _ua = ctx.ua, _va = ctx.va;
+ auto sbuf = ctx.image.buf32;
+ auto dbuf = ctx.surface->buf8;
int32_t x1, x2, x, y;
float dx, u, v;
uint8_t* buf;
uint8_t px;
- if (yStart < bbox.min.y) yStart = bbox.min.y;
- if (yEnd > bbox.max.y) yEnd = bbox.max.y;
+ if (yStart < ctx.bbox.yMin) yStart = ctx.bbox.yMin;
+ if (yEnd > ctx.bbox.yMax) yEnd = ctx.bbox.yMax;
y = yStart;
while (y < yEnd) {
- x1 = std::max((int32_t)_xa, bbox.min.x);
- x2 = std::min((int32_t)_xb, bbox.max.x);
+ x1 = std::max((int32_t)_xa, ctx.bbox.xMin);
+ x2 = std::min((int32_t)_xb, ctx.bbox.xMax);
//Range allowed
- if ((x2 - x1) >= 1 && (x1 < bbox.max.x) && (x2 > bbox.min.x)) {
+ if ((x2 - x1) >= 1 && (x1 < ctx.bbox.xMax) && (x2 > ctx.bbox.xMin)) {
//Perform subtexel pre-stepping on UV
dx = 1 - (_xa - x1);
u = _ua + dx * _dudx;
v = _va + dx * _dvdx;
- buf = dbuf + ((y * surface->stride) + x1);
+ buf = dbuf + ((y * ctx.surface->stride) + x1);
x = x1;
//Draw horizontal line
while (x++ < x2) {
auto uu = (int) u;
auto vv = (int) v;
- if ((uint32_t) uu >= image.w || (uint32_t) vv >= image.h) continue;
+ if ((uint32_t)uu >= ctx.image.w || (uint32_t)vv >= ctx.image.h) continue;
- px = A(*(sbuf + (vv * image.stride) + uu));
- *buf = MULTIPLY(px, opacity);
+ px = A(*(sbuf + (vv * ctx.image.stride) + uu));
+ *buf = MULTIPLY(px, ctx.opacity);
++buf;
//Step UV horizontally
u += _dudx;
@@ -333,22 +334,21 @@ static void _rasterPolygonImageSegment8(SwSurface* surface, const SwImage& image
_va += _dvdya;
++y;
}
- xa = _xa;
- xb = _xb;
- ua = _ua;
- va = _va;
+ ctx.xa = _xa;
+ ctx.xb = _xb;
+ ctx.ua = _ua;
+ ctx.va = _va;
}
-
-static void _rasterPolygonImageSegment(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, int yStart, int yEnd, uint8_t opacity, bool matting, bool needAA)
+static void _rasterPolygonImageSegment(TexmapCtx& ctx, int yStart, int yEnd, bool matting, bool needAA)
{
- if (surface->channelSize == sizeof(uint32_t)) _rasterPolygonImageSegment32(surface, image, bbox, yStart, yEnd, opacity, matting, needAA);
- else if (surface->channelSize == sizeof(uint8_t)) _rasterPolygonImageSegment8(surface, image, bbox, yStart, yEnd, opacity, needAA);
+ if (ctx.surface->channelSize == sizeof(uint32_t)) _rasterPolygonImageSegment32(ctx, yStart, yEnd, matting, needAA);
+ else if (ctx.surface->channelSize == sizeof(uint8_t)) _rasterPolygonImageSegment8(ctx, yStart, yEnd, needAA);
}
/* This mapping algorithm is based on Mikael Kalms's. */
-static void _rasterPolygonImage(SwSurface* surface, const SwImage& image, const RenderRegion& bbox, Polygon& polygon, uint8_t opacity, bool needAA)
+static void _rasterPolygonImage(TexmapCtx& ctx, Polygon& polygon, bool needAA)
{
float x[3] = {polygon.vertex[0].pt.x, polygon.vertex[1].pt.x, polygon.vertex[2].pt.x};
float y[3] = {polygon.vertex[0].pt.y, polygon.vertex[1].pt.y, polygon.vertex[2].pt.y};
@@ -393,8 +393,8 @@ static void _rasterPolygonImage(SwSurface* surface, const SwImage& image, const
if (tvg::zero(denom)) return;
denom = 1 / denom; //Reciprocal for speeding up
- dudx = ((u[2] - u[0]) * (y[1] - y[0]) - (u[1] - u[0]) * (y[2] - y[0])) * denom;
- dvdx = ((v[2] - v[0]) * (y[1] - y[0]) - (v[1] - v[0]) * (y[2] - y[0])) * denom;
+ ctx.dudx = ((u[2] - u[0]) * (y[1] - y[0]) - (u[1] - u[0]) * (y[2] - y[0])) * denom;
+ ctx.dvdx = ((v[2] - v[0]) * (y[1] - y[0]) - (v[1] - v[0]) * (y[2] - y[0])) * denom;
auto dudy = ((u[1] - u[0]) * (x[2] - x[0]) - (u[2] - u[0]) * (x[1] - x[0])) * denom;
auto dvdy = ((v[1] - v[0]) * (x[2] - x[0]) - (v[2] - v[0]) * (x[1] - x[0])) * denom;
@@ -409,115 +409,115 @@ static void _rasterPolygonImage(SwSurface* surface, const SwImage& image, const
if (tvg::equal(y[0], y[1])) side = x[0] > x[1];
if (tvg::equal(y[1], y[2])) side = x[2] > x[1];
- auto compositing = _compositing(surface); //Composition required
- auto blending = _blending(surface); //Blending required
+ auto compositing = _compositing(ctx.surface); // Composition required
+ auto blending = _blending(ctx.surface); // Blending required
//Longer edge is on the left side
if (!side) {
//Calculate slopes along left edge
- dxdya = dxdy[1];
- dudya = dxdya * dudx + dudy;
- dvdya = dxdya * dvdx + dvdy;
+ ctx.dxdya = dxdy[1];
+ ctx.dudya = ctx.dxdya * ctx.dudx + dudy;
+ ctx.dvdya = ctx.dxdya * ctx.dvdx + dvdy;
//Perform subpixel pre-stepping along left edge
auto dy = 1.0f - (y[0] - yi[0]);
- xa = x[0] + dy * dxdya;
- ua = u[0] + dy * dudya;
- va = v[0] + dy * dvdya;
+ ctx.xa = x[0] + dy * ctx.dxdya;
+ ctx.ua = u[0] + dy * ctx.dudya;
+ ctx.va = v[0] + dy * ctx.dvdya;
//Draw upper segment if possibly visible
if (yi[0] < yi[1]) {
- off_y = y[0] < bbox.min.y ? (bbox.min.y - y[0]) : 0;
- xa += (off_y * dxdya);
- ua += (off_y * dudya);
- va += (off_y * dvdya);
+ off_y = y[0] < ctx.bbox.yMin ? (ctx.bbox.yMin - y[0]) : 0;
+ ctx.xa += (off_y * ctx.dxdya);
+ ctx.ua += (off_y * ctx.dudya);
+ ctx.va += (off_y * ctx.dvdya);
// Set right edge X-slope and perform subpixel pre-stepping
- dxdyb = dxdy[0];
- xb = x[0] + dy * dxdyb + (off_y * dxdyb);
+ ctx.dxdyb = dxdy[0];
+ ctx.xb = x[0] + dy * ctx.dxdyb + (off_y * ctx.dxdyb);
if (compositing) {
- if (_matting(surface)) _rasterPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, true, needAA);
- else _rasterMaskedPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, needAA);
+ if (_matting(ctx.surface)) _rasterPolygonImageSegment(ctx, yi[0], yi[1], true, needAA);
+ else _rasterMaskedPolygonImageSegment(ctx, yi[0], yi[1], needAA);
} else if (blending) {
- _rasterBlendingPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, needAA);
+ _rasterBlendingPolygonImageSegment(ctx, yi[0], yi[1], needAA);
} else {
- _rasterPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, false, needAA);
+ _rasterPolygonImageSegment(ctx, yi[0], yi[1], false, needAA);
}
upper = true;
}
//Draw lower segment if possibly visible
if (yi[1] < yi[2]) {
- off_y = y[1] < bbox.min.y ? (bbox.min.y - y[1]) : 0;
+ off_y = y[1] < ctx.bbox.yMin ? (ctx.bbox.yMin - y[1]) : 0;
if (!upper) {
- xa += (off_y * dxdya);
- ua += (off_y * dudya);
- va += (off_y * dvdya);
+ ctx.xa += (off_y * ctx.dxdya);
+ ctx.ua += (off_y * ctx.dudya);
+ ctx.va += (off_y * ctx.dvdya);
}
// Set right edge X-slope and perform subpixel pre-stepping
- dxdyb = dxdy[2];
- xb = x[1] + (1 - (y[1] - yi[1])) * dxdyb + (off_y * dxdyb);
+ ctx.dxdyb = dxdy[2];
+ ctx.xb = x[1] + (1 - (y[1] - yi[1])) * ctx.dxdyb + (off_y * ctx.dxdyb);
if (compositing) {
- if (_matting(surface)) _rasterPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, true, needAA);
- else _rasterMaskedPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, needAA);
+ if (_matting(ctx.surface)) _rasterPolygonImageSegment(ctx, yi[1], yi[2], true, needAA);
+ else _rasterMaskedPolygonImageSegment(ctx, yi[1], yi[2], needAA);
} else if (blending) {
- _rasterBlendingPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, needAA);
+ _rasterBlendingPolygonImageSegment(ctx, yi[1], yi[2], needAA);
} else {
- _rasterPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, false, needAA);
+ _rasterPolygonImageSegment(ctx, yi[1], yi[2], false, needAA);
}
}
//Longer edge is on the right side
} else {
//Set right edge X-slope and perform subpixel pre-stepping
- dxdyb = dxdy[1];
+ ctx.dxdyb = dxdy[1];
auto dy = 1.0f - (y[0] - yi[0]);
- xb = x[0] + dy * dxdyb;
+ ctx.xb = x[0] + dy * ctx.dxdyb;
//Draw upper segment if possibly visible
if (yi[0] < yi[1]) {
- off_y = y[0] < bbox.min.y ? (bbox.min.y - y[0]) : 0;
- xb += (off_y *dxdyb);
+ off_y = y[0] < ctx.bbox.yMin ? (ctx.bbox.yMin - y[0]) : 0;
+ ctx.xb += (off_y * ctx.dxdyb);
// Set slopes along left edge and perform subpixel pre-stepping
- dxdya = dxdy[0];
- dudya = dxdya * dudx + dudy;
- dvdya = dxdya * dvdx + dvdy;
+ ctx.dxdya = dxdy[0];
+ ctx.dudya = ctx.dxdya * ctx.dudx + dudy;
+ ctx.dvdya = ctx.dxdya * ctx.dvdx + dvdy;
- xa = x[0] + dy * dxdya + (off_y * dxdya);
- ua = u[0] + dy * dudya + (off_y * dudya);
- va = v[0] + dy * dvdya + (off_y * dvdya);
+ ctx.xa = x[0] + dy * ctx.dxdya + (off_y * ctx.dxdya);
+ ctx.ua = u[0] + dy * ctx.dudya + (off_y * ctx.dudya);
+ ctx.va = v[0] + dy * ctx.dvdya + (off_y * ctx.dvdya);
if (compositing) {
- if (_matting(surface)) _rasterPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, true, needAA);
- else _rasterMaskedPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, needAA);
+ if (_matting(ctx.surface)) _rasterPolygonImageSegment(ctx, yi[0], yi[1], true, needAA);
+ else _rasterMaskedPolygonImageSegment(ctx, yi[0], yi[1], needAA);
} else if (blending) {
- _rasterBlendingPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, needAA);
+ _rasterBlendingPolygonImageSegment(ctx, yi[0], yi[1], needAA);
} else {
- _rasterPolygonImageSegment(surface, image, bbox, yi[0], yi[1], opacity, false, needAA);
+ _rasterPolygonImageSegment(ctx, yi[0], yi[1], false, needAA);
}
upper = true;
}
//Draw lower segment if possibly visible
if (yi[1] < yi[2]) {
- off_y = y[1] < bbox.min.y ? (bbox.min.y - y[1]) : 0;
- if (!upper) xb += (off_y *dxdyb);
+ off_y = y[1] < ctx.bbox.yMin ? (ctx.bbox.yMin - y[1]) : 0;
+ if (!upper) ctx.xb += (off_y * ctx.dxdyb);
// Set slopes along left edge and perform subpixel pre-stepping
- dxdya = dxdy[2];
- dudya = dxdya * dudx + dudy;
- dvdya = dxdya * dvdx + dvdy;
+ ctx.dxdya = dxdy[2];
+ ctx.dudya = ctx.dxdya * ctx.dudx + dudy;
+ ctx.dvdya = ctx.dxdya * ctx.dvdx + dvdy;
dy = 1 - (y[1] - yi[1]);
- xa = x[1] + dy * dxdya + (off_y * dxdya);
- ua = u[1] + dy * dudya + (off_y * dudya);
- va = v[1] + dy * dvdya + (off_y * dvdya);
+ ctx.xa = x[1] + dy * ctx.dxdya + (off_y * ctx.dxdya);
+ ctx.ua = u[1] + dy * ctx.dudya + (off_y * ctx.dudya);
+ ctx.va = v[1] + dy * ctx.dvdya + (off_y * ctx.dvdya);
if (compositing) {
- if (_matting(surface)) _rasterPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, true, needAA);
- else _rasterMaskedPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, needAA);
+ if (_matting(ctx.surface)) _rasterPolygonImageSegment(ctx, yi[1], yi[2], true, needAA);
+ else _rasterMaskedPolygonImageSegment(ctx, yi[1], yi[2], needAA);
} else if (blending) {
- _rasterBlendingPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, needAA);
+ _rasterBlendingPolygonImageSegment(ctx, yi[1], yi[2], needAA);
} else {
- _rasterPolygonImageSegment(surface, image, bbox, yi[1], yi[2], opacity, false, needAA);
+ _rasterPolygonImageSegment(ctx, yi[1], yi[2], false, needAA);
}
}
}
@@ -539,6 +539,7 @@ static void _rasterPolygonImage(SwSurface* surface, const SwImage& image, const
bool rasterTexmapPolygon(SwSurface* surface, const SwImage& image, const Matrix& transform, const RenderRegion& bbox, uint8_t opacity)
{
//Prepare vertices. Shift XY coordinates to match the sub-pixeling technique.
+ TexmapCtx ctx = {surface, image, bbox, opacity};
Vertex vertices[4];
vertices[0] = {{0.0f, 0.0f}, {0.0f, 0.0f}};
vertices[1] = {{float(image.w), 0.0f}, {float(image.w), 0.0f}};
@@ -561,14 +562,14 @@ bool rasterTexmapPolygon(SwSurface* surface, const SwImage& image, const Matrix&
polygon.vertex[1] = vertices[1];
polygon.vertex[2] = vertices[3];
- _rasterPolygonImage(surface, image, bbox, polygon, opacity, needAA);
+ _rasterPolygonImage(ctx, polygon, needAA);
//Draw the second polygon
polygon.vertex[0] = vertices[1];
polygon.vertex[1] = vertices[2];
polygon.vertex[2] = vertices[3];
- _rasterPolygonImage(surface, image, bbox, polygon, opacity, needAA);
+ _rasterPolygonImage(ctx, polygon, needAA);
#if 0
if (_compositing(surface) && _masking(surface) && !_direct(surface->compositor->method)) {
@@ -577,4 +578,3 @@ bool rasterTexmapPolygon(SwSurface* surface, const SwImage& image, const Matrix&
#endif
return true;
}
-
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRenderer.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRenderer.cpp
similarity index 80%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwRenderer.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRenderer.cpp
index 8ca9acade7a..2baed67703d 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRenderer.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRenderer.cpp
@@ -20,26 +20,20 @@
* SOFTWARE.
*/
-#include <algorithm>
#include "tvgSwCommon.h"
#include "tvgTaskScheduler.h"
#include "tvgSwRenderer.h"
-#ifdef THORVG_OPENMP_SUPPORT
- #include <omp.h>
-#endif
-
/************************************************************************/
/* Internal Class Implementation */
/************************************************************************/
static int32_t _rendererCnt = -1;
-static mutex _rendererMtx;
+static StrictKey _rendererMtx;
struct SwTask : Task
{
- SwSurface* surface = nullptr;
- SwMpool* mpool = nullptr;
+ SwRenderer* renderer;
RenderRegion clipBox; //clipping region applied to the task, may differ from curBox which is the actual rendering region
RenderRegion curBox{}; //current rendering region
RenderRegion prvBox{}; //previous rendering region
@@ -63,8 +57,8 @@ struct SwTask : Task
void invisible()
{
- curBox.reset();
- if (!nodirty) dirtyRegion->add(prvBox, curBox);
+ valid = false;
+ if (!nodirty) dirtyRegion->add(prvBox, {});
}
bool ready(bool condition)
@@ -80,7 +74,13 @@ struct SwTask : Task
return false;
}
- virtual void dispose() = 0;
+ bool complete()
+ {
+ prvBox = valid ? curBox : RenderRegion{};
+ nodirty = false;
+ return true;
+ }
+
virtual bool clip(SwRle* target) = 0;
virtual ~SwTask() {}
};
@@ -92,13 +92,18 @@ struct SwShapeTask : SwTask
const RenderShape* rshape = nullptr;
bool clipper = false;
+ ~SwShapeTask()
+ {
+ shapeFree(shape);
+ }
+
/* We assume that if the stroke width is greater than 2,
the shape's outline beneath the stroke could be adequately covered by the stroke drawing.
Therefore, antialiasing is disabled under this condition.
Additionally, the stroke style should not be dashed. */
bool antialiasing(float strokeWidth)
{
- return strokeWidth < 2.0f || rshape->stroke->dash.count > 0 || rshape->stroke->first || rshape->trimpath() || rshape->stroke->color.a < 255;
+ return renderer->antiAlias && (strokeWidth < 2.0f || rshape->stroke->dash.count > 0 || rshape->stroke->first || rshape->trimpath() || rshape->stroke->color.a < 255);
}
float validStrokeWidth(bool clipper)
@@ -111,9 +116,11 @@ struct SwShapeTask : SwTask
bool clip(SwRle* target) override
{
- if (shape.strokeRle) return rleClip(target, shape.strokeRle);
- if (shape.fastTrack) return rleClip(target, &curBox);
- if (shape.rle) return rleClip(target, shape.rle);
+ if (target) {
+ if (shape.strokeRle) return rleClip(target, shape.strokeRle);
+ if (shape.fastTrack) return rleClip(target, &curBox);
+ if (shape.rle) return rleClip(target, shape.rle);
+ }
return false;
}
@@ -121,15 +128,14 @@ struct SwShapeTask : SwTask
{
auto strokeWidth = validStrokeWidth(clipper);
auto updateShape = flags[0] & (RenderUpdateFlag::Path | RenderUpdateFlag::Transform | RenderUpdateFlag::Clip);
- auto updateFill = (flags[0] & (RenderUpdateFlag::Color | RenderUpdateFlag::Gradient));
+ auto updateFill = flags[0] & (RenderUpdateFlag::Color | RenderUpdateFlag::Gradient | RenderUpdateFlag::Transform);
//Shape
if (updateShape) {
shapeReset(shape);
if (rshape->fill || rshape->color.a > 0 || clipper) {
- if (shapePrepare(shape, rshape, transform, clipBox, curBox, mpool, tid, clips.count > 0 ? true : false)) {
- if (!shapeGenRle(shape, curBox, mpool, tid, antialiasing(strokeWidth))) goto err;
- } else {
+ auto composite = clips.count > 0 ? true : false;
+ if (!shapeGenRle(shape, rshape, transform, clipBox, curBox, renderer->mpool, tid, composite, antialiasing(strokeWidth))) {
updateFill = false;
curBox.reset();
}
@@ -137,53 +143,39 @@ struct SwShapeTask : SwTask
}
//Fill
if (updateFill) {
- if (auto fill = rshape->fill) {
- auto ctable = (flags[0] & RenderUpdateFlag::Gradient) ? true : false;
- if (ctable) shapeResetFill(shape);
- if (!shapeGenFillColors(shape, fill, transform, surface, opacity, ctable)) goto err;
- }
+ if (!fillPrepare(shape.fill, rshape->fill, transform, renderer->surface, opacity, (flags[0] & RenderUpdateFlag::Gradient))) goto dismiss;
}
//Stroke
- if (updateShape || flags[0] & RenderUpdateFlag::Stroke) {
- if (strokeWidth > 0.0f) {
- shapeResetStroke(shape, rshape, transform, mpool, tid);
- if (!shapeGenStrokeRle(shape, rshape, transform, clipBox, curBox, mpool, tid)) goto err;
- if (auto fill = rshape->strokeFill()) {
- auto ctable = (flags[0] & RenderUpdateFlag::GradientStroke) ? true : false;
- if (ctable) shapeResetStrokeFill(shape);
- if (!shapeGenStrokeFillColors(shape, fill, transform, surface, opacity, ctable)) goto err;
- }
- } else {
- shapeDelStroke(shape);
+ if (strokeWidth > 0.0f) {
+ auto updateStroke = updateShape || (flags[0] & RenderUpdateFlag::Stroke);
+ if (updateStroke && !shapeGenStrokeRle(shape, rshape, transform, clipBox, curBox, renderer->mpool, tid, renderer->antiAlias)) goto dismiss;
+ auto ctable = flags[0] & RenderUpdateFlag::GradientStroke;
+ if (ctable || flags[0] & RenderUpdateFlag::Transform) {
+ if (!fillPrepare(shape.stroke->fill, rshape->strokeFill(), transform, renderer->surface, opacity, ctable)) goto dismiss;
}
+ } else {
+ shapeDelStroke(shape);
}
- //Clear current task memorypool here if the clippers would use the same memory pool
- shapeDelOutline(shape, mpool, tid);
+ shapeDelOutline(shape);
//Clip Path
ARRAY_FOREACH(p, clips) {
auto clipper = static_cast<SwTask*>(*p);
- auto clipShapeRle = shape.rle ? clipper->clip(shape.rle) : true;
- auto clipStrokeRle = shape.strokeRle ? clipper->clip(shape.strokeRle) : true;
- if (!clipShapeRle || !clipStrokeRle) goto err;
+ auto clipShape = clipper->clip(shape.rle);
+ auto clipStroke = clipper->clip(shape.strokeRle);
+ if (!clipShape && !clipStroke) goto dismiss;
}
valid = true;
if (!nodirty) dirtyRegion->add(prvBox, curBox);
return;
- err:
+ dismiss:
shapeReset(shape);
rleReset(shape.strokeRle);
- shapeDelOutline(shape, mpool, tid);
invisible();
}
-
- void dispose() override
- {
- shapeFree(shape);
- }
};
@@ -192,6 +184,11 @@ struct SwImageTask : SwTask
SwImage image;
RenderSurface* source; //Image source
+ ~SwImageTask()
+ {
+ imageFree(image);
+ }
+
bool clip(SwRle* target) override
{
TVGERR("SW_ENGINE", "Image is used as ClipPath?");
@@ -201,14 +198,15 @@ struct SwImageTask : SwTask
void run(unsigned tid) override
{
//Convert colorspace if it's not aligned.
- rasterConvertCS(source, surface->cs);
- rasterPremultiply(source);
+ rasterConvertCS(source, renderer->surface->cs);
+ rasterPremultiplySurface(source);
image.data = source->data;
image.w = source->w;
image.h = source->h;
image.stride = source->stride;
image.channelSize = source->channelSize;
+ image.alphaIgnored = source->opaque;
auto updateImage = flags[0] & (RenderUpdateFlag::Image | RenderUpdateFlag::Clip | RenderUpdateFlag::Transform);
auto updateColor = flags[0] & (RenderUpdateFlag::Color);
@@ -217,13 +215,11 @@ struct SwImageTask : SwTask
if ((updateImage || updateColor) && (opacity > 0)) {
if (updateImage) imageReset(image);
if (!image.data || image.w == 0 || image.h == 0) goto err;
- if (!imagePrepare(image, transform, clipBox, curBox, mpool, tid)) goto err;
+ if (!imagePrepare(image, transform, clipBox, curBox, renderer->mpool, tid)) goto err;
valid = true;
if (clips.count > 0) {
- if (!imageGenRle(image, curBox, mpool, tid, false)) goto err;
+ if (!imageGenRle(image, curBox, renderer->mpool, tid, false)) goto err;
if (image.rle) {
- //Clear current task memorypool here if the clippers would use the same memory pool
- imageDelOutline(image, mpool, tid);
ARRAY_FOREACH(p, clips) {
auto clipper = static_cast<SwTask*>(*p);
if (!clipper->clip(image.rle)) goto err;
@@ -238,14 +234,8 @@ struct SwImageTask : SwTask
curBox.reset();
imageReset(image);
end:
- imageDelOutline(image, mpool, tid);
if (!nodirty) dirtyRegion->add(prvBox, curBox);
}
-
- void dispose() override
- {
- imageFree(image);
- }
};
@@ -279,21 +269,25 @@ bool SwRenderer::sync()
{
//clear if the rendering was not triggered.
ARRAY_FOREACH(p, tasks) {
+ (*p)->done();
if ((*p)->disposed) delete(*p);
- else {
- (*p)->done();
- (*p)->pushed = false;
- }
+ else (*p)->pushed = false;
}
tasks.clear();
+ if (rendered) {
+ dirtyRegion.clear();
+ fulldraw = false;
+ rendered = false;
+ }
+
return true;
}
-
-bool SwRenderer::target(pixel_t* data, uint32_t stride, uint32_t w, uint32_t h, ColorSpace cs)
+Result SwRenderer::target(pixel_t* data, uint32_t stride, uint32_t w, uint32_t h, ColorSpace cs)
{
- if (!data || stride == 0 || w == 0 || h == 0 || w > stride) return false;
+ if (!data || stride == 0 || w == 0 || h == 0 || w > stride) return Result::InvalidArguments;
+ if (cs != ColorSpace::ABGR8888 && cs != ColorSpace::ABGR8888S && cs != ColorSpace::ARGB8888 && cs != ColorSpace::ARGB8888S) return Result::NonSupport;
clearCompositors();
@@ -363,12 +357,10 @@ bool SwRenderer::postRender()
{
//Unmultiply alpha if needed
if (surface->cs == ColorSpace::ABGR8888S || surface->cs == ColorSpace::ARGB8888S) {
- rasterUnpremultiply(surface);
+ rasterUnpremultiplySurface(surface);
}
- dirtyRegion.clear();
- fulldraw = false;
-
+ rendered = true;
return true;
}
@@ -386,6 +378,27 @@ bool SwRenderer::partial(bool disable)
return dirtyRegion.deactivate(disable);
}
+uint32_t SwRenderer::dirtyRegions() const
+{
+ return (fulldraw || dirtyRegion.deactivated()) ? 1 : dirtyRegion.count();
+}
+
+Result SwRenderer::dirtyRegions(Region* regions, uint32_t cnt) const
+{
+ if (fulldraw || dirtyRegion.deactivated()) {
+ *regions = {0, 0, int32_t(surface->w), int32_t(surface->h)};
+ return Result::Success;
+ }
+
+ for (int idx = 0; idx < RenderDirtyRegion::PARTITIONING; ++idx) {
+ ARRAY_FOREACH(p, dirtyRegion.get(idx)) {
+ *regions++ = *p;
+ if (--cnt == 0) return Result::Success;
+ }
+ }
+
+ return Result::Success;
+}
bool SwRenderer::renderImage(RenderData data)
{
@@ -427,7 +440,7 @@ bool SwRenderer::renderImage(RenderData data)
for (int idx = 0; idx < RenderDirtyRegion::PARTITIONING; ++idx) {
if (!dirtyRegion.partition(idx).intersected(task->curBox)) continue;
ARRAY_FOREACH(p, dirtyRegion.get(idx)) {
- if (task->curBox.max.x <= p->min.x) break; //dirtyRegion is sorted in x order
+ if (task->curBox.xMax <= p->xMin) break; // dirtyRegion is sorted in x order
if (task->curBox.intersected(*p)) {
auto bbox = RenderRegion::intersect(task->curBox, *p);
raster(surface, task->image, task->transform, bbox, task->opacity);
@@ -436,8 +449,7 @@ bool SwRenderer::renderImage(RenderData data)
}
}
}
- task->prvBox = task->curBox;
- return true;
+ return task->complete();
}
@@ -484,7 +496,7 @@ bool SwRenderer::renderShape(RenderData data)
for (int idx = 0; idx < RenderDirtyRegion::PARTITIONING; ++idx) {
if (!dirtyRegion.partition(idx).intersected(task->curBox)) continue;
ARRAY_FOREACH(p, dirtyRegion.get(idx)) {
- if (task->curBox.max.x <= p->min.x) break; //dirtyRegion is sorted in x order
+ if (task->curBox.xMax <= p->xMin) break; // dirtyRegion is sorted in x order
if (task->rshape->strokeFirst()) {
if (task->rshape->stroke && task->curBox.intersected(*p)) stroke(task, surface, RenderRegion::intersect(task->curBox, *p));
if (task->shape.bbox.intersected(*p)) fill(task, surface, RenderRegion::intersect(task->shape.bbox, *p));
@@ -496,8 +508,7 @@ bool SwRenderer::renderShape(RenderData data)
}
}
}
- task->prvBox = task->curBox;
- return true;
+ return task->complete();
}
@@ -508,52 +519,52 @@ bool SwRenderer::blend(BlendMethod method)
switch (method) {
case BlendMethod::Multiply:
- surface->blender = opBlendMultiply;
+ surface->blender = blendMultiply;
break;
case BlendMethod::Screen:
- surface->blender = opBlendScreen;
+ surface->blender = blendScreen;
break;
case BlendMethod::Overlay:
- surface->blender = opBlendOverlay;
+ surface->blender = blendOverlay;
break;
case BlendMethod::Darken:
- surface->blender = opBlendDarken;
+ surface->blender = blendDarken;
break;
case BlendMethod::Lighten:
- surface->blender = opBlendLighten;
+ surface->blender = blendLighten;
break;
case BlendMethod::ColorDodge:
- surface->blender = opBlendColorDodge;
+ surface->blender = blendColorDodge;
break;
case BlendMethod::ColorBurn:
- surface->blender = opBlendColorBurn;
+ surface->blender = blendColorBurn;
break;
case BlendMethod::HardLight:
- surface->blender = opBlendHardLight;
+ surface->blender = blendHardLight;
break;
case BlendMethod::SoftLight:
- surface->blender = opBlendSoftLight;
+ surface->blender = blendSoftLight;
break;
case BlendMethod::Difference:
- surface->blender = opBlendDifference;
+ surface->blender = blendDifference;
break;
case BlendMethod::Exclusion:
- surface->blender = opBlendExclusion;
+ surface->blender = blendExclusion;
break;
case BlendMethod::Hue:
- surface->blender = opBlendHue;
+ surface->blender = blendHue;
break;
case BlendMethod::Saturation:
- surface->blender = opBlendSaturation;
+ surface->blender = blendSaturation;
break;
case BlendMethod::Color:
- surface->blender = opBlendColor;
+ surface->blender = blendColor;
break;
case BlendMethod::Luminosity:
- surface->blender = opBlendLuminosity;
+ surface->blender = blendLuminosity;
break;
case BlendMethod::Add:
- surface->blender = opBlendAdd;
+ surface->blender = blendAdd;
break;
default:
surface->blender = nullptr;
@@ -565,8 +576,7 @@ bool SwRenderer::blend(BlendMethod method)
RenderRegion SwRenderer::region(RenderData data)
{
- if (data) return static_cast<SwTask*>(data)->bounds();
- return {};
+ return data ? static_cast<SwTask*>(data)->bounds() : RenderRegion{};
}
@@ -643,7 +653,7 @@ SwSurface* SwRenderer::request(int channelSize, bool square)
RenderCompositor* SwRenderer::target(const RenderRegion& region, ColorSpace cs, CompositionFlag flags)
{
- auto bbox = RenderRegion::intersect(region, {{0, 0}, {int32_t(surface->w), int32_t(surface->h)}});
+ auto bbox = RenderRegion::intersect(region, {0, 0, int32_t(surface->w), int32_t(surface->h)});
if (bbox.invalid()) return nullptr;
auto cmp = request(CHANNEL_SIZE(cs), (flags & CompositionFlag::PostProcessing));
@@ -689,6 +699,7 @@ bool SwRenderer::endComposite(RenderCompositor* cmp)
void SwRenderer::prepare(RenderEffect* effect, const Matrix& transform)
{
switch (effect->type) {
+ case SceneEffect::MotionBlur: effectMotionBlurUpdate(static_cast<RenderEffectMotionBlur*>(effect), transform); break;
case SceneEffect::GaussianBlur: effectGaussianBlurUpdate(static_cast<RenderEffectGaussianBlur*>(effect), transform); break;
case SceneEffect::DropShadow: effectDropShadowUpdate(static_cast<RenderEffectDropShadow*>(effect), transform); break;
case SceneEffect::Fill: effectFillUpdate(static_cast<RenderEffectFill*>(effect)); break;
@@ -706,7 +717,7 @@ bool SwRenderer::bounds(RenderData data, Point* pt4, const Matrix& m)
auto task = static_cast<SwShapeTask*>(data);
task->done();
- return shapeStrokeBBox(task->shape, task->rshape, pt4, m, task->mpool);
+ return shapeStrokeBBox(task->shape, task->rshape, pt4, m, task->renderer->mpool);
}
@@ -717,7 +728,7 @@ bool SwRenderer::intersectsShape(RenderData data, const RenderRegion& region)
if (!task->valid || !task->bounds().intersected(region)) return false;
if (rleIntersect(task->shape.strokeRle, region)) return true;
- return task->shape.rle ? rleIntersect(task->shape.rle, region): task->shape.fastTrack;
+ return task->shape.fastTrack || rleIntersect(task->shape.rle, region);
}
@@ -732,10 +743,10 @@ bool SwRenderer::intersectsImage(RenderData data, const RenderRegion& region)
auto rad = tvg::radian(task->transform);
if (rad > 0.0f && rad < MATH_PI) {
Point aabb[4];
- aabb[0] = {(float)region.min.x, (float)region.min.y};
- aabb[1] = {(float)region.max.x, (float)region.min.y};
- aabb[2] = {(float)region.max.x, (float)region.max.y};
- aabb[3] = {(float)region.min.x, (float)region.max.y};
+ aabb[0] = {(float)region.xMin, (float)region.yMin};
+ aabb[1] = {(float)region.xMax, (float)region.yMin};
+ aabb[2] = {(float)region.xMax, (float)region.yMax};
+ aabb[3] = {(float)region.xMin, (float)region.yMax};
Point obb[4];
obb[0] = Point{0.0f, 0.0f} * task->transform;
@@ -768,6 +779,7 @@ bool SwRenderer::intersectsImage(RenderData data, const RenderRegion& region)
bool SwRenderer::region(RenderEffect* effect)
{
switch (effect->type) {
+ case SceneEffect::MotionBlur: return effectMotionBlurRegion(static_cast<RenderEffectMotionBlur*>(effect));
case SceneEffect::GaussianBlur: return effectGaussianBlurRegion(static_cast<RenderEffectGaussianBlur*>(effect));
case SceneEffect::DropShadow: return effectDropShadowRegion(static_cast<RenderEffectDropShadow*>(effect));
default: return false;
@@ -788,6 +800,9 @@ bool SwRenderer::render(RenderCompositor* cmp, const RenderEffect* effect, bool
if (p->recoverSfc->channelSize != sizeof(uint32_t)) direct = false;
switch (effect->type) {
+ case SceneEffect::MotionBlur: {
+ return effectMotionBlur(p, request(surface->channelSize, true), static_cast<const RenderEffectMotionBlur*>(effect));
+ }
case SceneEffect::GaussianBlur: {
return effectGaussianBlur(p, request(surface->channelSize, true), static_cast<const RenderEffectGaussianBlur*>(effect));
}
@@ -831,9 +846,6 @@ ColorSpace SwRenderer::colorSpace()
void SwRenderer::dispose(RenderData data)
{
auto task = static_cast<SwTask*>(data);
- task->done();
- task->dispose();
-
if (task->pushed) task->disposed = true;
else delete(task);
}
@@ -843,9 +855,8 @@ SwTask* SwRenderer::prepareCommon(SwTask* task, const Matrix& transform, const A
{
if (task->disposed) return task;
- task->surface = surface;
- task->mpool = mpool;
- task->clipBox = RenderRegion::intersect(vport, {{0, 0}, {int32_t(surface->w), int32_t(surface->h)}});
+ task->renderer = this;
+ task->clipBox = RenderRegion::intersect(vport, {0, 0, int32_t(surface->w), int32_t(surface->h)});
task->transform = transform;
task->clips = clips;
task->dirtyRegion = &dirtyRegion;
@@ -859,22 +870,20 @@ SwTask* SwRenderer::prepareCommon(SwTask* task, const Matrix& transform, const A
tasks.push(task);
}
- //TODO: Failed threading them. It would be better if it's possible.
- //See: https://github.com/thorvg/thorvg/issues/1409
- //Guarantee composition targets get ready.
- ARRAY_FOREACH(p, clips) {
- static_cast<SwTask*>(*p)->done();
- }
-
if (task->ready(ready)) return task;
- if (flags) TaskScheduler::request(task);
+ if (flags) {
+ // TODO: For deferred process, task scheduler dependency graph might be useful.
+ ARRAY_FOREACH(p, clips) {
+ static_cast<SwTask*>(*p)->done();
+ }
+ TaskScheduler::request(task);
+ }
return task;
}
-
-RenderData SwRenderer::prepare(RenderSurface* surface, RenderData data, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, FilterMethod filter, RenderUpdateFlag flags)
+RenderData SwRenderer::prepare(RenderSurface* surface, RenderData data, const Matrix& transform, const Array<RenderData>& clips, uint8_t opacity, FilterMethod filter, RenderUpdateFlag flags)
{
auto task = static_cast<SwImageTask*>(data);
if (task) task->done();
@@ -887,7 +896,7 @@ RenderData SwRenderer::prepare(RenderSurface* surface, RenderData data, const Ma
return prepareCommon(task, transform, clips, opacity, flags, (opacity == 0));
}
-RenderData SwRenderer::prepare(const RenderShape& rshape, RenderData data, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flags, bool clipper)
+RenderData SwRenderer::prepare(const RenderShape& rshape, RenderData data, const Matrix& transform, const Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flags, bool clipper)
{
auto task = static_cast<SwShapeTask*>(data);
if (task) task->done();
@@ -926,6 +935,7 @@ SwRenderer::SwRenderer(uint32_t threads, EngineOption op)
#ifdef THORVG_OPENMP_SUPPORT
omp_set_num_threads(threads);
#endif
+ rasterInit();
mpoolInit(threads);
_rendererCnt = 0;
}
@@ -934,5 +944,7 @@ SwRenderer::SwRenderer(uint32_t threads, EngineOption op)
mpool = mpoolReq();
- if (op == EngineOption::None) dirtyRegion.support = false;
+ auto byDefault = (op == EngineOption::Default);
+ dirtyRegion.support = (byDefault || (op & EngineOption::SmartRender));
+ antiAlias = (byDefault || !(op & EngineOption::Aliased));
}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRenderer.h b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRenderer.h
similarity index 82%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwRenderer.h
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRenderer.h
index 299a06f55d9..3c4055a77b3 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRenderer.h
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRenderer.h
@@ -37,8 +37,8 @@ struct SwRenderer : RenderMethod
{
//main features
bool preUpdate() override;
- RenderData prepare(const RenderShape& rshape, RenderData data, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flags, bool clipper) override;
- RenderData prepare(RenderSurface* surface, RenderData data, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, FilterMethod filter, RenderUpdateFlag flags) override;
+ RenderData prepare(const RenderShape& rshape, RenderData data, const Matrix& transform, const Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flags, bool clipper) override;
+ RenderData prepare(RenderSurface* surface, RenderData data, const Matrix& transform, const Array<RenderData>& clips, uint8_t opacity, FilterMethod filter, RenderUpdateFlag flags) override;
bool postUpdate() override;
bool preRender() override;
bool renderShape(RenderData data) override;
@@ -54,7 +54,7 @@ struct SwRenderer : RenderMethod
bool sync() override;
bool intersectsShape(RenderData data, const RenderRegion& region) override;
bool intersectsImage(RenderData data, const RenderRegion& region) override;
- bool target(pixel_t* data, uint32_t stride, uint32_t w, uint32_t h, ColorSpace cs);
+ Result target(pixel_t* data, uint32_t stride, uint32_t w, uint32_t h, ColorSpace cs);
//composition
SwSurface* request(int channelSize, bool square);
@@ -72,17 +72,22 @@ struct SwRenderer : RenderMethod
//partial rendering
void damage(RenderData rd, const RenderRegion& region) override;
bool partial(bool disable) override;
+ uint32_t dirtyRegions() const override;
+ Result dirtyRegions(Region* regions, uint32_t cnt) const override;
SwRenderer(uint32_t threads, EngineOption op);
static bool term();
+ SwSurface* surface = nullptr; // active surface
+ SwMpool* mpool; // designated memory pool
+ bool antiAlias; // anti-aliasing support
+
private:
- SwSurface* surface = nullptr; //active surface
+ bool fulldraw = true; //buffer is cleared (need to redraw full screen)
+ bool rendered = false; //draw completed and awaits sync
Array<SwTask*> tasks; //async task list
Array<SwSurface*> compositors; //render targets cache list
RenderDirtyRegion dirtyRegion; //partial rendering support
- SwMpool* mpool; // designated memory pool
- bool fulldraw = true; //buffer is cleared (need to redraw full screen)
~SwRenderer();
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRle.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRle.cpp
similarity index 86%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwRle.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRle.cpp
index 1aacae96399..3bc4b241c0b 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRle.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwRle.cpp
@@ -213,7 +213,7 @@ struct RleWorker
int32_t cellXCnt;
int32_t cellYCnt;
- Area area;
+ long area;
int32_t cover;
SwCell* cells;
@@ -222,11 +222,14 @@ struct RleWorker
SwPoint pos;
- SwPoint bezStack[32 * 3 + 1];
- SwPoint lineStack[32 + 1];
+#define BEZ_STACK_SIZE (32 * 3 + 1)
+ SwPoint bezStack[BEZ_STACK_SIZE];
+
+#define LINE_STACK_SIZE (32 + 1)
+ SwPoint lineStack[LINE_STACK_SIZE];
int levStack[32];
- SwOutline* outline;
+ const SwOutline* outline;
int bandSize;
int bandShoot;
@@ -277,16 +280,36 @@ static inline int32_t HYPOT(SwPoint pt)
return ((pt.x > pt.y) ? (pt.x + (3 * pt.y >> 3)) : (pt.y + (3 * pt.x >> 3)));
}
-
-// Used to prevent integer overflow when calculating the distance between points.
-// This function uses 64-bit arithmetic to safely compute the difference between coordinates.
-static inline uint32_t SAFE_HYPOT(SwPoint& pt1, SwPoint& pt2)
+static void _splitCubic(SwPoint* base)
{
- auto x = uint32_t(abs(int64_t(pt1.x) - int64_t(pt2.x)));
- auto y = uint32_t(abs(int64_t(pt1.y) - int64_t(pt2.y)));
- return (x > y) ? (x + (3 * y >> 3)) : (y + (3 * x >> 3));
+ int32_t a, b, c, d;
+
+ base[6].x = base[3].x;
+ c = base[1].x;
+ d = base[2].x;
+ base[1].x = a = (base[0].x + c) >> 1;
+ base[5].x = b = (base[3].x + d) >> 1;
+ c = (c + d) >> 1;
+ base[2].x = a = (a + c) >> 1;
+ base[4].x = b = (b + c) >> 1;
+ base[3].x = (a + b) >> 1;
+
+ base[6].y = base[3].y;
+ c = base[1].y;
+ d = base[2].y;
+ base[1].y = a = (base[0].y + c) >> 1;
+ base[5].y = b = (base[3].y + d) >> 1;
+ c = (c + d) >> 1;
+ base[2].y = a = (a + c) >> 1;
+ base[4].y = b = (b + c) >> 1;
+ base[3].y = (a + b) >> 1;
}
+static void _splitLine(SwPoint* base)
+{
+ base[2] = base[1];
+ base[1] = {(base[0].x >> 1) + (base[1].x >> 1), (base[0].y >> 1) + (base[1].y >> 1)};
+}
static void _horizLine(RleWorker& rw, int32_t x, int32_t y, int32_t area, int32_t aCount)
{
@@ -311,12 +334,6 @@ static void _horizLine(RleWorker& rw, int32_t x, int32_t y, int32_t area, int32_
if (coverage == 0) return;
- //span has ushort coordinates. check limit overflow
- if (x >= SHRT_MAX || y >= SHRT_MAX) {
- TVGERR("SW_ENGINE", "XY-coordinate overflow!");
- return;
- }
-
auto rle = rw.rle;
if (!rw.antiAlias) coverage = 255;
@@ -346,7 +363,7 @@ static void _horizLine(RleWorker& rw, int32_t x, int32_t y, int32_t area, int32_
if (aCount + xOver <= 0) return;
//add a span to the current list
- rle->spans.next() = {(uint16_t)x, (uint16_t)y, uint16_t(aCount + xOver), (uint8_t)coverage};
+ rle->spans.next() = {x, y, aCount + xOver, (uint8_t)coverage};
}
@@ -486,16 +503,20 @@ static bool _lineTo(RleWorker& rw, const SwPoint& to)
}
auto line = rw.lineStack;
+ auto end = line + LINE_STACK_SIZE;
line[0] = to;
line[1] = rw.pos;
- while (true) {
- if (SAFE_HYPOT(line[0], line[1]) > SHRT_MAX) {
- mathSplitLine(line);
+ while (line < end) {
+ auto diff = line[0] - line[1];
+
+ // avoid possible arithmetic overflow below by splitting
+ if (HYPOT(diff) > SHRT_MAX) {
+ _splitLine(line);
++line;
continue;
}
- auto diff = line[0] - line[1];
+
e1 = TRUNC(line[1]);
e2 = TRUNC(line[0]);
@@ -535,7 +556,7 @@ static bool _lineTo(RleWorker& rw, const SwPoint& to)
} else {
#define SW_UDIV(a, b) (int32_t)((uint64_t(a) * uint64_t(b)) >> 32)
- Area prod = diff.x * f1.y - diff.y * f1.x;
+ long prod = diff.x * f1.y - diff.y * f1.x;
/* These macros speed up repetitive divisions by replacing them
with multiplications and right shifts. */
@@ -595,12 +616,14 @@ static bool _lineTo(RleWorker& rw, const SwPoint& to)
if (line-- == rw.lineStack) return true;
}
+ return false;
}
static bool _cubicTo(RleWorker& rw, const SwPoint& ctrl1, const SwPoint& ctrl2, const SwPoint& to)
{
auto arc = rw.bezStack;
+ auto end = rw.bezStack + BEZ_STACK_SIZE;
arc[0] = to;
arc[1] = ctrl2;
arc[2] = ctrl1;
@@ -623,7 +646,7 @@ static bool _cubicTo(RleWorker& rw, const SwPoint& ctrl1, const SwPoint& ctrl2,
/* Evaluation for Recursive Subdivision of Bezier Curves' by Thomas */
/* F. Hain, at */
/* http://www.cis.southalabama.edu/~hain/general/Publications/Bezier/Camera-ready%20CISST02%202.pdf */
- while (true) {
+ while (arc < end) {
{
//diff is the P0 - P3 chord vector
auto diff = arc[3] - arc[0];
@@ -636,15 +659,11 @@ static bool _cubicTo(RleWorker& rw, const SwPoint& ctrl1, const SwPoint& ctrl2,
auto sLimit = L * (ONE_PIXEL / 6);
auto diff1 = arc[1] - arc[0];
- auto s = diff.y * diff1.x - diff.x * diff1.y;
- if (s < 0) s = -s;
- if (s > sLimit) goto split;
+ if (abs(diff.y * diff1.x - diff.x * diff1.y) > sLimit) goto split;
//s is L * the perpendicular distance from P2 to the line P0 - P3
auto diff2 = arc[2] - arc[0];
- s = diff.y * diff2.x - diff.x * diff2.y;
- if (s < 0) s = -s;
- if (s > sLimit) goto split;
+ if (abs(diff.y * diff2.x - diff.x * diff2.y) > sLimit) goto split;
/* Split super curvy segments where the off points are so far
from the chord that the angles P0-P1-P3 or P0-P2-P3 become
@@ -657,7 +676,7 @@ static bool _cubicTo(RleWorker& rw, const SwPoint& ctrl1, const SwPoint& ctrl2,
goto draw;
}
split:
- mathSplitCubic(arc);
+ _splitCubic(arc);
arc += 3;
continue;
@@ -666,48 +685,47 @@ static bool _cubicTo(RleWorker& rw, const SwPoint& ctrl1, const SwPoint& ctrl2,
if (arc == rw.bezStack) return true;
arc -= 3;
}
+ return false;
}
static bool _decomposeOutline(RleWorker& rw)
{
auto outline = rw.outline;
- auto first = 0; //index of first point in contour
-
- ARRAY_FOREACH(p, outline->cntrs) {
- auto last = *p;
- auto limit = outline->pts.data + last;
- auto start = UPSCALE(outline->pts[first]);
- auto pt = outline->pts.data + first;
- auto types = outline->types.data + first;
- ++types;
-
- if (!_moveTo(rw, UPSCALE(outline->pts[first]))) return false;
-
- while (pt < limit) {
- //emit a single line_to
- if (types[0] == SW_CURVE_TYPE_POINT) {
- ++pt;
- ++types;
- if (!_lineTo(rw, UPSCALE(*pt))) return false;
- //types cubic
- } else {
- pt += 3;
- types += 3;
- if (pt <= limit) {
- if (!_cubicTo(rw, UPSCALE(pt[-2]), UPSCALE(pt[-1]), UPSCALE(pt[0]))) return false;
- } else if (pt - 1 == limit) {
- if (!_cubicTo(rw, UPSCALE(pt[-2]), UPSCALE(pt[-1]), start)) return false;
- }
- else goto close;
+ auto pts = outline->out.data;
+ auto start = UPSCALE(*pts);
+ auto open = false;
+
+ for (auto cmd : outline->path->cmds) {
+ switch (cmd) {
+ case PathCommand::MoveTo: {
+ if (open && !_lineTo(rw, start)) return false;
+ start = UPSCALE(*pts++);
+ if (!_moveTo(rw, start)) return false;
+ open = true;
+ break;
+ }
+ case PathCommand::LineTo: {
+ if (!open && !_moveTo(rw, start)) return false;
+ if (!_lineTo(rw, UPSCALE(*pts++))) return false;
+ open = true;
+ break;
+ }
+ case PathCommand::CubicTo: {
+ if (!open && !_moveTo(rw, start)) return false;
+ if (!_cubicTo(rw, UPSCALE(pts[0]), UPSCALE(pts[1]), UPSCALE(pts[2]))) return false;
+ pts += 3;
+ open = true;
+ break;
+ }
+ case PathCommand::Close: {
+ if (open && !_lineTo(rw, start)) return false;
+ open = false;
+ break;
}
}
- close:
- if (!_lineTo(rw, start)) return false;
- first = last + 1;
}
-
- return true;
+ return !open || _lineTo(rw, start);
}
@@ -748,11 +766,11 @@ SwRle* rleRender(SwRle* rle, const SwOutline* outline, const RenderRegion& bbox,
rw.area = 0;
rw.cover = 0;
rw.invalid = true;
- rw.cellMin = {bbox.min.x, bbox.min.y};
- rw.cellMax = {bbox.max.x, bbox.max.y};
+ rw.cellMin = {bbox.xMin, bbox.yMin};
+ rw.cellMax = {bbox.xMax, bbox.yMax};
rw.cellXCnt = rw.cellMax.x - rw.cellMin.x;
rw.cellYCnt = rw.cellMax.y - rw.cellMin.y;
- rw.outline = const_cast<SwOutline*>(outline);
+ rw.outline = outline;
rw.bandSize = rw.bufferSize / (sizeof(SwCell) * 2);
rw.bandShoot = 0;
rw.antiAlias = antiAlias;
@@ -852,9 +870,9 @@ SwRle* rleRender(const RenderRegion* bbox)
rle->spans.count = bbox->h();
//cheaper without push()
- auto x = uint16_t(bbox->min.x);
- auto y = uint16_t(bbox->min.y);
- auto len = uint16_t(bbox->w());
+ auto x = bbox->xMin;
+ auto y = bbox->yMin;
+ auto len = (int32_t)bbox->w();
ARRAY_FOREACH(p, rle->spans) {
*p = {x, y++, len, 255};
@@ -904,24 +922,38 @@ bool rleClip(SwRle* rle, const SwRle *clip)
++cspans;
continue;
}
- //try clipping with all clip spans which have a same y-coordinate.
- auto temp = cspans;
- while(temp < cend && temp->y == cspans->y) {
- //span must be left(x1) to right(x2) direction. Not intersected.
- if ((spans->x + spans->len) < spans->x || (temp->x + temp->len) < temp->x) {
- ++temp;
- continue;
- }
- //clip span region
- auto x = std::max(spans->x, temp->x);
- auto len = std::min((spans->x + spans->len), (temp->x + temp->len)) - x;
- if (len > 0) out.next() = {uint16_t(x), temp->y, uint16_t(len), (uint8_t)(((spans->coverage * temp->coverage) + 0xff) >> 8)};
- ++temp;
+
+ // Both span lists are ordered and non-overlapping within a scanline.
+ if (spans->len <= 0) {
+ ++spans;
+ continue;
+ }
+ if (cspans->len <= 0) {
+ ++cspans;
+ continue;
+ }
+
+ auto spanEnd = spans->x + spans->len;
+ auto clipEnd = cspans->x + cspans->len;
+
+ if (spanEnd <= cspans->x) {
+ ++spans;
+ continue;
}
- ++spans;
+ if (clipEnd <= spans->x) {
+ ++cspans;
+ continue;
+ }
+
+ auto x = std::max(spans->x, cspans->x);
+ auto len = std::min(spanEnd, clipEnd) - x;
+ out.next() = {x, spans->y, len, (uint8_t)(((spans->coverage * cspans->coverage) + 0xff) >> 8)};
+
+ if (spanEnd <= clipEnd) ++spans;
+ if (clipEnd <= spanEnd) ++cspans;
}
out.move(rle->spans);
- return true;
+ return !rle->spans.empty();
}
@@ -930,24 +962,21 @@ bool rleClip(SwRle *rle, const RenderRegion* clip)
{
if (rle->spans.empty() || clip->invalid()) return false;
- auto& min = clip->min;
- auto& max = clip->max;
-
Array<SwSpan> out;
out.reserve(rle->spans.count);
auto data = out.data;
const SwSpan* end;
- uint16_t x, len;
+ int32_t x, len;
for (auto p = rle->fetch(*clip, &end); p < end; ++p) {
- if (p->y >= max.y) break;
- if (p->y < min.y || p->x >= max.x || (p->x + p->len) <= min.x) continue;
- if (p->x < min.x) {
- x = min.x;
- len = std::min(uint16_t(p->len - (x - p->x)), uint16_t(max.x - x));
+ if (p->y >= clip->yMax) break;
+ if (p->y < clip->yMin || p->x >= clip->xMax || (p->x + p->len) <= clip->xMin) continue;
+ if (p->x < clip->xMin) {
+ x = clip->xMin;
+ len = std::min(p->len - (x - p->x), (clip->xMax - x));
} else {
x = p->x;
- len = std::min(p->len, uint16_t(max.x - x));
+ len = std::min(p->len, clip->xMax - x);
}
if (len > 0) {
*data = {x, p->y, len, p->coverage};
@@ -956,7 +985,7 @@ bool rleClip(SwRle *rle, const RenderRegion* clip)
}
}
out.move(rle->spans);
- return true;
+ return !rle->spans.empty();
}
@@ -964,13 +993,10 @@ bool rleIntersect(const SwRle* rle, const RenderRegion& region)
{
if (!rle || rle->spans.empty()) return false;
- auto& min = region.min;
- auto& max = region.max;
-
const SwSpan* end;
for (auto p = rle->fetch(region, &end); p < end; ++p) {
- if (p->y >= max.y) break;
- if (p->y < min.y || p->x >= max.x || (p->x + p->len) <= min.x) continue;
+ if (p->y >= region.yMax) break;
+ if (p->y < region.yMin || p->x >= region.xMax || (p->x + p->len) <= region.xMin) continue;
return true;
}
return false;
diff --git a/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwShape.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwShape.cpp
new file mode 100644
index 00000000000..af0fdc1055b
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwShape.cpp
@@ -0,0 +1,466 @@
+/*
+ * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
+
+ * 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 "tvgSwCommon.h"
+
+/************************************************************************/
+/* Internal Class Implementation */
+/************************************************************************/
+
+static void _drawPoint(SwDashStroke& dash, const Point& start)
+{
+ if (dash.move || dash.pattern[dash.curIdx] < FLOAT_EPSILON) {
+ dash.path->moveTo(start);
+ dash.move = false;
+ }
+ dash.path->lineTo(start);
+}
+
+static void _dashLineTo(SwDashStroke& dash, const Point& to, bool validPoint)
+{
+ Line cur = {dash.ptCur, to};
+ auto len = cur.length();
+ if (tvg::zero(len)) {
+ dash.ptCur = to;
+ return;
+ }
+
+ if (len <= dash.curLen) {
+ dash.curLen -= len;
+ if (!dash.curOpGap) {
+ if (dash.move) {
+ dash.path->moveTo(dash.ptCur);
+ dash.move = false;
+ }
+ dash.path->lineTo(to);
+ }
+ //draw the current line partially
+ } else {
+ while (len - dash.curLen > DASH_PATTERN_THRESHOLD) {
+ Line left, right;
+ if (dash.curLen > 0) {
+ len -= dash.curLen;
+ cur.split(dash.curLen, left, right);
+ if (!dash.curOpGap) {
+ if (dash.move || dash.pattern[dash.curIdx] - dash.curLen < FLOAT_EPSILON) {
+ dash.path->moveTo(left.pt1);
+ dash.move = false;
+ }
+ dash.path->lineTo(left.pt2);
+ }
+ } else {
+ if (validPoint && !dash.curOpGap) _drawPoint(dash, cur.pt1);
+ right = cur;
+ }
+ dash.curIdx = (dash.curIdx + 1) % dash.cnt;
+ dash.curLen = dash.pattern[dash.curIdx];
+ dash.curOpGap = !dash.curOpGap;
+ cur = right;
+ dash.ptCur = cur.pt1;
+ dash.move = true;
+ }
+ //leftovers
+ dash.curLen -= len;
+ if (!dash.curOpGap) {
+ if (dash.move) {
+ dash.path->moveTo(cur.pt1);
+ dash.move = false;
+ }
+ dash.path->lineTo(cur.pt2);
+ }
+ if (dash.curLen < DASH_PATTERN_THRESHOLD && !tvg::zero(len)) {
+ //move to next dash
+ dash.curIdx = (dash.curIdx + 1) % dash.cnt;
+ dash.curLen = dash.pattern[dash.curIdx];
+ dash.curOpGap = !dash.curOpGap;
+ dash.move = true;
+ }
+ }
+ dash.ptCur = to;
+}
+
+static void _dashCubicTo(SwDashStroke& dash, const Point& ctrl1, const Point& ctrl2, const Point& to, bool validPoint)
+{
+ Bezier cur = {dash.ptCur, ctrl1, ctrl2, to};
+ auto len = cur.length();
+ if (tvg::zero(len)) {
+ dash.ptCur = to;
+ return;
+ }
+
+ //draw the current line fully
+ if (len <= dash.curLen) {
+ dash.curLen -= len;
+ if (!dash.curOpGap) {
+ if (dash.move) {
+ dash.path->moveTo(dash.ptCur);
+ dash.move = false;
+ }
+ dash.path->cubicTo(ctrl1, ctrl2, to);
+ }
+ //draw the current line partially
+ } else {
+ while ((len - dash.curLen) > DASH_PATTERN_THRESHOLD) {
+ Bezier left, right;
+ if (dash.curLen > 0) {
+ len -= dash.curLen;
+ cur.split(dash.curLen, left, right);
+ if (!dash.curOpGap) {
+ if (dash.move || dash.pattern[dash.curIdx] - dash.curLen < FLOAT_EPSILON) {
+ dash.path->moveTo(left.start);
+ dash.move = false;
+ }
+ dash.path->cubicTo(left.ctrl1, left.ctrl2, left.end);
+ }
+ } else {
+ if (validPoint && !dash.curOpGap) _drawPoint(dash, cur.start);
+ right = cur;
+ }
+ dash.curIdx = (dash.curIdx + 1) % dash.cnt;
+ dash.curLen = dash.pattern[dash.curIdx];
+ dash.curOpGap = !dash.curOpGap;
+ cur = right;
+ dash.ptCur = right.start;
+ dash.move = true;
+ }
+ //leftovers
+ dash.curLen -= len;
+ if (!dash.curOpGap) {
+ if (dash.move) {
+ dash.path->moveTo(cur.start);
+ dash.move = false;
+ }
+ dash.path->cubicTo(cur.ctrl1, cur.ctrl2, cur.end);
+ }
+ if (dash.curLen < DASH_PATTERN_THRESHOLD && !tvg::zero(len)) {
+ //move to next dash
+ dash.curIdx = (dash.curIdx + 1) % dash.cnt;
+ dash.curLen = dash.pattern[dash.curIdx];
+ dash.curOpGap = !dash.curOpGap;
+ dash.move = true;
+ }
+ }
+ dash.ptCur = to;
+}
+
+static void _dashClose(SwDashStroke& dash, bool validPoint, uint32_t cmdBegin, uint32_t ptBegin)
+{
+ _dashLineTo(dash, dash.ptStart, validPoint);
+ auto& cmds = dash.path->cmds;
+ auto& pts = dash.path->pts;
+
+ // join the first and the last dashes across the seam only when both touch the start point
+ if (cmds.count > cmdBegin + 1 &&
+ tvg::closed(pts[ptBegin], dash.ptStart, DASH_PATTERN_THRESHOLD) &&
+ tvg::closed(pts.last(), dash.ptStart, DASH_PATTERN_THRESHOLD)) {
+ // locate the end of the first dash
+ auto cmdEnd = cmdBegin + 1, ptEnd = ptBegin + 1;
+ for (; cmdEnd < cmds.count && cmds[cmdEnd] != PathCommand::MoveTo; ++cmdEnd) {
+ ptEnd += (cmds[cmdEnd] == PathCommand::CubicTo) ? 3 : 1;
+ }
+
+ // move the first dash behind the last to join them at the start point
+ if (cmdEnd < cmds.count) {
+ auto rotate = [](auto& arr, uint32_t from, uint32_t to) {
+ arr.grow(to - from);
+ memcpy(arr.end(), arr.begin() + from, (to - from) * sizeof(*arr.data));
+ memmove(arr.begin() + from, arr.begin() + to, (arr.count - from) * sizeof(*arr.data));
+ };
+ cmds[cmdBegin] = PathCommand::LineTo;
+ rotate(pts, ptBegin, ptEnd);
+ rotate(cmds, cmdBegin, cmdEnd);
+ }
+ }
+ // the next sub-path may continue without moveTo
+ dash.move = true;
+}
+
+static void _dashMoveTo(SwDashStroke& dash, uint32_t offIdx, float offset, const Point& pts)
+{
+ dash.curIdx = offIdx % dash.cnt;
+ dash.curLen = dash.pattern[dash.curIdx] - offset;
+ dash.curOpGap = offIdx % 2;
+ dash.ptStart = dash.ptCur = pts;
+ dash.move = true;
+}
+
+static SwOutline* _genDashOutline(const RenderShape* rshape, SwMpool* mpool, unsigned tid, bool trimmed)
+{
+ RenderPath trim;
+ auto path = &rshape->path;
+ if (trimmed) {
+ if (!rshape->stroke->trim.trim(*path, trim)) return nullptr;
+ path = &trim;
+ }
+
+ if (path->cmds.empty() || path->empty()) return nullptr;
+
+ auto cmds = path->cmds.data;
+ auto cmdCnt = path->cmds.count;
+ auto pts = path->pts.data;
+
+ SwDashStroke dash;
+ dash.pattern = rshape->stroke->dash.pattern;
+ dash.cnt = rshape->stroke->dash.count;
+ auto offset = rshape->stroke->dash.offset;
+
+ //offset
+ uint32_t offIdx = 0;
+ if (!tvg::zero(offset)) {
+ auto length = rshape->stroke->dash.length;
+ bool isOdd = dash.cnt % 2;
+ if (isOdd) length *= 2;
+
+ offset = fmodf(offset, length);
+ if (offset < 0) offset += length;
+
+ for (size_t i = 0; i < dash.cnt * (1 + (size_t)isOdd); ++i, ++offIdx) {
+ auto curPattern = dash.pattern[i % dash.cnt];
+ if (offset < curPattern) break;
+ offset -= curPattern;
+ }
+ }
+
+ auto outline = mpool->outline(tid);
+ dash.path = const_cast<RenderPath*>(outline->path);
+ auto cmdBegin = dash.path->cmds.count;
+ auto ptBegin = dash.path->pts.count;
+
+ //must begin with moveTo
+ if (cmds[0] == PathCommand::MoveTo) {
+ _dashMoveTo(dash, offIdx, offset, *pts);
+ cmds++;
+ pts++;
+ }
+
+ //zero length segment with non-butt cap still should be rendered as a point - only the caps are visible
+ auto validPoint = rshape->stroke->cap != StrokeCap::Butt;
+ while (--cmdCnt > 0) {
+ switch (*cmds) {
+ case PathCommand::Close: {
+ _dashClose(dash, validPoint, cmdBegin, ptBegin);
+ cmdBegin = dash.path->cmds.count;
+ ptBegin = dash.path->pts.count;
+ break;
+ }
+ case PathCommand::MoveTo: {
+ _dashMoveTo(dash, offIdx, offset, *pts);
+ cmdBegin = dash.path->cmds.count;
+ ptBegin = dash.path->pts.count;
+ ++pts;
+ break;
+ }
+ case PathCommand::LineTo: {
+ _dashLineTo(dash, *pts, validPoint);
+ ++pts;
+ break;
+ }
+ case PathCommand::CubicTo: {
+ _dashCubicTo(dash, *pts, pts[1], pts[2], validPoint);
+ pts += 3;
+ break;
+ }
+ }
+ ++cmds;
+ }
+
+ outline->fillRule = rshape->rule;
+
+ return outline;
+}
+
+static bool _axisAlignedRect(const SwOutline* outline)
+{
+ auto& path = *outline->path;
+ // TODO: We can return false if the coordinates have a fractional part, for smoother rectangle movement
+ if (path.cmds.count != 5 || (path.cmds[0] != PathCommand::MoveTo && path.cmds[0] != PathCommand::LineTo)) return false;
+ for (uint32_t i = 1; i < 4; ++i) {
+ if (path.cmds[i] != PathCommand::LineTo) return false;
+ }
+ if (path.cmds[4] != PathCommand::Close && path.cmds[4] != PathCommand::LineTo) return false;
+
+ auto pt1 = outline->out.data + 0;
+ auto pt2 = outline->out.data + 1;
+ auto pt3 = outline->out.data + 2;
+ auto pt4 = outline->out.data + 3;
+
+ auto a = SwPoint{pt1->x, pt3->y};
+ auto b = SwPoint{pt3->x, pt1->y};
+
+ if ((*pt2 == a && *pt4 == b) || (*pt2 == b && *pt4 == a)) return true;
+
+ return false;
+}
+
+static SwOutline* _genOutline(const RenderShape* rshape, SwMpool* mpool, unsigned tid, bool trimmed = false)
+{
+ auto outline = mpool->outline(tid);
+ if (trimmed) {
+ if (!rshape->stroke->trim.trim(rshape->path, *const_cast<RenderPath*>(outline->path))) return nullptr;
+ } else {
+ outline->path = &rshape->path;
+ }
+
+ auto path = outline->path;
+ if (path->empty() || path->cmds.empty() || path->cmds.first() == PathCommand::CubicTo) return nullptr;
+
+ outline->fillRule = rshape->rule;
+ return outline;
+}
+
+/************************************************************************/
+/* External Class Implementation */
+/************************************************************************/
+
+bool shapeGenRle(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool composite, bool antiAlias)
+{
+ auto outline = _genOutline(rshape, mpool, tid, rshape->trimpath());
+ if (!outline) {
+ renderBox.reset();
+ return false;
+ }
+
+ BBox bbox;
+ utilExport(outline, transform, bbox);
+
+ shape.outline = outline;
+ shape.fastTrack = !composite && _axisAlignedRect(outline);
+
+ if (!utilBBox(bbox, clipBox, renderBox, shape.fastTrack)) return false;
+ shape.bbox = renderBox;
+
+ if (shape.fastTrack) return true;
+
+ shape.rle = rleRender(shape.rle, outline, renderBox, mpool, tid, antiAlias);
+ return shape.rle ? true : false;
+}
+
+void shapeDelOutline(SwShape& shape)
+{
+ shape.outline = nullptr;
+}
+
+void shapeReset(SwShape& shape)
+{
+ rleReset(shape.rle);
+ shape.outline = nullptr;
+ shape.bbox.reset();
+ shape.fastTrack = false;
+}
+
+
+void shapeFree(SwShape& shape)
+{
+ rleFree(shape.rle);
+ shape.rle = nullptr;
+
+ if (shape.fill) {
+ tvg::free(shape.fill);
+ shape.fill = nullptr;
+ }
+
+ if (shape.stroke) {
+ rleFree(shape.strokeRle);
+ shape.strokeRle = nullptr;
+ strokeFree(shape.stroke);
+ shape.stroke = nullptr;
+ }
+}
+
+
+void shapeDelStroke(SwShape& shape)
+{
+ if (!shape.stroke) return;
+ rleFree(shape.strokeRle);
+ shape.strokeRle = nullptr;
+ strokeFree(shape.stroke);
+ shape.stroke = nullptr;
+}
+
+
+void shapeResetStroke(SwShape& shape, const RenderShape* rshape, const Matrix& transform, SwMpool* mpool, unsigned tid)
+{
+ if (!shape.stroke) shape.stroke = tvg::calloc<SwStroke>(1, sizeof(SwStroke));
+ strokeReset(shape.stroke, rshape, transform, mpool, tid);
+ rleReset(shape.strokeRle);
+}
+
+
+bool shapeGenStrokeRle(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool antiAlias)
+{
+ shapeResetStroke(shape, rshape, transform, mpool, tid);
+
+ auto dash = (rshape->stroke->dash.length > DASH_PATTERN_THRESHOLD);
+ SwOutline* outline;
+
+ if (dash) outline = _genDashOutline(rshape, mpool, tid, rshape->trimpath());
+ // resuse outline generated by shape
+ else outline = shape.outline ? shape.outline : _genOutline(rshape, mpool, tid, rshape->trimpath());
+ if (!outline) return false;
+
+ if (!strokeParseOutline(shape.stroke, *outline)) return false;
+ BBox bbox;
+ outline = strokeExportOutline(shape.stroke, mpool, tid);
+ if (outline->path->empty()) return false;
+ utilExport(outline, transform, bbox);
+ if (!utilBBox(bbox, clipBox, renderBox, false)) return false;
+
+ shape.strokeRle = rleRender(shape.strokeRle, outline, renderBox, mpool, tid, antiAlias);
+ return shape.strokeRle ? true : false;
+}
+
+bool shapeStrokeBBox(SwShape& shape, const RenderShape* rshape, Point* pt4, const Matrix& m, SwMpool* mpool)
+{
+ // TODO: We can skip generation here if the stroke hasn't been updated.
+ if (rshape->strokeWidth() > 0.0f) {
+ auto outline = _genOutline(rshape, mpool, 0, rshape->trimpath());
+ if (!outline) return false;
+
+ if (!shape.stroke) shape.stroke = tvg::calloc<SwStroke>(1, sizeof(SwStroke));
+ strokeReset(shape.stroke, rshape, m, mpool, 0);
+ strokeParseOutline(shape.stroke, *outline);
+
+ auto func = [](SwStrokeBorder* border, const Matrix& m, Point& min, Point& max) {
+ ARRAY_FOREACH(pts, border->pts)
+ {
+ auto t = *pts * m;
+ if (t.x < min.x) min.x = t.x;
+ if (t.x > max.x) max.x = t.x;
+ if (t.y < min.y) min.y = t.y;
+ if (t.y > max.y) max.y = t.y;
+ }
+ };
+
+ Point min = {FLT_MAX, FLT_MAX};
+ Point max = {-FLT_MAX, -FLT_MAX};
+ func(shape.stroke->borders[0], m, min, max);
+ func(shape.stroke->borders[1], m, min, max);
+
+ pt4[0] = min;
+ pt4[1] = {max.x, min.y};
+ pt4[2] = max;
+ pt4[3] = {min.x, max.y};
+
+ return true;
+ }
+ return false;
+}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwStroke.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwStroke.cpp
similarity index 51%
rename from thirdparty/thorvg/src/renderer/sw_engine/tvgSwStroke.cpp
rename to thirdparty/thorvg/src/renderer/cpu_engine/tvgSwStroke.cpp
index d7499f9e297..b0d6b6bfa0c 100644
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwStroke.cpp
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwStroke.cpp
@@ -31,18 +31,31 @@
#define SW_STROKE_TAG_BEGIN 4
#define SW_STROKE_TAG_END 8
-static inline int64_t SIDE_TO_ROTATE(const int32_t s)
+static inline float _sideToRotate(int32_t s)
{
- return (SW_ANGLE_PI2 - static_cast<int64_t>(s) * SW_ANGLE_PI);
+ return (MATH_PI2 - float(s) * MATH_PI);
}
+static inline bool _tiny(const Point& pt)
+{
+ constexpr float EPSILON = 2.0f / 64.0f;
+ return fabsf(pt.x) < EPSILON && fabsf(pt.y) < EPSILON;
+}
-static inline void SCALE(const SwStroke& stroke, SwPoint& pt)
+static inline float _mean(float angle1, float angle2)
{
- pt.x = static_cast<int32_t>(pt.x * stroke.sx);
- pt.y = static_cast<int32_t>(pt.y * stroke.sy);
+ return angle1 + remainderf(angle2 - angle1, MATH_2PI) * 0.5f;
}
+static void _rotate(Point& pt, float radian)
+{
+ if (tvg::zero(radian)) return;
+ auto cosv = cosf(radian);
+ auto sinv = sinf(radian);
+ auto x = pt.x * cosv - pt.y * sinv;
+ auto y = pt.x * sinv + pt.y * cosv;
+ pt = {x, y};
+}
static void _growBorder(SwStrokeBorder* border, uint32_t newPts)
{
@@ -96,8 +109,7 @@ static void _borderClose(SwStrokeBorder* border, bool reverse)
border->movable = false;
}
-
-static void _borderCubicTo(SwStrokeBorder* border, const SwPoint& ctrl1, const SwPoint& ctrl2, const SwPoint& to)
+static void _borderCubicTo(SwStrokeBorder* border, const Point& ctrl1, const Point& ctrl2, const Point& to)
{
_growBorder(border, 3);
@@ -114,47 +126,72 @@ static void _borderCubicTo(SwStrokeBorder* border, const SwPoint& ctrl1, const S
border->movable = false;
}
+static void _borderLineTo(SwStrokeBorder* border, const Point& to, bool movable)
+{
+ if (border->movable) {
+ // move last point
+ border->pts.last() = to;
+ } else {
+ // don't add zero-length line_to
+ if (!border->pts.empty() && _tiny(border->pts.last() - to)) return;
+ _growBorder(border, 1);
+ border->tags[border->pts.count] = SW_STROKE_TAG_POINT;
+ border->pts.push(to);
+ }
+ border->movable = movable;
+}
+
+static void _borderMoveTo(SwStrokeBorder* border, const Point& to)
+{
+ // close current open path if any?
+ if (border->start >= 0) _borderClose(border, false);
+
+ border->start = border->pts.count;
+ border->movable = false;
+
+ _borderLineTo(border, to, false);
+}
-static void _borderArcTo(SwStrokeBorder* border, const SwPoint& center, int64_t radius, int64_t angleStart, int64_t angleDiff, SwStroke& stroke)
+static void _borderArcTo(SwStroke& stroke, int32_t side)
{
- constexpr int64_t ARC_CUBIC_ANGLE = SW_ANGLE_PI / 2;
- SwPoint a = {static_cast<int32_t>(radius), 0};
- mathRotate(a, angleStart);
- SCALE(stroke, a);
- a += center;
+ auto border = stroke.borders[side];
+ auto rotate = _sideToRotate(side);
+ auto angleStart = stroke.angleIn + rotate;
+ auto angleDiff = remainderf(stroke.angleOut - stroke.angleIn, MATH_2PI);
+ if (tvg::equal(angleDiff, MATH_PI)) angleDiff = -rotate * 2.0f;
+
+ auto a = Point{stroke.width, 0.0f};
+ _rotate(a, angleStart);
+ a += stroke.center;
auto total = angleDiff;
auto angle = angleStart;
- auto rotate = (angleDiff >= 0) ? SW_ANGLE_PI2 : -SW_ANGLE_PI2;
+ rotate = (angleDiff >= 0) ? MATH_PI2 : -MATH_PI2;
- while (total != 0) {
+ while (!tvg::zero(total)) {
auto step = total;
- if (step > ARC_CUBIC_ANGLE) step = ARC_CUBIC_ANGLE;
- else if (step < -ARC_CUBIC_ANGLE) step = -ARC_CUBIC_ANGLE;
+ if (step > MATH_PI2) step = MATH_PI2;
+ else if (step < -MATH_PI2) step = -MATH_PI2;
auto next = angle + step;
auto theta = step;
if (theta < 0) theta = -theta;
-
- theta >>= 1;
+ theta *= 0.5f;
//compute end point
- SwPoint b = {static_cast<int32_t>(radius), 0};
- mathRotate(b, next);
- SCALE(stroke, b);
- b += center;
+ auto b = Point{stroke.width, 0.0f};
+ _rotate(b, next);
+ b += stroke.center;
//compute first and second control points
- auto length = mathMulDiv(radius, mathSin(theta) * 4, (0x10000L + mathCos(theta)) * 3);
+ auto length = stroke.width * (4.0f / 3.0f) * std::tan(theta * 0.5f);
- SwPoint a2 = {static_cast<int32_t>(length), 0};
- mathRotate(a2, angle + rotate);
- SCALE(stroke, a2);
+ auto a2 = Point{length, 0.0f};
+ _rotate(a2, angle + rotate);
a2 += a;
- SwPoint b2 = {static_cast<int32_t>(length), 0};
- mathRotate(b2, next - rotate);
- SCALE(stroke, b2);
+ auto b2 = Point{length, 0.0f};
+ _rotate(b2, next - rotate);
b2 += b;
//add cubic arc
@@ -165,103 +202,57 @@ static void _borderArcTo(SwStrokeBorder* border, const SwPoint& center, int64_t
total -= step;
angle = next;
}
-}
-
-
-static void _borderLineTo(SwStrokeBorder* border, const SwPoint& to, bool movable)
-{
- if (border->movable) {
- //move last point
- border->pts.last() = to;
- } else {
- //don't add zero-length line_to
- if (!border->pts.empty() && (border->pts.last() - to).tiny()) return;
- _growBorder(border, 1);
- border->tags[border->pts.count] = SW_STROKE_TAG_POINT;
- border->pts.push(to);
- }
-
- border->movable = movable;
-}
-
-
-static void _borderMoveTo(SwStrokeBorder* border, SwPoint& to)
-{
- //close current open path if any?
- if (border->start >= 0) _borderClose(border, false);
-
- border->start = border->pts.count;
- border->movable = false;
- _borderLineTo(border, to, false);
-}
-
-
-static void _arcTo(SwStroke& stroke, int32_t side)
-{
- auto border = stroke.borders[side];
- auto rotate = SIDE_TO_ROTATE(side);
- auto total = mathDiff(stroke.angleIn, stroke.angleOut);
- if (total == SW_ANGLE_PI) total = -rotate * 2;
-
- _borderArcTo(border, stroke.center, stroke.width, stroke.angleIn + rotate, total, stroke);
border->movable = false;
}
-
-static void _outside(SwStroke& stroke, int32_t side, int64_t lineLength)
+static void _outside(SwStroke& stroke, int32_t side, float length)
{
auto border = stroke.borders[side];
if (stroke.join == StrokeJoin::Round) {
- _arcTo(stroke, side);
+ _borderArcTo(stroke, side);
} else {
//this is a mitered (pointed) or beveled (truncated) corner
- auto rotate = SIDE_TO_ROTATE(side);
+ auto rotate = _sideToRotate(side);
auto bevel = stroke.join == StrokeJoin::Bevel;
- int64_t phi = 0;
- int64_t thcos = 0;
+ auto phi = 0.0f;
+ auto thcos = 0.0f;
if (!bevel) {
- auto theta = mathDiff(stroke.angleIn, stroke.angleOut);
- if (theta == SW_ANGLE_PI) {
+ auto theta = remainderf(stroke.angleOut - stroke.angleIn, MATH_2PI);
+ if (tvg::equal(theta, MATH_PI)) {
theta = rotate;
phi = stroke.angleIn;
} else {
- theta /= 2;
+ theta *= 0.5f;
phi = stroke.angleIn + theta + rotate;
}
-
- thcos = mathCos(theta);
- auto sigma = mathMultiply(stroke.miterlimit, thcos);
+ thcos = std::cos(theta);
//is miter limit exceeded?
- if (sigma < 0x10000L) bevel = true;
+ if (stroke.miterlimit * thcos < 1.0f) bevel = true;
}
//this is a bevel (broken angle)
if (bevel) {
- SwPoint delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, stroke.angleOut + rotate);
- SCALE(stroke, delta);
+ auto delta = Point{stroke.width, 0.0f};
+ _rotate(delta, stroke.angleOut + rotate);
delta += stroke.center;
border->movable = false;
_borderLineTo(border, delta, false);
//this is a miter (intersection)
} else {
- auto length = mathDivide(stroke.width, thcos);
- SwPoint delta = {static_cast<int32_t>(length), 0};
- mathRotate(delta, phi);
- SCALE(stroke, delta);
+ auto delta = Point{stroke.width / thcos, 0.0f};
+ _rotate(delta, phi);
delta += stroke.center;
_borderLineTo(border, delta, false);
/* Now add and end point
Only needed if not lineto (lineLength is zero for curves) */
- if (lineLength == 0) {
- delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, stroke.angleOut + rotate);
- SCALE(stroke, delta);
+ if (tvg::zero(length)) {
+ delta = {stroke.width, 0.0f};
+ _rotate(delta, stroke.angleOut + rotate);
delta += stroke.center;
_borderLineTo(border, delta, false);
}
@@ -269,118 +260,94 @@ static void _outside(SwStroke& stroke, int32_t side, int64_t lineLength)
}
}
-
-static void _inside(SwStroke& stroke, int32_t side, int64_t lineLength)
+static void _inside(SwStroke& stroke, int32_t side, float length)
{
auto border = stroke.borders[side];
- auto theta = mathDiff(stroke.angleIn, stroke.angleOut) / 2;
- SwPoint delta;
- bool intersect = false;
+ auto theta = remainderf(stroke.angleOut - stroke.angleIn, MATH_2PI) * 0.5f;
+ auto intersect = false;
/* Only intersect borders if between two line_to's and both
lines are long enough (line length is zero for curves). */
- if (border->movable && lineLength > 0) {
+ if (border->movable && length > 0.0f) {
//compute minimum required length of lines
- int64_t minLength = abs(mathMultiply(stroke.width, mathTan(theta)));
- if (stroke.lineLength >= minLength && lineLength >= minLength) intersect = true;
+ auto minLength = fabsf(stroke.width * std::tan(theta));
+ if (stroke.length >= minLength && length >= minLength) intersect = true;
}
- auto rotate = SIDE_TO_ROTATE(side);
+ auto rotate = _sideToRotate(side);
+ Point delta;
if (!intersect) {
- delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, stroke.angleOut + rotate);
- SCALE(stroke, delta);
+ delta = {stroke.width, 0.0f};
+ _rotate(delta, stroke.angleOut + rotate);
delta += stroke.center;
border->movable = false;
} else {
//compute median angle
auto phi = stroke.angleIn + theta;
- auto thcos = mathCos(theta);
- delta = {static_cast<int32_t>(mathDivide(stroke.width, thcos)), 0};
- mathRotate(delta, phi + rotate);
- SCALE(stroke, delta);
+ auto thcos = std::cos(theta);
+ delta = {stroke.width / thcos, 0.0f};
+ _rotate(delta, phi + rotate);
delta += stroke.center;
}
-
_borderLineTo(border, delta, false);
}
-
-void _processCorner(SwStroke& stroke, int64_t lineLength)
+static void _processCorner(SwStroke& stroke, float length)
{
- auto turn = mathDiff(stroke.angleIn, stroke.angleOut);
+ auto turn = remainderf(stroke.angleOut - stroke.angleIn, MATH_2PI);
//no specific corner processing is required if the turn is 0
- if (turn == 0) return;
+ if (tvg::zero(turn)) return;
- //when we turn to the right, the inside side is 0
- int32_t inside = 0;
+ // when we turn to the right, the inside side is 0 otherwise, the inside is 1
+ auto inside = (turn < 0.0f) ? 1 : 0;
- //otherwise, the inside is 1
- if (turn < 0) inside = 1;
-
- //process the inside
- _inside(stroke, inside, lineLength);
-
- //process the outside
- _outside(stroke, 1 - inside, lineLength);
+ _inside(stroke, inside, length);
+ _outside(stroke, 1 - inside, length);
}
-
-void _firstSubPath(SwStroke& stroke, int64_t startAngle, int64_t lineLength)
+static void _firstSubPath(SwStroke& stroke, float startAngle, float length)
{
- SwPoint delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, startAngle + SW_ANGLE_PI2);
- SCALE(stroke, delta);
-
- auto pt = stroke.center + delta;
- _borderMoveTo(stroke.borders[0], pt);
+ auto delta = Point{stroke.width, 0.0f};
+ _rotate(delta, startAngle + MATH_PI2);
- pt = stroke.center - delta;
- _borderMoveTo(stroke.borders[1], pt);
+ _borderMoveTo(stroke.borders[0], stroke.center + delta);
+ _borderMoveTo(stroke.borders[1], stroke.center - delta);
/* Save angle, position and line length for last join
lineLength is zero for curves */
stroke.subPathAngle = startAngle;
stroke.firstPt = false;
- stroke.subPathLineLength = lineLength;
+ stroke.subPathLength = length;
}
-
-static void _lineTo(SwStroke& stroke, const SwPoint& to)
+static void _lineTo(SwStroke& stroke, const Point& to)
{
auto delta = to - stroke.center;
//a zero-length lineto is a no-op
- if (delta.zero()) {
+ if (tvg::zero(delta)) {
//round and square caps are expected to be drawn as a dot even for zero-length lines
- if (stroke.firstPt && stroke.cap != StrokeCap::Butt) _firstSubPath(stroke, 0, 0);
- return;
+ if (stroke.firstPt && stroke.cap != StrokeCap::Butt) _firstSubPath(stroke, 0.0f, 0.0f);
+ return;
}
- /* The lineLength is used to determine the intersection of strokes outlines.
- The scale needs to be reverted since the stroke width has not been scaled.
- An alternative option is to scale the width of the stroke properly by
- calculating the mixture of the sx/sy rating on the stroke direction. */
- delta.x = static_cast<int32_t>(delta.x / stroke.sx);
- delta.y = static_cast<int32_t>(delta.y / stroke.sy);
- auto lineLength = mathLength(delta);
- auto angle = mathAtan(delta);
+ auto length = tvg::length(delta);
+ auto angle = tvg::atan(delta);
- delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, angle + SW_ANGLE_PI2);
- SCALE(stroke, delta);
+ delta = {stroke.width, 0.0f};
+ _rotate(delta, angle + MATH_PI2);
//process corner if necessary
if (stroke.firstPt) {
/* This is the first segment of a subpath. We need to add a point to each border
at their respective starting point locations. */
- _firstSubPath(stroke, angle, lineLength);
+ _firstSubPath(stroke, angle, length);
} else {
//process the current corner
stroke.angleOut = angle;
- _processCorner(stroke, lineLength);
+ _processCorner(stroke, length);
}
//now add a line segment to both the inside and outside paths
@@ -393,13 +360,79 @@ static void _lineTo(SwStroke& stroke, const SwPoint& to)
stroke.angleIn = angle;
stroke.center = to;
- stroke.lineLength = lineLength;
+ stroke.length = length;
+}
+
+static int _cubicAngle(const Point* base, float& angleIn, float& angleMid, float& angleOut)
+{
+ auto d1 = base[2] - base[3];
+ auto d2 = base[1] - base[2];
+ auto d3 = base[0] - base[1];
+
+ if (_tiny(d1)) {
+ if (_tiny(d2)) {
+ if (_tiny(d3)) {
+ angleIn = angleMid = angleOut = 0;
+ return -1; // ignoreable
+ } else {
+ angleIn = angleMid = angleOut = tvg::atan(d3);
+ }
+ } else {
+ if (_tiny(d3)) {
+ angleIn = angleMid = angleOut = tvg::atan(d2);
+ } else {
+ angleIn = angleMid = tvg::atan(d2);
+ angleOut = tvg::atan(d3);
+ }
+ }
+ } else {
+ if (_tiny(d2)) {
+ if (_tiny(d3)) {
+ angleIn = angleMid = angleOut = tvg::atan(d1);
+ } else {
+ angleIn = tvg::atan(d1);
+ angleOut = tvg::atan(d3);
+ angleMid = _mean(angleIn, angleOut);
+ }
+ } else {
+ if (_tiny(d3)) {
+ angleIn = tvg::atan(d1);
+ angleMid = angleOut = tvg::atan(d2);
+ } else {
+ angleIn = tvg::atan(d1);
+ angleMid = tvg::atan(d2);
+ angleOut = tvg::atan(d3);
+ }
+ }
+ }
+
+ auto theta1 = fabsf(remainderf(angleMid - angleIn, MATH_2PI));
+ auto theta2 = fabsf(remainderf(angleOut - angleMid, MATH_2PI));
+
+ if ((theta1 < (MATH_PI / 8)) && (theta2 < (MATH_PI / 8))) return 0; // small size
+ return 1;
}
+static void _splitCubic(Point* base)
+{
+ auto p01 = (base[0] + base[1]) * 0.5f;
+ auto p12 = (base[1] + base[2]) * 0.5f;
+ auto p23 = (base[2] + base[3]) * 0.5f;
+ auto p012 = (p01 + p12) * 0.5f;
+ auto p123 = (p12 + p23) * 0.5f;
+ auto mid = (p012 + p123) * 0.5f;
+
+ base[6] = base[3];
+ base[1] = p01;
+ base[2] = p012;
+ base[3] = mid;
+ base[4] = p123;
+ base[5] = p23;
+}
-static void _cubicTo(SwStroke& stroke, const SwPoint& ctrl1, const SwPoint& ctrl2, const SwPoint& to)
+static void _cubicTo(SwStroke& stroke, const Point& ctrl1, const Point& ctrl2, const Point& to)
{
- SwPoint bezStack[37]; //TODO: static?
+ Point bezStack[37];
auto limit = bezStack + 32;
auto arc = bezStack;
auto firstArc = true;
@@ -408,18 +441,19 @@ static void _cubicTo(SwStroke& stroke, const SwPoint& ctrl1, const SwPoint& ctrl
arc[2] = ctrl1;
arc[3] = stroke.center;
+ auto join = stroke.join; // backup
+
while (arc >= bezStack) {
- int64_t angleIn, angleOut, angleMid;
+ float angleIn, angleOut, angleMid;
//initialize with current direction
angleIn = angleOut = angleMid = stroke.angleIn;
-
- auto valid = mathCubicAngle(arc, angleIn, angleMid, angleOut);
+ auto valid = _cubicAngle(arc, angleIn, angleMid, angleOut);
//valid size
if (valid > 0 && arc < limit) {
if (stroke.firstPt) stroke.angleIn = angleIn;
- mathSplitCubic(arc);
+ _splitCubic(arc);
arc += 3;
continue;
}
@@ -427,9 +461,8 @@ static void _cubicTo(SwStroke& stroke, const SwPoint& ctrl1, const SwPoint& ctrl
//ignoreable size
if (valid < 0 && arc == bezStack) {
stroke.center = to;
-
//round and square caps are expected to be drawn as a dot even for zero-length lines
- if (stroke.firstPt && stroke.cap != StrokeCap::Butt) _firstSubPath(stroke, 0, 0);
+ if (stroke.firstPt && stroke.cap != StrokeCap::Butt) _firstSubPath(stroke, 0.0f, 0.0f);
return;
}
@@ -438,92 +471,85 @@ static void _cubicTo(SwStroke& stroke, const SwPoint& ctrl1, const SwPoint& ctrl
firstArc = false;
//process corner if necessary
if (stroke.firstPt) {
- _firstSubPath(stroke, angleIn, 0);
+ _firstSubPath(stroke, angleIn, 0.0f);
} else {
stroke.angleOut = angleIn;
- _processCorner(stroke, 0);
+ _processCorner(stroke, 0.0f);
}
- } else if (abs(mathDiff(stroke.angleIn, angleIn)) > (SW_ANGLE_PI / 8) / 4) {
+ } else if (fabsf(remainderf(angleIn - stroke.angleIn, MATH_2PI)) > (MATH_PI / 8) / 4) {
//if the deviation from one arc to the next is too great add a round corner
stroke.center = arc[3];
stroke.angleOut = angleIn;
stroke.join = StrokeJoin::Round;
- _processCorner(stroke, 0);
+ _processCorner(stroke, 0.0f);
- //reinstate line join style
- stroke.join = stroke.joinSaved;
+ stroke.join = join; // reinstate line join style
}
//the arc's angle is small enough; we can add it directly to each border
- auto theta1 = mathDiff(angleIn, angleMid) / 2;
- auto theta2 = mathDiff(angleMid, angleOut) / 2;
- auto phi1 = mathMean(angleIn, angleMid);
- auto phi2 = mathMean(angleMid, angleOut);
- auto length1 = mathDivide(stroke.width, mathCos(theta1));
- auto length2 = mathDivide(stroke.width, mathCos(theta2));
- int64_t alpha0 = 0;
+ auto theta1 = remainderf(angleMid - angleIn, MATH_2PI) * 0.5f;
+ auto theta2 = remainderf(angleOut - angleMid, MATH_2PI) * 0.5f;
+ auto phi1 = _mean(angleIn, angleMid);
+ auto phi2 = _mean(angleMid, angleOut);
+ auto length1 = stroke.width / std::cos(theta1);
+ auto length2 = stroke.width / std::cos(theta2);
+ auto alpha0 = 0.0f;
//compute direction of original arc
if (stroke.handleWideStrokes) {
- alpha0 = mathAtan(arc[0] - arc[3]);
+ alpha0 = tvg::atan(arc[0] - arc[3]);
}
for (int side = 0; side < 2; ++side) {
auto border = stroke.borders[side];
- auto rotate = SIDE_TO_ROTATE(side);
-
- //compute control points
- SwPoint _ctrl1 = {static_cast<int32_t>(length1), 0};
- mathRotate(_ctrl1, phi1 + rotate);
- SCALE(stroke, _ctrl1);
- _ctrl1 += arc[2];
-
- SwPoint _ctrl2 = {static_cast<int32_t>(length2), 0};
- mathRotate(_ctrl2, phi2 + rotate);
- SCALE(stroke, _ctrl2);
- _ctrl2 += arc[1];
-
- //compute end point
- SwPoint end = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(end, angleOut + rotate);
- SCALE(stroke, end);
+ auto rotate = _sideToRotate(side);
+
+ // compute bezier points
+ auto c1 = Point{length1, 0.0f};
+ _rotate(c1, phi1 + rotate);
+ c1 += arc[2];
+
+ auto c2 = Point{length2, 0.0f};
+ _rotate(c2, phi2 + rotate);
+ c2 += arc[1];
+
+ auto end = Point{stroke.width, 0.0f};
+ _rotate(end, angleOut + rotate);
end += arc[0];
if (stroke.handleWideStrokes) {
- /* determine whether the border radius is greater than the radius of
- curvature of the original arc */
+ // determine whether the border radius is greater than the radius of curvature of the original arc
auto start = border->pts.last();
- auto alpha1 = mathAtan(end - start);
+ auto alpha1 = tvg::atan(end - start);
//is the direction of the border arc opposite to that of the original arc?
- if (abs(mathDiff(alpha0, alpha1)) > SW_ANGLE_PI / 2) {
-
+ if (fabsf(remainderf(alpha1 - alpha0, MATH_2PI)) > MATH_PI2) {
//use the sine rule to find the intersection point
- auto beta = mathAtan(arc[3] - start);
- auto gamma = mathAtan(arc[0] - end);
+ auto beta = tvg::atan(arc[3] - start);
+ auto gamma = tvg::atan(arc[0] - end);
auto bvec = end - start;
- auto blen = mathLength(bvec);
- auto sinA = abs(mathSin(alpha1 - gamma));
- auto sinB = abs(mathSin(beta - gamma));
- auto alen = mathMulDiv(blen, sinA, sinB);
+ auto blen = tvg::length(bvec);
+ auto sinA = fabsf(std::sin(alpha1 - gamma));
+ auto sinB = fabsf(std::sin(beta - gamma));
+ auto alen = (blen * sinA) / sinB;
- SwPoint delta = {static_cast<int32_t>(alen), 0};
- mathRotate(delta, beta);
+ auto delta = Point{alen, 0.0f};
+ _rotate(delta, beta);
delta += start;
//circumnavigate the negative sector backwards
border->movable = false;
_borderLineTo(border, delta, false);
_borderLineTo(border, end, false);
- _borderCubicTo(border, _ctrl2, _ctrl1, start);
+ _borderCubicTo(border, c2, c1, start);
//and then move to the endpoint
_borderLineTo(border, end, false);
continue;
}
}
- _borderCubicTo(border, _ctrl1, _ctrl2, end);
+ _borderCubicTo(border, c1, c2, end);
}
arc -= 3;
stroke.angleIn = angleOut;
@@ -531,54 +557,39 @@ static void _cubicTo(SwStroke& stroke, const SwPoint& ctrl1, const SwPoint& ctrl
stroke.center = to;
}
-
-static void _addCap(SwStroke& stroke, int64_t angle, int32_t side)
+static void _addCap(SwStroke& stroke, float angle, int32_t side)
{
- if (stroke.cap == StrokeCap::Square) {
- auto rotate = SIDE_TO_ROTATE(side);
- auto border = stroke.borders[side];
+ auto rotate = _sideToRotate(side);
+ auto border = stroke.borders[side];
+ auto delta = Point{stroke.width, 0.0f};
- SwPoint delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, angle);
- SCALE(stroke, delta);
+ if (stroke.cap == StrokeCap::Square) {
+ _rotate(delta, angle);
- SwPoint delta2 = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta2, angle + rotate);
- SCALE(stroke, delta2);
+ auto delta2 = Point{stroke.width, 0.0f};
+ _rotate(delta2, angle + rotate);
delta += stroke.center + delta2;
-
_borderLineTo(border, delta, false);
- delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, angle);
- SCALE(stroke, delta);
+ delta = {stroke.width, 0.0f};
+ _rotate(delta, angle);
- delta2 = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta2, angle - rotate);
- SCALE(stroke, delta2);
+ delta2 = {stroke.width, 0.0f};
+ _rotate(delta2, angle - rotate);
delta += delta2 + stroke.center;
-
_borderLineTo(border, delta, false);
} else if (stroke.cap == StrokeCap::Round) {
stroke.angleIn = angle;
- stroke.angleOut = angle + SW_ANGLE_PI;
- _arcTo(stroke, side);
- } else { //Butt
- auto rotate = SIDE_TO_ROTATE(side);
- auto border = stroke.borders[side];
-
- SwPoint delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, angle + rotate);
- SCALE(stroke, delta);
+ stroke.angleOut = angle + MATH_PI;
+ _borderArcTo(stroke, side);
+ } else { // Butt
+ _rotate(delta, angle + rotate);
delta += stroke.center;
-
_borderLineTo(border, delta, false);
- delta = {static_cast<int32_t>(stroke.width), 0};
- mathRotate(delta, angle - rotate);
- SCALE(stroke, delta);
+ delta = {stroke.width, 0.0f};
+ _rotate(delta, angle - rotate);
delta += stroke.center;
-
_borderLineTo(border, delta, false);
}
}
@@ -620,8 +631,7 @@ static void _addReverseLeft(SwStroke& stroke, bool opened)
left->movable = false;
}
-
-static void _beginSubPath(SwStroke& stroke, const SwPoint& to, bool closed)
+static void _beginSubPath(SwStroke& stroke, const Point& to, bool closed)
{
/* We cannot process the first point because there is not enough
information regarding its corner/cap. Later, it will be processed
@@ -641,39 +651,38 @@ static void _beginSubPath(SwStroke& stroke, const SwPoint& to, bool closed)
else
stroke.handleWideStrokes = false;
- stroke.ptStartSubPath = to;
- stroke.angleIn = 0;
+ stroke.subPathStart = to;
+ stroke.angleIn = 0.0f;
}
static void _endSubPath(SwStroke& stroke)
{
- if (stroke.closedSubPath) {
+ auto right = stroke.borders[0];
+ auto left = stroke.borders[1];
+
+ /* A closed subpath without any length leaves only the start point on each border.
+ Stroke it like a zero-length open line, so round/square caps still draw a dot. */
+ auto zeroLength = (right->pts.count == right->start + 1U) && (left->pts.count == left->start + 1U);
+
+ if (stroke.closedSubPath && !zeroLength) {
//close the path if needed
- if (stroke.center != stroke.ptStartSubPath)
- _lineTo(stroke, stroke.ptStartSubPath);
+ if (stroke.center != stroke.subPathStart) _lineTo(stroke, stroke.subPathStart);
//process the corner
stroke.angleOut = stroke.subPathAngle;
- auto turn = mathDiff(stroke.angleIn, stroke.angleOut);
+ auto turn = remainderf(stroke.angleOut - stroke.angleIn, MATH_2PI);
//No specific corner processing is required if the turn is 0
- if (turn != 0) {
- //when we turn to the right, the inside is 0
- int32_t inside = 0;
-
- //otherwise, the inside is 1
- if (turn < 0) inside = 1;
-
- _inside(stroke, inside, stroke.subPathLineLength); //inside
- _outside(stroke, 1 - inside, stroke.subPathLineLength); //outside
+ if (!tvg::zero(turn)) {
+ int32_t inside = 0; // when we turn to the right, the inside is 0
+ if (turn < 0) inside = 1; // otherwise, the inside is 1
+ _inside(stroke, inside, stroke.subPathLength); // inside
+ _outside(stroke, 1 - inside, stroke.subPathLength); // outside
}
-
- _borderClose(stroke.borders[0], false);
- _borderClose(stroke.borders[1], true);
+ _borderClose(right, false);
+ _borderClose(left, true);
} else {
- auto right = stroke.borders[0];
-
/* all right, this is an opened path, we need to add a cap between
right & left, add the reverse of left, then add a final cap
between left & right */
@@ -683,8 +692,8 @@ static void _endSubPath(SwStroke& stroke)
_addReverseLeft(stroke, true);
//now add the final cap
- stroke.center = stroke.ptStartSubPath;
- _addCap(stroke, stroke.subPathAngle + SW_ANGLE_PI, 0);
+ stroke.center = stroke.subPathStart;
+ _addCap(stroke, stroke.subPathAngle + MATH_PI, 0);
/* now end the right subpath accordingly. The left one is rewind
and doesn't need further processing */
@@ -692,23 +701,33 @@ static void _endSubPath(SwStroke& stroke)
}
}
-
-static void _exportBorderOutline(const SwStroke& stroke, SwOutline* outline, uint32_t side)
+static void _exportBorderOutline(const SwStroke& stroke, RenderPath& path, uint32_t side)
{
auto border = stroke.borders[side];
if (border->pts.empty()) return;
- auto src = border->tags;
- auto idx = outline->pts.count;
-
- ARRAY_FOREACH(pts, border->pts) {
- if (*src & SW_STROKE_TAG_POINT) outline->types.push(SW_CURVE_TYPE_POINT);
- else if (*src & SW_STROKE_TAG_CUBIC) outline->types.push(SW_CURVE_TYPE_CUBIC);
- if (*src & SW_STROKE_TAG_END) outline->cntrs.push(idx);
- ++src;
- ++idx;
+ Point start{};
+
+ for (uint32_t i = 0; i < border->pts.count; ++i) {
+ auto tag = border->tags[i];
+ if (tag & SW_STROKE_TAG_BEGIN) {
+ start = border->pts[i];
+ path.moveTo(start);
+ } else if (tag & SW_STROKE_TAG_CUBIC) {
+ //_borderClose() moved the last point to the start of the sub-path (adjusted starting coordinates),
+ //so a closing cubic keeps only its two controls and ends at the start point.
+ if (border->tags[i + 1] & SW_STROKE_TAG_END) {
+ path.cubicTo(border->pts[i], border->pts[i + 1], start);
+ ++i;
+ } else {
+ path.cubicTo(border->pts[i], border->pts[i + 1], border->pts[i + 2]);
+ i += 2;
+ }
+ } else {
+ path.lineTo(border->pts[i]);
+ }
+ if (border->tags[i] & SW_STROKE_TAG_END) path.close();
}
- outline->pts.push(border->pts);
}
@@ -718,78 +737,61 @@ static void _exportBorderOutline(const SwStroke& stroke, SwOutline* outline, uin
void strokeFree(SwStroke* stroke)
{
- if (!stroke) return;
-
- fillFree(stroke->fill);
- stroke->fill = nullptr;
-
+ if (stroke && stroke->fill) tvg::free(stroke->fill);
tvg::free(stroke);
}
void strokeReset(SwStroke* stroke, const RenderShape* rshape, const Matrix& transform, SwMpool* mpool, unsigned tid)
{
- stroke->sx = sqrtf(powf(transform.e11, 2.0f) + powf(transform.e21, 2.0f));
- stroke->sy = sqrtf(powf(transform.e12, 2.0f) + powf(transform.e22, 2.0f));
- stroke->width = HALF_STROKE(rshape->strokeWidth());
+ stroke->width = rshape->strokeWidth() * 0.5f;
stroke->cap = rshape->strokeCap();
- stroke->miterlimit = static_cast<int64_t>(rshape->strokeMiterlimit() * 65536.0f);
-
- //Save line join: it can be temporarily changed when stroking curves...
- stroke->joinSaved = stroke->join = rshape->strokeJoin();
+ stroke->miterlimit = rshape->strokeMiterlimit();
+ stroke->join = rshape->strokeJoin();
stroke->borders[0] = mpool->strokeLBorder(tid);
stroke->borders[1] = mpool->strokeRBorder(tid);
}
-bool strokeParseOutline(SwStroke* stroke, const SwOutline& outline, SwMpool* mpool, unsigned tid)
+bool strokeParseOutline(SwStroke* stroke, const SwOutline& outline)
{
- uint32_t first = 0;
- uint32_t i = 0;
-
- ARRAY_FOREACH(p, outline.cntrs) {
- auto last = *p; //index of last point in contour
- auto limit = outline.pts.data + last;
- ++i;
-
- //Skip empty points
- if (last <= first) {
- first = last + 1;
+ auto& path = *outline.path;
+ auto cmd = path.cmds.begin();
+ auto pts = path.pts.data;
+ Point start;
+
+ while (cmd < path.cmds.end()) {
+ if (*cmd == PathCommand::Close) {
+ ++cmd;
continue;
}
+ // Treat an initial LineTo as MoveTo when no points have been consumed yet.
+ if (*cmd == PathCommand::MoveTo || pts == path.pts.data) {
+ //A contour cannot start with a cubic control point
+ if (*cmd == PathCommand::CubicTo) return false;
+ start = *pts++;
+ ++cmd;
+ }
- auto start = outline.pts[first];
- auto pt = outline.pts.data + first;
- auto types = outline.types.data + first;
- auto type = types[0];
-
- //A contour cannot start with a cubic control point
- if (type == SW_CURVE_TYPE_CUBIC) return false;
- ++types;
-
- auto closed = outline.closed.data ? outline.closed.data[i - 1]: false;
-
+ // Find the subpath end and determine whether it is closed before beginning it.
+ auto end = cmd;
+ while (end < path.cmds.end() && *end != PathCommand::MoveTo && *end != PathCommand::Close) {
+ ++end;
+ }
+ auto closed = end < path.cmds.end() && *end == PathCommand::Close;
_beginSubPath(*stroke, start, closed);
- while (pt < limit) {
- //emit a single line_to
- if (types[0] == SW_CURVE_TYPE_POINT) {
- ++pt;
- ++types;
- _lineTo(*stroke, *pt);
- //types cubic
+ for (; cmd < end; ++cmd) {
+ if (*cmd == PathCommand::LineTo) {
+ _lineTo(*stroke, *pts++);
} else {
- pt += 3;
- types += 3;
- if (pt <= limit) _cubicTo(*stroke, pt[-2], pt[-1], pt[0]);
- else if (pt - 1 == limit) _cubicTo(*stroke, pt[-2], pt[-1], start);
- else goto close;
+ _cubicTo(*stroke, pts[0], pts[1], pts[2]);
+ pts += 3;
}
}
- close:
+ if (closed) _lineTo(*stroke, start);
if (!stroke->firstPt) _endSubPath(*stroke);
- first = last + 1;
}
return true;
}
@@ -799,12 +801,13 @@ SwOutline* strokeExportOutline(SwStroke* stroke, SwMpool* mpool, unsigned tid)
{
auto reserve = stroke->borders[0]->pts.count + stroke->borders[1]->pts.count;
auto outline = mpool->outline(tid);
- outline->pts.reserve(reserve);
- outline->types.reserve(reserve);
+ auto& path = *const_cast<RenderPath*>(outline->path);
+ path.pts.reserve(reserve);
+ path.cmds.reserve(reserve);
outline->fillRule = FillRule::NonZero;
- _exportBorderOutline(*stroke, outline, 0); //left
- _exportBorderOutline(*stroke, outline, 1); //right
+ _exportBorderOutline(*stroke, path, 0); // left
+ _exportBorderOutline(*stroke, path, 1); // right
return outline;
}
diff --git a/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwUtil.cpp b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwUtil.cpp
new file mode 100644
index 00000000000..d79c5441739
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/cpu_engine/tvgSwUtil.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
+
+ * 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 "tvgMath.h"
+#include "tvgSwCommon.h"
+
+/************************************************************************/
+/* External Class Implementation */
+/************************************************************************/
+
+void utilExport(SwOutline* outline, const Matrix& transform, BBox& bbox)
+{
+ outline->out.reserve(outline->path->pts.count);
+
+ bbox = {{FLT_MAX, FLT_MAX}, {-FLT_MAX, -FLT_MAX}};
+
+ ARRAY_FOREACH(pt, outline->path->pts) {
+ auto t = *pt * transform;
+ if (bbox.min.x > t.x) bbox.min.x = t.x;
+ if (bbox.max.x < t.x) bbox.max.x = t.x;
+ if (bbox.min.y > t.y) bbox.min.y = t.y;
+ if (bbox.max.y < t.y) bbox.max.y = t.y;
+ outline->out.push({int32_t(t.x * 64.0f), int32_t(t.y * 64.0f)});
+ }
+}
+
+bool utilBBox(const BBox& bbox, const RenderRegion& clipBox, RenderRegion& renderBox, bool fastTrack)
+{
+ if (fastTrack) {
+ renderBox.xMin = (int32_t)round(bbox.min.x);
+ renderBox.yMin = (int32_t)round(bbox.min.y);
+ renderBox.xMax = (int32_t)round(bbox.max.x);
+ renderBox.yMax = (int32_t)round(bbox.max.y);
+ } else {
+ renderBox.xMin = (int32_t)floorf(bbox.min.x);
+ renderBox.yMin = (int32_t)floorf(bbox.min.y);
+ renderBox.xMax = (int32_t)ceilf(bbox.max.x);
+ renderBox.yMax = (int32_t)ceilf(bbox.max.y);
+ }
+ renderBox.intersect(clipBox);
+ return renderBox.valid();
+}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwMath.cpp b/thirdparty/thorvg/src/renderer/sw_engine/tvgSwMath.cpp
deleted file mode 100644
index 8610ef38350..00000000000
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwMath.cpp
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
-
- * 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 "tvgMath.h"
-#include "tvgSwCommon.h"
-
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-static float TO_RADIAN(int64_t angle)
-{
- return (float(angle) / 65536.0f) * (MATH_PI / 180.0f);
-}
-
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-int64_t mathMean(int64_t angle1, int64_t angle2)
-{
- return angle1 + mathDiff(angle1, angle2) / 2;
-}
-
-
-int mathCubicAngle(const SwPoint* base, int64_t& angleIn, int64_t& angleMid, int64_t& angleOut)
-{
- auto d1 = base[2] - base[3];
- auto d2 = base[1] - base[2];
- auto d3 = base[0] - base[1];
-
- if (d1.tiny()) {
- if (d2.tiny()) {
- if (d3.tiny()) {
- angleIn = angleMid = angleOut = 0;
- return -1; //ignoreable
- } else {
- angleIn = angleMid = angleOut = mathAtan(d3);
- }
- } else {
- if (d3.tiny()) {
- angleIn = angleMid = angleOut = mathAtan(d2);
- } else {
- angleIn = angleMid = mathAtan(d2);
- angleOut = mathAtan(d3);
- }
- }
- } else {
- if (d2.tiny()) {
- if (d3.tiny()) {
- angleIn = angleMid = angleOut = mathAtan(d1);
- } else {
- angleIn = mathAtan(d1);
- angleOut = mathAtan(d3);
- angleMid = mathMean(angleIn, angleOut);
- }
- } else {
- if (d3.tiny()) {
- angleIn = mathAtan(d1);
- angleMid = angleOut = mathAtan(d2);
- } else {
- angleIn = mathAtan(d1);
- angleMid = mathAtan(d2);
- angleOut = mathAtan(d3);
- }
- }
- }
-
- auto theta1 = abs(mathDiff(angleIn, angleMid));
- auto theta2 = abs(mathDiff(angleMid, angleOut));
-
- if ((theta1 < (SW_ANGLE_PI / 8)) && (theta2 < (SW_ANGLE_PI / 8))) return 0; //small size
- return 1;
-}
-
-
-int64_t mathMultiply(int64_t a, int64_t b)
-{
- int32_t s = 1;
-
- //move sign
- if (a < 0) {
- a = -a;
- s = -s;
- }
- if (b < 0) {
- b = -b;
- s = -s;
- }
- int64_t c = (a * b + 0x8000L) >> 16;
- return (s > 0) ? c : -c;
-}
-
-
-int64_t mathDivide(int64_t a, int64_t b)
-{
- int32_t s = 1;
-
- //move sign
- if (a < 0) {
- a = -a;
- s = -s;
- }
- if (b < 0) {
- b = -b;
- s = -s;
- }
- int64_t q = b > 0 ? ((a << 16) + (b >> 1)) / b : 0x7FFFFFFFL;
- return (s < 0 ? -q : q);
-}
-
-
-int64_t mathMulDiv(int64_t a, int64_t b, int64_t c)
-{
- int32_t s = 1;
-
- //move sign
- if (a < 0) {
- a = -a;
- s = -s;
- }
- if (b < 0) {
- b = -b;
- s = -s;
- }
- if (c < 0) {
- c = -c;
- s = -s;
- }
- int64_t d = c > 0 ? (a * b + (c >> 1)) / c : 0x7FFFFFFFL;
-
- return (s > 0 ? d : -d);
-}
-
-
-void mathRotate(SwPoint& pt, int64_t angle)
-{
- if (angle == 0 || pt.zero()) return;
-
- Point v = pt.toPoint();
-
- auto radian = TO_RADIAN(angle);
- auto cosv = cosf(radian);
- auto sinv = sinf(radian);
-
- pt.x = int32_t(nearbyint((v.x * cosv - v.y * sinv) * 64.0f));
- pt.y = int32_t(nearbyint((v.x * sinv + v.y * cosv) * 64.0f));
-}
-
-
-int64_t mathTan(int64_t angle)
-{
- if (angle == 0) return 0;
- return int64_t(tanf(TO_RADIAN(angle)) * 65536.0f);
-}
-
-
-int64_t mathAtan(const SwPoint& pt)
-{
- if (pt.zero()) return 0;
- return int64_t(tvg::atan2(TO_FLOAT(pt.y), TO_FLOAT(pt.x)) * (180.0f / MATH_PI) * 65536.0f);
-}
-
-
-int64_t mathSin(int64_t angle)
-{
- if (angle == 0) return 0;
- return mathCos(SW_ANGLE_PI2 - angle);
-}
-
-
-int64_t mathCos(int64_t angle)
-{
- return int64_t(cosf(TO_RADIAN(angle)) * 65536.0f);
-}
-
-
-int64_t mathLength(const SwPoint& pt)
-{
- if (pt.zero()) return 0;
-
- //trivial case
- if (pt.x == 0) return abs(pt.y);
- if (pt.y == 0) return abs(pt.x);
-
- auto v = pt.toPoint();
- //return static_cast<int64_t>(sqrtf(v.x * v.x + v.y * v.y) * 65536.0f);
-
- /* approximate sqrt(x*x + y*y) using alpha max plus beta min algorithm.
- With alpha = 1, beta = 3/8, giving results with the largest error less
- than 7% compared to the exact value. */
- if (v.x < 0) v.x = -v.x;
- if (v.y < 0) v.y = -v.y;
- return static_cast<int64_t>((v.x > v.y) ? (v.x + v.y * 0.375f) : (v.y + v.x * 0.375f));
-}
-
-
-void mathSplitCubic(SwPoint* base)
-{
- int32_t a, b, c, d;
-
- base[6].x = base[3].x;
- c = base[1].x;
- d = base[2].x;
- base[1].x = a = (base[0].x + c) >> 1;
- base[5].x = b = (base[3].x + d) >> 1;
- c = (c + d) >> 1;
- base[2].x = a = (a + c) >> 1;
- base[4].x = b = (b + c) >> 1;
- base[3].x = (a + b) >> 1;
-
- base[6].y = base[3].y;
- c = base[1].y;
- d = base[2].y;
- base[1].y = a = (base[0].y + c) >> 1;
- base[5].y = b = (base[3].y + d) >> 1;
- c = (c + d) >> 1;
- base[2].y = a = (a + c) >> 1;
- base[4].y = b = (b + c) >> 1;
- base[3].y = (a + b) >> 1;
-}
-
-
-void mathSplitLine(SwPoint* base)
-{
- base[2] = base[1];
- base[1] = {(base[0].x >> 1) + (base[1].x >> 1), (base[0].y >> 1) + (base[1].y >> 1)};
-}
-
-
-int64_t mathDiff(int64_t angle1, int64_t angle2)
-{
- auto delta = angle2 - angle1;
-
- delta %= SW_ANGLE_2PI;
- if (delta < 0) delta += SW_ANGLE_2PI;
- if (delta > SW_ANGLE_PI) delta -= SW_ANGLE_2PI;
-
- return delta;
-}
-
-
-SwPoint mathTransform(const Point* to, const Matrix& transform)
-{
- auto tx = to->x * transform.e11 + to->y * transform.e12 + transform.e13;
- auto ty = to->x * transform.e21 + to->y * transform.e22 + transform.e23;
-
- return {TO_SWCOORD(tx), TO_SWCOORD(ty)};
-}
-
-
-bool mathUpdateOutlineBBox(const SwOutline* outline, const RenderRegion& clipBox, RenderRegion& renderBox, bool fastTrack)
-{
- if (!outline || outline->pts.empty() || outline->cntrs.empty()) {
- renderBox.reset();
- return false;
- }
-
- auto pt = outline->pts.begin();
-
- auto xMin = pt->x;
- auto xMax = pt->x;
- auto yMin = pt->y;
- auto yMax = pt->y;
-
- for (++pt; pt < outline->pts.end(); ++pt) {
- if (xMin > pt->x) xMin = pt->x;
- if (xMax < pt->x) xMax = pt->x;
- if (yMin > pt->y) yMin = pt->y;
- if (yMax < pt->y) yMax = pt->y;
- }
-
- if (fastTrack) {
- renderBox.min = {int32_t(round(xMin / 64.0f)), int32_t(round(yMin / 64.0f))};
- renderBox.max = {int32_t(round(xMax / 64.0f)), int32_t(round(yMax / 64.0f))};
- } else {
- renderBox.min = {xMin >> 6, yMin >> 6};
- renderBox.max = {(xMax + 63) >> 6, (yMax + 63) >> 6};
- }
-
- renderBox.intersect(clipBox);
- return renderBox.valid();
-}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterAvx.h b/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterAvx.h
deleted file mode 100644
index b5c30ab2a74..00000000000
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterAvx.h
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (c) 2021 - 2026 ThorVG project. All rights reserved.
-
- * 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.
- */
-
-#ifdef THORVG_AVX_VECTOR_SUPPORT
-
-#include <immintrin.h>
-
-#define N_32BITS_IN_128REG 4
-#define N_32BITS_IN_256REG 8
-
-static inline __m128i ALPHA_BLEND(__m128i c, __m128i a)
-{
- //1. set the masks for the A/G and R/B channels
- auto AG = _mm_set1_epi32(0xff00ff00);
- auto RB = _mm_set1_epi32(0x00ff00ff);
-
- //2. mask the alpha vector - originally quartet [a, a, a, a]
- auto aAG = _mm_and_si128(a, AG);
- auto aRB = _mm_and_si128(a, RB);
-
- //3. calculate the alpha blending of the 2nd and 4th channel
- //- mask the color vector
- //- multiply it by the masked alpha vector
- //- add the correction to compensate bit shifting used instead of dividing by 255
- //- shift bits - corresponding to division by 256
- auto even = _mm_and_si128(c, RB);
- even = _mm_mullo_epi16(even, aRB);
- even =_mm_add_epi16(even, RB);
- even = _mm_srli_epi16(even, 8);
-
- //4. calculate the alpha blending of the 1st and 3rd channel:
- //- mask the color vector
- //- multiply it by the corresponding masked alpha vector and store the high bits of the result
- //- add the correction to compensate division by 256 instead of by 255 (next step)
- //- remove the low 8 bits to mimic the division by 256
- auto odd = _mm_and_si128(c, AG);
- odd = _mm_mulhi_epu16(odd, aAG);
- odd = _mm_add_epi16(odd, RB);
- odd = _mm_and_si128(odd, AG);
-
- //5. the final result
- return _mm_or_si128(odd, even);
-}
-
-
-static void avxRasterGrayscale8(uint8_t* dst, uint8_t val, uint32_t offset, int32_t len)
-{
- dst += offset;
-
- __m256i vecVal = _mm256_set1_epi8(val);
-
- int32_t i = 0;
- for (; i <= len - 32; i += 32) {
- _mm256_storeu_si256((__m256i*)(dst + i), vecVal);
- }
-
- for (; i < len; ++i) {
- dst[i] = val;
- }
-}
-
-
-static void avxRasterPixel32(uint32_t *dst, uint32_t val, uint32_t offset, int32_t len)
-{
- //1. calculate how many iterations we need to cover the length
- uint32_t iterations = len / N_32BITS_IN_256REG;
- uint32_t avxFilled = iterations * N_32BITS_IN_256REG;
-
- //2. set the beginning of the array
- dst += offset;
-
- //3. fill the octets
- for (uint32_t i = 0; i < iterations; ++i, dst += N_32BITS_IN_256REG) {
- _mm256_storeu_si256((__m256i*)dst, _mm256_set1_epi32(val));
- }
-
- //4. fill leftovers (in the first step we have to set the pointer to the place where the avx job is done)
- int32_t leftovers = len - avxFilled;
- while (leftovers--) *dst++ = val;
-}
-
-
-static bool avxRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
-{
- auto h = bbox.h();
- auto w = bbox.w();
-
- //32bits channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto color = surface->join(c.r, c.g, c.b, c.a);
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
-
- uint32_t ialpha = 255 - c.a;
-
- auto avxColor = _mm_set1_epi32(color);
- auto avxIalpha = _mm_set1_epi8(ialpha);
-
- for (uint32_t y = 0; y < h; ++y) {
- auto dst = &buffer[y * surface->stride];
-
- //1. fill the not aligned memory (for 128-bit registers a 16-bytes alignment is required)
- auto notAligned = ((uintptr_t)dst & 0xf) / 4;
- if (notAligned) {
- notAligned = (N_32BITS_IN_128REG - notAligned > w ? w : N_32BITS_IN_128REG - notAligned);
- for (uint32_t x = 0; x < notAligned; ++x, ++dst) {
- *dst = color + ALPHA_BLEND(*dst, ialpha);
- }
- }
-
- //2. fill the aligned memory - N_32BITS_IN_128REG pixels processed at once
- uint32_t iterations = (w - notAligned) / N_32BITS_IN_128REG;
- uint32_t avxFilled = iterations * N_32BITS_IN_128REG;
- auto avxDst = (__m128i*)dst;
- for (uint32_t x = 0; x < iterations; ++x, ++avxDst) {
- *avxDst = _mm_add_epi32(avxColor, ALPHA_BLEND(*avxDst, avxIalpha));
- }
-
- //3. fill the remaining pixels
- int32_t leftovers = w - notAligned - avxFilled;
- dst += avxFilled;
- while (leftovers--) {
- *dst = color + ALPHA_BLEND(*dst, ialpha);
- dst++;
- }
- }
- //8bit grayscale
- } else if (surface->channelSize == sizeof(uint8_t)) {
- TVGLOG("SW_ENGINE", "Require AVX Optimization, Channel Size = %d", surface->channelSize);
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
- auto ialpha = ~c.a;
- for (uint32_t y = 0; y < h; ++y) {
- auto dst = &buffer[y * surface->stride];
- for (uint32_t x = 0; x < w; ++x, ++dst) {
- *dst = c.a + MULTIPLY(*dst, ialpha);
- }
- }
- }
- return true;
-}
-
-
-static bool avxRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
-{
- const SwSpan* end;
- int32_t x, len;
-
- //32bit channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto color = surface->join(c.r, c.g, c.b, c.a);
- uint32_t src;
-
- for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
- if (!span->fetch(bbox, x, len)) continue;
- if (span->coverage < 255) src = ALPHA_BLEND(color, span->coverage);
- else src = color;
-
- auto dst = &surface->buf32[span->y * surface->stride + x];
- auto ialpha = IA(src);
-
- //1. fill the not aligned memory (for 128-bit registers a 16-bytes alignment is required)
- int32_t notAligned = ((uintptr_t)dst & 0xf) / 4;
- if (notAligned) {
- notAligned = (N_32BITS_IN_128REG - notAligned > len ? len : N_32BITS_IN_128REG - notAligned);
- for (auto x = 0; x < notAligned; ++x, ++dst) {
- *dst = src + ALPHA_BLEND(*dst, ialpha);
- }
- }
-
- //2. fill the aligned memory using avx - N_32BITS_IN_128REG pixels processed at once
- //In order to avoid unnecessary avx variables declarations a check is made whether there are any iterations at all
- int32_t iterations = (len - notAligned) / N_32BITS_IN_128REG;
- int32_t avxFilled = 0;
- if (iterations > 0) {
- auto avxSrc = _mm_set1_epi32(src);
- auto avxIalpha = _mm_set1_epi8(ialpha);
-
- avxFilled = iterations * N_32BITS_IN_128REG;
- auto avxDst = (__m128i*)dst;
- for (auto x = 0; x < iterations; ++x, ++avxDst) {
- *avxDst = _mm_add_epi32(avxSrc, ALPHA_BLEND(*avxDst, avxIalpha));
- }
- }
-
- //3. fill the remaining pixels
- auto leftovers = len - notAligned - avxFilled;
- dst += avxFilled;
- while (leftovers--) {
- *dst = src + ALPHA_BLEND(*dst, ialpha);
- dst++;
- }
- }
- //8bit grayscale
- } else if (surface->channelSize == sizeof(uint8_t)) {
- TVGLOG("SW_ENGINE", "Require AVX Optimization, Channel Size = %d", surface->channelSize);
- uint8_t src;
- for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
- if (!span->fetch(bbox, x, len)) continue;
- auto dst = &surface->buf8[span->y * surface->stride + x];
- if (span->coverage < 255) src = MULTIPLY(span->coverage, c.a);
- else src = c.a;
- auto ialpha = ~c.a;
- for (auto x = 0; x < len; ++x, ++dst) {
- *dst = src + MULTIPLY(*dst, ialpha);
- }
- }
- }
- return true;
-}
-
-
-#endif
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterC.h b/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterC.h
deleted file mode 100644
index 03146da9d6e..00000000000
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterC.h
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (c) 2021 - 2026 ThorVG project. All rights reserved.
-
- * 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.
- */
-
-
-template<typename PIXEL_T>
-static void inline cRasterTranslucentPixels(PIXEL_T* dst, PIXEL_T* src, uint32_t len, uint32_t opacity)
-{
- //TODO: 64bits faster?
- if (opacity == 255) {
- for (uint32_t x = 0; x < len; ++x, ++dst, ++src) {
- *dst = *src + ALPHA_BLEND(*dst, IA(*src));
- }
- } else {
- for (uint32_t x = 0; x < len; ++x, ++dst, ++src) {
- auto tmp = ALPHA_BLEND(*src, opacity);
- *dst = tmp + ALPHA_BLEND(*dst, IA(tmp));
- }
- }
-}
-
-
-template<typename PIXEL_T>
-static void inline cRasterPixels(PIXEL_T* dst, PIXEL_T* src, uint32_t len, uint32_t opacity)
-{
- //TODO: 64bits faster?
- if (opacity == 255) {
- for (uint32_t x = 0; x < len; ++x, ++dst, ++src) {
- *dst = *src;
- }
- } else {
- cRasterTranslucentPixels(dst, src, len, opacity);
- }
-}
-
-
-template<typename PIXEL_T>
-static void inline cRasterPixels(PIXEL_T* dst, PIXEL_T val, uint32_t offset, int32_t len)
-{
- dst += offset;
-
- //fix the misaligned memory
- auto alignOffset = (long long) dst % 8;
- if (alignOffset > 0) {
- if (sizeof(PIXEL_T) == 4) alignOffset /= 4;
- else if (sizeof(PIXEL_T) == 1) alignOffset = 8 - alignOffset;
- while (alignOffset > 0 && len > 0) {
- *dst++ = val;
- --len;
- --alignOffset;
- }
- }
-
- //64bits faster clear
- if ((sizeof(PIXEL_T) == 4)) {
- auto val64 = (uint64_t(val) << 32) | uint64_t(val);
- while (len > 1) {
- *reinterpret_cast<uint64_t*>(dst) = val64;
- len -= 2;
- dst += 2;
- }
- } else if (sizeof(PIXEL_T) == 1) {
- auto val32 = (uint32_t(val) << 24) | (uint32_t(val) << 16) | (uint32_t(val) << 8) | uint32_t(val);
- auto val64 = (uint64_t(val32) << 32) | val32;
- while (len > 7) {
- *reinterpret_cast<uint64_t*>(dst) = val64;
- len -= 8;
- dst += 8;
- }
- }
-
- //leftovers
- while (len--) *dst++ = val;
-}
-
-
-static bool inline cRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
-{
- const SwSpan* end;
- int32_t x, len;
-
- //32bit channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto color = surface->join(c.r, c.g, c.b, c.a);
- uint32_t src;
- for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
- if (!span->fetch(bbox, x, len)) continue;
- auto dst = &surface->buf32[span->y * surface->stride + x];
- if (span->coverage < 255) src = ALPHA_BLEND(color, span->coverage);
- else src = color;
- auto ialpha = IA(src);
- for (auto x = 0; x < len; ++x, ++dst) {
- *dst = src + ALPHA_BLEND(*dst, ialpha);
- }
- }
- //8bit grayscale
- } else if (surface->channelSize == sizeof(uint8_t)) {
- uint8_t src;
- for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
- if (!span->fetch(bbox, x, len)) continue;
- auto dst = &surface->buf8[span->y * surface->stride + x];
- if (span->coverage < 255) src = MULTIPLY(span->coverage, c.a);
- else src = c.a;
- auto ialpha = ~c.a;
- for (auto x = 0; x < len; ++x, ++dst) {
- *dst = src + MULTIPLY(*dst, ialpha);
- }
- }
- }
- return true;
-}
-
-
-static bool inline cRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
-{
- //32bits channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto color = surface->join(c.r, c.g, c.b, c.a);
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
- auto ialpha = 255 - c.a;
- for (uint32_t y = 0; y < bbox.h(); ++y) {
- auto dst = &buffer[y * surface->stride];
- for (uint32_t x = 0; x < bbox.w(); ++x, ++dst) {
- *dst = color + ALPHA_BLEND(*dst, ialpha);
- }
- }
- //8bit grayscale
- } else if (surface->channelSize == sizeof(uint8_t)) {
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
- auto ialpha = ~c.a;
- for (uint32_t y = 0; y < bbox.h(); ++y) {
- auto dst = &buffer[y * surface->stride];
- for (uint32_t x = 0; x < bbox.w(); ++x, ++dst) {
- *dst = c.a + MULTIPLY(*dst, ialpha);
- }
- }
- }
- return true;
-}
-
-
-static bool inline cRasterABGRtoARGB(RenderSurface* surface)
-{
- TVGLOG("SW_ENGINE", "Convert ColorSpace ABGR - ARGB [Size: %d x %d]", surface->w, surface->h);
-
- //64bits faster converting
- if (surface->w % 2 == 0) {
- auto buffer = reinterpret_cast<uint64_t*>(surface->buf32);
- for (uint32_t y = 0; y < surface->h; ++y, buffer += surface->stride / 2) {
- auto dst = buffer;
- for (uint32_t x = 0; x < surface->w / 2; ++x, ++dst) {
- auto c = *dst;
- //flip Blue, Red channels
- *dst = (c & 0xff000000ff000000) + ((c & 0x00ff000000ff0000) >> 16) + (c & 0x0000ff000000ff00) + ((c & 0x000000ff000000ff) << 16);
- }
- }
- //default converting
- } else {
- auto buffer = surface->buf32;
- for (uint32_t y = 0; y < surface->h; ++y, buffer += surface->stride) {
- auto dst = buffer;
- for (uint32_t x = 0; x < surface->w; ++x, ++dst) {
- auto c = *dst;
- //flip Blue, Red channels
- *dst = (c & 0xff000000) + ((c & 0x00ff0000) >> 16) + (c & 0x0000ff00) + ((c & 0x000000ff) << 16);
- }
- }
- }
- return true;
-}
-
-
-static bool inline cRasterARGBtoABGR(RenderSurface* surface)
-{
- //exactly same with ABGRtoARGB
- return cRasterABGRtoARGB(surface);
-}
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterNeon.h b/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterNeon.h
deleted file mode 100644
index 649595f8592..00000000000
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwRasterNeon.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (c) 2021 - 2026 ThorVG project. All rights reserved.
-
- * 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.
- */
-
-#ifdef THORVG_NEON_VECTOR_SUPPORT
-
-#include <arm_neon.h>
-
-//TODO : need to support windows ARM
-
-#if defined(__ARM_64BIT_STATE) || defined(_M_ARM64)
-#define TVG_AARCH64 1
-#else
-#define TVG_AARCH64 0
-#endif
-
-
-static inline uint8x8_t ALPHA_BLEND(uint8x8_t c, uint8x8_t a)
-{
- uint16x8_t t = vmull_u8(c, a);
- return vshrn_n_u16(t, 8);
-}
-
-
-static void neonRasterGrayscale8(uint8_t* dst, uint8_t val, uint32_t offset, int32_t len)
-{
- dst += offset;
-
- int32_t i = 0;
- const uint8x16_t valVec = vdupq_n_u8(val);
-#if TVG_AARCH64
- uint8x16x4_t valQuad = {valVec, valVec, valVec, valVec};
- for (; i <= len - 16 * 4; i += 16 * 4) {
- vst1q_u8_x4(dst + i, valQuad);
- }
-#else
- for (; i <= len - 16; i += 16) {
- vst1q_u8(dst + i, valVec);
- }
-#endif
- for (; i < len; i++) {
- dst[i] = val;
- }
-}
-
-
-static void neonRasterPixel32(uint32_t *dst, uint32_t val, uint32_t offset, int32_t len)
-{
- dst += offset;
-
- uint32x4_t vectorVal = vdupq_n_u32(val);
-
-#if TVG_AARCH64
- uint32_t iterations = len / 16;
- uint32_t neonFilled = iterations * 16;
- uint32x4x4_t valQuad = {vectorVal, vectorVal, vectorVal, vectorVal};
- for (uint32_t i = 0; i < iterations; ++i) {
- vst4q_u32(dst, valQuad);
- dst += 16;
- }
-#else
- uint32_t iterations = len / 4;
- uint32_t neonFilled = iterations * 4;
- for (uint32_t i = 0; i < iterations; ++i) {
- vst1q_u32(dst, vectorVal);
- dst += 4;
- }
-#endif
- int32_t leftovers = len - neonFilled;
- while (leftovers--) *dst++ = val;
-}
-
-
-static bool neonRasterTranslucentRle(SwSurface* surface, const SwRle* rle, const RenderRegion& bbox, const RenderColor& c)
-{
- const SwSpan* end;
- int32_t x, len;
-
- //32bit channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto color = surface->join(c.r, c.g, c.b, c.a);
- uint32_t src;
- uint8x8_t *vDst = nullptr;
- int32_t align;
-
- for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
- if (!span->fetch(bbox, x, len)) continue;
- if (span->coverage < 255) src = ALPHA_BLEND(color, span->coverage);
- else src = color;
-
- auto dst = &surface->buf32[span->y * surface->stride + x];
- auto ialpha = IA(src);
-
- if ((((uintptr_t) dst) & 0x7) != 0) {
- //fill not aligned byte
- *dst = src + ALPHA_BLEND(*dst, ialpha);
- vDst = (uint8x8_t*)(dst + 1);
- align = 1;
- } else {
- vDst = (uint8x8_t*) dst;
- align = 0;
- }
-
- uint8x8_t vSrc = (uint8x8_t) vdup_n_u32(src);
- uint8x8_t vIalpha = vdup_n_u8((uint8_t) ialpha);
-
- for (int32_t x = 0; x < (len - align) / 2; ++x)
- vDst[x] = vadd_u8(vSrc, ALPHA_BLEND(vDst[x], vIalpha));
-
- auto leftovers = (len - align) % 2;
- if (leftovers > 0) dst[len - 1] = src + ALPHA_BLEND(dst[len - 1], ialpha);
- }
- //8bit grayscale
- } else if (surface->channelSize == sizeof(uint8_t)) {
- TVGLOG("SW_ENGINE", "Require Neon Optimization, Channel Size = %d", surface->channelSize);
- uint8_t src;
- for (auto span = rle->fetch(bbox, &end); span < end; ++span) {
- if (!span->fetch(bbox, x, len)) continue;
- auto dst = &surface->buf8[span->y * surface->stride + x];
- if (span->coverage < 255) src = MULTIPLY(span->coverage, c.a);
- else src = c.a;
- auto ialpha = ~c.a;
- for (auto x = 0; x < len; ++x, ++dst) {
- *dst = src + MULTIPLY(*dst, ialpha);
- }
- }
- }
- return true;
-}
-
-
-static bool neonRasterTranslucentRect(SwSurface* surface, const RenderRegion& bbox, const RenderColor& c)
-{
- auto h = bbox.h();
- auto w = bbox.w();
-
- //32bits channels
- if (surface->channelSize == sizeof(uint32_t)) {
- auto color = surface->join(c.r, c.g, c.b, c.a);
- auto buffer = surface->buf32 + (bbox.min.y * surface->stride) + bbox.min.x;
- auto ialpha = 255 - c.a;
-
- auto vColor = vdup_n_u32(color);
- auto vIalpha = vdup_n_u8((uint8_t) ialpha);
-
- uint8x8_t* vDst = nullptr;
- uint32_t align;
-
- for (uint32_t y = 0; y < h; ++y) {
- auto dst = &buffer[y * surface->stride];
-
- if ((((uintptr_t) dst) & 0x7) != 0) {
- //fill not aligned byte
- *dst = color + ALPHA_BLEND(*dst, ialpha);
- vDst = (uint8x8_t*) (dst + 1);
- align = 1;
- } else {
- vDst = (uint8x8_t*) dst;
- align = 0;
- }
-
- for (uint32_t x = 0; x < (w - align) / 2; ++x)
- vDst[x] = vadd_u8((uint8x8_t)vColor, ALPHA_BLEND(vDst[x], vIalpha));
-
- auto leftovers = (w - align) % 2;
- if (leftovers > 0) dst[w - 1] = color + ALPHA_BLEND(dst[w - 1], ialpha);
- }
- //8bit grayscale
- } else if (surface->channelSize == sizeof(uint8_t)) {
- TVGLOG("SW_ENGINE", "Require Neon Optimization, Channel Size = %d", surface->channelSize);
- auto buffer = surface->buf8 + (bbox.min.y * surface->stride) + bbox.min.x;
- auto ialpha = ~c.a;
- for (uint32_t y = 0; y < h; ++y) {
- auto dst = &buffer[y * surface->stride];
- for (uint32_t x = 0; x < w; ++x, ++dst) {
- *dst = c.a + MULTIPLY(*dst, ialpha);
- }
- }
- }
- return true;
-}
-
-#endif
diff --git a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwShape.cpp b/thirdparty/thorvg/src/renderer/sw_engine/tvgSwShape.cpp
deleted file mode 100644
index 268a1d5a3d3..00000000000
--- a/thirdparty/thorvg/src/renderer/sw_engine/tvgSwShape.cpp
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
- * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
-
- * 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 "tvgSwCommon.h"
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-static bool _outlineBegin(SwOutline& outline)
-{
- //Make a contour if lineTo/curveTo without calling close or moveTo beforehand.
- if (outline.pts.empty()) return false;
- outline.cntrs.push(outline.pts.count - 1);
- outline.closed.push(false);
- outline.pts.push(outline.pts[outline.cntrs.last()]);
- outline.types.push(SW_CURVE_TYPE_POINT);
- return false;
-}
-
-
-static bool _outlineEnd(SwOutline& outline)
-{
- if (outline.pts.empty()) return false;
- outline.cntrs.push(outline.pts.count - 1);
- outline.closed.push(false);
- return false;
-}
-
-
-static bool _outlineMoveTo(SwOutline& outline, const Point* to, const Matrix& transform, bool closed = false)
-{
- //make it a contour, if the last contour is not closed yet.
- if (!closed) _outlineEnd(outline);
-
- outline.pts.push(mathTransform(to, transform));
- outline.types.push(SW_CURVE_TYPE_POINT);
- return false;
-}
-
-
-static void _outlineLineTo(SwOutline& outline, const Point* to, const Matrix& transform)
-{
- outline.pts.push(mathTransform(to, transform));
- outline.types.push(SW_CURVE_TYPE_POINT);
-}
-
-
-static void _outlineCubicTo(SwOutline& outline, const Point* ctrl1, const Point* ctrl2, const Point* to, const Matrix& transform)
-{
- outline.pts.push(mathTransform(ctrl1, transform));
- outline.types.push(SW_CURVE_TYPE_CUBIC);
-
- outline.pts.push(mathTransform(ctrl2, transform));
- outline.types.push(SW_CURVE_TYPE_CUBIC);
-
- outline.pts.push(mathTransform(to, transform));
- outline.types.push(SW_CURVE_TYPE_POINT);
-}
-
-
-static bool _outlineClose(SwOutline& outline)
-{
- uint32_t i;
- if (outline.cntrs.count > 0) i = outline.cntrs.last() + 1;
- else i = 0;
-
- //Make sure there is at least one point in the current path
- if (outline.pts.count == i) return false;
-
- //Close the path
- outline.pts.push(outline.pts[i]);
- outline.cntrs.push(outline.pts.count - 1);
- outline.types.push(SW_CURVE_TYPE_POINT);
- outline.closed.push(true);
-
- return true;
-}
-
-
-static void _drawPoint(SwDashStroke& dash, const Point* start, const Matrix& transform)
-{
- if (dash.move || dash.pattern[dash.curIdx] < FLOAT_EPSILON) {
- _outlineMoveTo(*dash.outline, start, transform);
- dash.move = false;
- }
- _outlineLineTo(*dash.outline, start, transform);
-}
-
-
-static void _dashLineTo(SwDashStroke& dash, const Point* to, const Matrix& transform, bool validPoint)
-{
- Line cur = {dash.ptCur, *to};
- auto len = cur.length();
- if (tvg::zero(len)) {
- _outlineMoveTo(*dash.outline, &dash.ptCur, transform);
- //draw the current line fully
- } else if (len <= dash.curLen) {
- dash.curLen -= len;
- if (!dash.curOpGap) {
- if (dash.move) {
- _outlineMoveTo(*dash.outline, &dash.ptCur, transform);
- dash.move = false;
- }
- _outlineLineTo(*dash.outline, to, transform);
- }
- //draw the current line partially
- } else {
- while (len - dash.curLen > DASH_PATTERN_THRESHOLD) {
- Line left, right;
- if (dash.curLen > 0) {
- len -= dash.curLen;
- cur.split(dash.curLen, left, right);
- if (!dash.curOpGap) {
- if (dash.move || dash.pattern[dash.curIdx] - dash.curLen < FLOAT_EPSILON) {
- _outlineMoveTo(*dash.outline, &left.pt1, transform);
- dash.move = false;
- }
- _outlineLineTo(*dash.outline, &left.pt2, transform);
- }
- } else {
- if (validPoint && !dash.curOpGap) _drawPoint(dash, &cur.pt1, transform);
- right = cur;
- }
- dash.curIdx = (dash.curIdx + 1) % dash.cnt;
- dash.curLen = dash.pattern[dash.curIdx];
- dash.curOpGap = !dash.curOpGap;
- cur = right;
- dash.ptCur = cur.pt1;
- dash.move = true;
- }
- //leftovers
- dash.curLen -= len;
- if (!dash.curOpGap) {
- if (dash.move) {
- _outlineMoveTo(*dash.outline, &cur.pt1, transform);
- dash.move = false;
- }
- _outlineLineTo(*dash.outline, &cur.pt2, transform);
- }
- if (dash.curLen < 1 && TO_SWCOORD(len) > 1) {
- //move to next dash
- dash.curIdx = (dash.curIdx + 1) % dash.cnt;
- dash.curLen = dash.pattern[dash.curIdx];
- dash.curOpGap = !dash.curOpGap;
- }
- }
- dash.ptCur = *to;
-}
-
-
-static void _dashCubicTo(SwDashStroke& dash, const Point* ctrl1, const Point* ctrl2, const Point* to, const Matrix& transform, bool validPoint)
-{
- Bezier cur = {dash.ptCur, *ctrl1, *ctrl2, *to};
- auto len = cur.length();
-
- //draw the current line fully
- if (tvg::zero(len)) {
- _outlineMoveTo(*dash.outline, &dash.ptCur, transform);
- } else if (len <= dash.curLen) {
- dash.curLen -= len;
- if (!dash.curOpGap) {
- if (dash.move) {
- _outlineMoveTo(*dash.outline, &dash.ptCur, transform);
- dash.move = false;
- }
- _outlineCubicTo(*dash.outline, ctrl1, ctrl2, to, transform);
- }
- //draw the current line partially
- } else {
- while ((len - dash.curLen) > DASH_PATTERN_THRESHOLD) {
- Bezier left, right;
- if (dash.curLen > 0) {
- len -= dash.curLen;
- cur.split(dash.curLen, left, right);
- if (!dash.curOpGap) {
- if (dash.move || dash.pattern[dash.curIdx] - dash.curLen < FLOAT_EPSILON) {
- _outlineMoveTo(*dash.outline, &left.start, transform);
- dash.move = false;
- }
- _outlineCubicTo(*dash.outline, &left.ctrl1, &left.ctrl2, &left.end, transform);
- }
- } else {
- if (validPoint && !dash.curOpGap) _drawPoint(dash, &cur.start, transform);
- right = cur;
- }
- dash.curIdx = (dash.curIdx + 1) % dash.cnt;
- dash.curLen = dash.pattern[dash.curIdx];
- dash.curOpGap = !dash.curOpGap;
- cur = right;
- dash.ptCur = right.start;
- dash.move = true;
- }
- //leftovers
- dash.curLen -= len;
- if (!dash.curOpGap) {
- if (dash.move) {
- _outlineMoveTo(*dash.outline, &cur.start, transform);
- dash.move = false;
- }
- _outlineCubicTo(*dash.outline, &cur.ctrl1, &cur.ctrl2, &cur.end, transform);
- }
- if (dash.curLen < 0.1f && TO_SWCOORD(len) > 1) {
- //move to next dash
- dash.curIdx = (dash.curIdx + 1) % dash.cnt;
- dash.curLen = dash.pattern[dash.curIdx];
- dash.curOpGap = !dash.curOpGap;
- }
- }
- dash.ptCur = *to;
-}
-
-
-static void _dashClose(SwDashStroke& dash, const Matrix& transform, bool validPoint)
-{
- _dashLineTo(dash, &dash.ptStart, transform, validPoint);
-}
-
-
-static void _dashMoveTo(SwDashStroke& dash, uint32_t offIdx, float offset, const Point* pts)
-{
- dash.curIdx = offIdx % dash.cnt;
- dash.curLen = dash.pattern[dash.curIdx] - offset;
- dash.curOpGap = offIdx % 2;
- dash.ptStart = dash.ptCur = *pts;
- dash.move = true;
-}
-
-
-static SwOutline* _genDashOutline(const RenderShape* rshape, const Matrix& transform, SwMpool* mpool, unsigned tid, bool trimmed)
-{
- PathCommand *cmds, *trimmedCmds = nullptr;
- Point *pts, *trimmedPts = nullptr;
- uint32_t cmdCnt, ptsCnt;
-
- if (trimmed) {
- RenderPath trimmedPath;
- if (!rshape->stroke->trim.trim(rshape->path, trimmedPath)) return nullptr;
- cmds = trimmedCmds = trimmedPath.cmds.data;
- cmdCnt = trimmedPath.cmds.count;
- pts = trimmedPts = trimmedPath.pts.data;
- ptsCnt = trimmedPath.pts.count;
-
- trimmedPath.cmds.data = nullptr;
- trimmedPath.pts.data = nullptr;
- } else {
- cmds = rshape->path.cmds.data;
- cmdCnt = rshape->path.cmds.count;
- pts = rshape->path.pts.data;
- ptsCnt = rshape->path.pts.count;
- }
-
- //No actual shape data
- if (cmdCnt == 0 || ptsCnt == 0) return nullptr;
-
- SwDashStroke dash;
- dash.pattern = rshape->stroke->dash.pattern;
- dash.cnt = rshape->stroke->dash.count;
- auto offset = rshape->stroke->dash.offset;
-
- //offset
- uint32_t offIdx = 0;
- if (!tvg::zero(offset)) {
- auto length = rshape->stroke->dash.length;
- bool isOdd = dash.cnt % 2;
- if (isOdd) length *= 2;
-
- offset = fmodf(offset, length);
- if (offset < 0) offset += length;
-
- for (size_t i = 0; i < dash.cnt * (1 + (size_t)isOdd); ++i, ++offIdx) {
- auto curPattern = dash.pattern[i % dash.cnt];
- if (offset < curPattern) break;
- offset -= curPattern;
- }
- }
-
- dash.outline = mpool->outline(tid);
-
- //must begin with moveTo
- if (cmds[0] == PathCommand::MoveTo) {
- _dashMoveTo(dash, offIdx, offset, pts);
- cmds++;
- pts++;
- }
-
- //zero length segment with non-butt cap still should be rendered as a point - only the caps are visible
- auto validPoint = rshape->stroke->cap != StrokeCap::Butt;
- while (--cmdCnt > 0) {
- switch (*cmds) {
- case PathCommand::Close: {
- _dashClose(dash, transform, validPoint);
- break;
- }
- case PathCommand::MoveTo: {
- _dashMoveTo(dash, offIdx, offset, pts);
- ++pts;
- break;
- }
- case PathCommand::LineTo: {
- _dashLineTo(dash, pts, transform, validPoint);
- ++pts;
- break;
- }
- case PathCommand::CubicTo: {
- _dashCubicTo(dash, pts, pts + 1, pts + 2, transform, validPoint);
- pts += 3;
- break;
- }
- }
- ++cmds;
- }
-
- _outlineEnd(*dash.outline);
-
- dash.outline->fillRule = rshape->rule;
-
- tvg::free(trimmedCmds);
- tvg::free(trimmedPts);
-
- return dash.outline;
-}
-
-
-static bool _axisAlignedRect(const SwOutline* outline)
-{
- //Fast Track: axis-aligned rectangle?
- if (outline->pts.count != 5) return false;
- if (outline->types[2] == SW_CURVE_TYPE_CUBIC) return false;
-
- auto pt1 = outline->pts.data + 0;
- auto pt2 = outline->pts.data + 1;
- auto pt3 = outline->pts.data + 2;
- auto pt4 = outline->pts.data + 3;
-
- auto a = SwPoint{pt1->x, pt3->y};
- auto b = SwPoint{pt3->x, pt1->y};
-
- if ((*pt2 == a && *pt4 == b) || (*pt2 == b && *pt4 == a)) return true;
-
- return false;
-}
-
-
-static SwOutline* _genOutline(SwShape& shape, const RenderShape* rshape, const Matrix& transform, SwMpool* mpool, unsigned tid, bool hasComposite, bool trimmed = false)
-{
- PathCommand *cmds, *trimmedCmds = nullptr;
- Point *pts, *trimmedPts = nullptr;
- uint32_t cmdCnt, ptsCnt;
-
- if (trimmed) {
- RenderPath trimmedPath;
- if (!rshape->stroke->trim.trim(rshape->path, trimmedPath)) return nullptr;
- cmds = trimmedCmds = trimmedPath.cmds.data;
- cmdCnt = trimmedPath.cmds.count;
- pts = trimmedPts = trimmedPath.pts.data;
- ptsCnt = trimmedPath.pts.count;
-
- trimmedPath.cmds.data = nullptr;
- trimmedPath.pts.data = nullptr;
- } else {
- cmds = rshape->path.cmds.data;
- cmdCnt = rshape->path.cmds.count;
- pts = rshape->path.pts.data;
- ptsCnt = rshape->path.pts.count;
- }
-
- //No actual shape data
- if (cmdCnt == 0 || ptsCnt == 0) return nullptr;
-
- auto outline = mpool->outline(tid);
- auto closed = false;
-
- //Generate Outlines
- while (cmdCnt-- > 0) {
- switch (*cmds) {
- case PathCommand::Close: {
- if (!closed) closed = _outlineClose(*outline);
- break;
- }
- case PathCommand::MoveTo: {
- closed = _outlineMoveTo(*outline, pts, transform, closed);
- ++pts;
- break;
- }
- case PathCommand::LineTo: {
- if (closed) closed = _outlineBegin(*outline);
- _outlineLineTo(*outline, pts, transform);
- ++pts;
- break;
- }
- case PathCommand::CubicTo: {
- if (closed) closed = _outlineBegin(*outline);
- _outlineCubicTo(*outline, pts, pts + 1, pts + 2, transform);
- pts += 3;
- break;
- }
- }
- ++cmds;
- }
-
- if (!closed) _outlineEnd(*outline);
-
- outline->fillRule = rshape->rule;
-
- tvg::free(trimmedCmds);
- tvg::free(trimmedPts);
-
- shape.fastTrack = (!hasComposite && _axisAlignedRect(outline));
- return outline;
-}
-
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-bool shapePrepare(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid, bool hasComposite)
-{
- if ((shape.outline = _genOutline(shape, rshape, transform, mpool, tid, hasComposite, rshape->trimpath()))) {
- if (mathUpdateOutlineBBox(shape.outline, clipBox, renderBox, shape.fastTrack)) {
- shape.bbox = renderBox;
- return true;
- }
- }
- return false;
-}
-
-
-bool shapeGenRle(SwShape& shape, const RenderRegion& bbox, SwMpool* mpool, unsigned tid, bool antiAlias)
-{
- //Case A: Fast Track Rectangle Drawing
- if (shape.fastTrack) return true;
-
- //Case B: Normal Shape RLE Drawing
- if ((shape.rle = rleRender(shape.rle, shape.outline, bbox, mpool, tid, antiAlias))) return true;
-
- return false;
-}
-
-
-void shapeDelOutline(SwShape& shape, SwMpool* mpool, uint32_t tid)
-{
- shape.outline = nullptr;
-}
-
-
-void shapeReset(SwShape& shape)
-{
- rleReset(shape.rle);
- shape.bbox.reset();
- shape.fastTrack = false;
-}
-
-
-void shapeFree(SwShape& shape)
-{
- rleFree(shape.rle);
- shape.rle = nullptr;
-
- shapeDelFill(shape);
-
- if (shape.stroke) {
- rleFree(shape.strokeRle);
- shape.strokeRle = nullptr;
- strokeFree(shape.stroke);
- shape.stroke = nullptr;
- }
-}
-
-
-void shapeDelStroke(SwShape& shape)
-{
- if (!shape.stroke) return;
- rleFree(shape.strokeRle);
- shape.strokeRle = nullptr;
- strokeFree(shape.stroke);
- shape.stroke = nullptr;
-}
-
-
-void shapeResetStroke(SwShape& shape, const RenderShape* rshape, const Matrix& transform, SwMpool* mpool, unsigned tid)
-{
- if (!shape.stroke) shape.stroke = tvg::calloc<SwStroke>(1, sizeof(SwStroke));
- auto stroke = shape.stroke;
- strokeReset(stroke, rshape, transform, mpool, tid);
- rleReset(shape.strokeRle);
-}
-
-
-bool shapeGenStrokeRle(SwShape& shape, const RenderShape* rshape, const Matrix& transform, const RenderRegion& clipBox, RenderRegion& renderBox, SwMpool* mpool, unsigned tid)
-{
- SwOutline* shapeOutline = nullptr;
-
- //Dash style with/without trimming
- if (rshape->stroke->dash.length > DASH_PATTERN_THRESHOLD) {
- shapeOutline = _genDashOutline(rshape, transform, mpool, tid, rshape->trimpath());
- //Trimming & Normal style
- } else {
- shapeOutline = shape.outline ? shape.outline : _genOutline(shape, rshape, transform, mpool, tid, false, rshape->trimpath());
- }
-
- if (!shapeOutline) return false;
-
- if (!strokeParseOutline(shape.stroke, *shapeOutline, mpool, tid)) return false;
-
- auto strokeOutline = strokeExportOutline(shape.stroke, mpool, tid);
- auto ret = mathUpdateOutlineBBox(strokeOutline, clipBox, renderBox, false);
- if (ret) shape.strokeRle = rleRender(shape.strokeRle, strokeOutline, renderBox, mpool, tid, true);
-
- return ret;
-}
-
-
-bool shapeGenFillColors(SwShape& shape, const Fill* fill, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable)
-{
- return fillGenColorTable(shape.fill, fill, transform, surface, opacity, ctable);
-}
-
-
-bool shapeGenStrokeFillColors(SwShape& shape, const Fill* fill, const Matrix& transform, SwSurface* surface, uint8_t opacity, bool ctable)
-{
- return fillGenColorTable(shape.stroke->fill, fill, transform, surface, opacity, ctable);
-}
-
-
-void shapeResetFill(SwShape& shape)
-{
- if (!shape.fill) {
- shape.fill = tvg::calloc<SwFill>(1, sizeof(SwFill));
- if (!shape.fill) return;
- }
- fillReset(shape.fill);
-}
-
-
-void shapeResetStrokeFill(SwShape& shape)
-{
- if (!shape.stroke->fill) {
- shape.stroke->fill = tvg::calloc<SwFill>(1, sizeof(SwFill));
- if (!shape.stroke->fill) return;
- }
- fillReset(shape.stroke->fill);
-}
-
-
-void shapeDelFill(SwShape& shape)
-{
- if (!shape.fill) return;
- fillFree(shape.fill);
- shape.fill = nullptr;
-}
-
-
-bool shapeStrokeBBox(SwShape& shape, const RenderShape* rshape, Point* pt4, const Matrix& m, SwMpool* mpool)
-{
- auto outline = _genOutline(shape, rshape, m, mpool, 0, false, rshape->trimpath());
- if (!outline) return false;
-
- if (rshape->strokeWidth() > 0.0f) {
- strokeReset(shape.stroke, rshape, m, mpool, 0);
- strokeParseOutline(shape.stroke, *outline, mpool, 0);
-
- auto func = [](SwStrokeBorder* border, SwPoint& min, SwPoint& max) {
- ARRAY_FOREACH(pts, border->pts) {
- if (pts->x < min.x) min.x = pts->x;
- if (pts->x > max.x) max.x = pts->x;
- if (pts->y < min.y) min.y = pts->y;
- if (pts->y > max.y) max.y = pts->y;
- }
- };
-
- SwPoint min = {INT32_MAX, INT32_MAX};
- SwPoint max = {-INT32_MAX, -INT32_MAX};
- func(shape.stroke->borders[0], min, max);
- func(shape.stroke->borders[1], min, max);
-
- pt4[0] = min.toPoint();
- pt4[1] = SwPoint{max.x, min.y}.toPoint();
- pt4[2] = max.toPoint();
- pt4[3] = SwPoint{min.x, max.y}.toPoint();
- }
-
- shapeDelOutline(shape, mpool, 0);
-
- return true;
-}
diff --git a/thirdparty/thorvg/src/renderer/tvgAccessor.cpp b/thirdparty/thorvg/src/renderer/tvgAccessor.cpp
index fd67d2b4901..36e88f2cfff 100644
--- a/thirdparty/thorvg/src/renderer/tvgAccessor.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgAccessor.cpp
@@ -20,31 +20,55 @@
* SOFTWARE.
*/
-#include "tvgIteratorAccessor.h"
+#include "tvgAccessor.h"
#include "tvgCompressor.h"
+#include "tvgPicture.h"
/************************************************************************/
/* Internal Class Implementation */
/************************************************************************/
-static bool accessChildren(Iterator* it, function<bool(const Paint* paint, void* data)> func, void* data)
-{
- while (auto child = it->next()) {
- //Access the child
- if (!func(child, data)) return false;
+#define IMPL static_cast<AccessorImpl*>(this)
+
+Accessor::Accessor() = default;
- //Access the children of the child
- if (auto it2 = IteratorAccessor::iterator(child)) {
- if (!accessChildren(it2, func, data)) {
+struct AccessorImpl : Accessor
+{
+ Paint* paint;
+ AccessorCallback cb;
+ bool accessible = false; // special searching for picture nested scenes with id maps
+
+ bool access(AccessorIterator* it)
+ {
+ while (auto child = it->next()) {
+ // access the child
+ if (!cb.func(child, cb.data)) return false;
+
+ // access the children of the child
+ if (auto it2 = AccessorIterator::iterator(child)) {
+ if (!access(it2)) {
+ delete (it2);
+ return false;
+ }
delete(it2);
- return false;
}
- delete(it2);
}
+ return true;
}
- return true;
-}
+ // pre-order tree search
+ void search()
+ {
+ // root
+ if (!cb.func(paint, cb.data)) return;
+
+ // children
+ if (auto it = AccessorIterator::iterator(paint)) {
+ access(it);
+ delete (it);
+ }
+ }
+};
/************************************************************************/
/* External Class Implementation */
@@ -52,49 +76,40 @@ static bool accessChildren(Iterator* it, function<bool(const Paint* paint, void*
Result Accessor::set(Paint* paint, function<bool(const Paint* paint, void* data)> func, void* data) noexcept
{
- if (!paint || !func) return Result::InvalidArguments;
+ if (paint && func) {
+ IMPL->paint = paint;
+ IMPL->cb = {func, data};
+ IMPL->accessible = (paint->type() == Type::Picture && static_cast<Picture*>(paint)->accessible);
- //Use the Preorder Tree-Search
+ paint->ref();
- paint->ref();
+ if (IMPL->accessible) to<PictureImpl>(IMPL->paint)->access(IMPL->cb);
+ else IMPL->search();
- //Root
- if (!func(paint, data)) {
paint->unref(false);
- return Result::Success;
- }
-
- //Children
- if (auto it = IteratorAccessor::iterator(paint)) {
- accessChildren(it, func, data);
- delete(it);
- }
-
- paint->unref(false);
-
- return Result::Success;
-}
+ IMPL->accessible = false;
-uint32_t Accessor::id(const char* name) noexcept
-{
- return djb2Encode(name);
+ return Result::Success;
+ }
+ return Result::InvalidArguments;
}
-
-Accessor::~Accessor()
+const char* Accessor::name(uint32_t id) noexcept
{
-
+ if (IMPL->accessible) {
+ auto entity = to<PictureImpl>(IMPL->paint)->access(id);
+ if (entity) return entity->name;
+ } else TVGLOG("RENDERER", "Did you enable Picture::accessible?");
+ return nullptr;
}
-
-Accessor::Accessor() : pImpl(nullptr)
+uint32_t Accessor::id(const char* name) noexcept
{
-
+ return djb2Encode(name);
}
-
Accessor* Accessor::gen() noexcept
{
- return new Accessor;
+ return new AccessorImpl;
}
diff --git a/thirdparty/thorvg/src/renderer/tvgIteratorAccessor.h b/thirdparty/thorvg/src/renderer/tvgAccessor.h
similarity index 73%
rename from thirdparty/thorvg/src/renderer/tvgIteratorAccessor.h
rename to thirdparty/thorvg/src/renderer/tvgAccessor.h
index 01b4fa9c4f7..8420c0a55db 100644
--- a/thirdparty/thorvg/src/renderer/tvgIteratorAccessor.h
+++ b/thirdparty/thorvg/src/renderer/tvgAccessor.h
@@ -20,19 +20,33 @@
* SOFTWARE.
*/
-#ifndef _TVG_ITERATOR_ACCESSOR_H_
-#define _TVG_ITERATOR_ACCESSOR_H_
+#ifndef _TVG_ACCESSOR_H_
+#define _TVG_ACCESSOR_H_
#include "tvgPaint.h"
namespace tvg
{
-class IteratorAccessor
+struct AccessorEntity
{
-public:
- //Utility Method: Iterator Accessor
- static Iterator* iterator(const Paint* paint)
+ uint32_t id; // for fast access (equal to paint->id)
+ Paint* paint;
+ char* name;
+};
+
+struct AccessorCallback
+{
+ function<bool(const Paint* paint, void* data)> func;
+ void* data;
+};
+
+struct AccessorIterator
+{
+ virtual ~AccessorIterator() {}
+ virtual const Paint* next() = 0;
+
+ static AccessorIterator* iterator(const Paint* paint)
{
return PAINT(paint)->iterator();
}
@@ -40,4 +54,4 @@ public:
}
-#endif //_TVG_ITERATOR_ACCESSOR_H_
+#endif //_TVG_ACCESSOR_H_
diff --git a/thirdparty/thorvg/src/renderer/tvgAnimation.cpp b/thirdparty/thorvg/src/renderer/tvgAnimation.cpp
index 62998950252..79d9a0a874a 100644
--- a/thirdparty/thorvg/src/renderer/tvgAnimation.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgAnimation.cpp
@@ -20,7 +20,7 @@
* SOFTWARE.
*/
-#include "tvgFrameModule.h"
+#include "tvgLoader.h"
#include "tvgAnimation.h"
@@ -40,10 +40,10 @@ Result Animation::frame(float no) noexcept
auto loader = to<PictureImpl>(pImpl->picture)->loader;
if (!loader) return Result::InsufficientCondition;
- if (!loader->animatable()) return Result::NonSupport;
+ if (!loader->playable) return Result::NonSupport;
- if (static_cast<FrameModule*>(loader)->frame(no)) {
- PAINT(pImpl->picture)->mark(RenderUpdateFlag::All);
+ if (static_cast<AnimLoader*>(loader)->frame(no)) {
+ PAINT(pImpl->picture)->mark(RenderUpdateFlag::Children);
return Result::Success;
}
return Result::InsufficientCondition;
@@ -59,33 +59,24 @@ Picture* Animation::picture() const noexcept
float Animation::curFrame() const noexcept
{
auto loader = to<PictureImpl>(pImpl->picture)->loader;
-
- if (!loader) return 0;
- if (!loader->animatable()) return 0;
-
- return static_cast<FrameModule*>(loader)->curFrame();
+ if (!loader || !loader->playable) return 0;
+ return static_cast<AnimLoader*>(loader)->curFrame();
}
float Animation::totalFrame() const noexcept
{
auto loader = to<PictureImpl>(pImpl->picture)->loader;
-
- if (!loader) return 0;
- if (!loader->animatable()) return 0;
-
- return static_cast<FrameModule*>(loader)->totalFrame();
+ if (!loader || !loader->playable) return 0;
+ return static_cast<AnimLoader*>(loader)->totalFrame();
}
float Animation::duration() const noexcept
{
auto loader = to<PictureImpl>(pImpl->picture)->loader;
-
- if (!loader) return 0;
- if (!loader->animatable()) return 0;
-
- return static_cast<FrameModule*>(loader)->duration();
+ if (!loader || !loader->playable) return 0;
+ return static_cast<AnimLoader*>(loader)->duration();
}
@@ -93,9 +84,9 @@ Result Animation::segment(float begin, float end) noexcept
{
auto loader = to<PictureImpl>(pImpl->picture)->loader;
if (!loader) return Result::InsufficientCondition;
- if (!loader->animatable()) return Result::NonSupport;
+ if (!loader->playable) return Result::NonSupport;
- return static_cast<FrameModule*>(loader)->segment(begin, end);
+ return static_cast<AnimLoader*>(loader)->segment(begin, end);
}
@@ -103,10 +94,10 @@ Result Animation::segment(float *begin, float *end) noexcept
{
auto loader = to<PictureImpl>(pImpl->picture)->loader;
if (!loader) return Result::InsufficientCondition;
- if (!loader->animatable()) return Result::NonSupport;
+ if (!loader->playable) return Result::NonSupport;
if (!begin && !end) return Result::InvalidArguments;
- static_cast<FrameModule*>(loader)->segment(begin, end);
+ static_cast<AnimLoader*>(loader)->segment(begin, end);
return Result::Success;
}
diff --git a/thirdparty/thorvg/src/renderer/tvgCanvas.cpp b/thirdparty/thorvg/src/renderer/tvgCanvas.cpp
index a2b41958602..00beb8de6e9 100644
--- a/thirdparty/thorvg/src/renderer/tvgCanvas.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgCanvas.cpp
@@ -22,17 +22,17 @@
#include "tvgCanvas.h"
#include "tvgTaskScheduler.h"
-#include "tvgLoadModule.h"
+#include "tvgLoader.h"
-#ifdef THORVG_SW_RASTER_SUPPORT
+#ifdef THORVG_CPU_ENGINE_SUPPORT
#include "tvgSwRenderer.h"
#endif
-#ifdef THORVG_GL_RASTER_SUPPORT
+#ifdef THORVG_GL_ENGINE_SUPPORT
#include "tvgGlRenderer.h"
#endif
-#ifdef THORVG_WG_RASTER_SUPPORT
+#ifdef THORVG_WG_ENGINE_SUPPORT
#include "tvgWgRenderer.h"
#endif
@@ -102,6 +102,16 @@ Result Canvas::sync() noexcept
return pImpl->sync();
}
+uint32_t Canvas::dirtyRegions() const noexcept
+{
+ return pImpl->dirtyRegions();
+}
+
+Result Canvas::dirtyRegions(Region* regions, uint32_t cnt) const noexcept
+{
+ if (!regions || cnt == 0) return Result::InvalidArguments;
+ return pImpl->dirtyRegions(regions, cnt);
+}
/************************************************************************/
/* SwCanvas Class Implementation */
@@ -111,7 +121,7 @@ SwCanvas::SwCanvas() = default;
SwCanvas::~SwCanvas()
{
-#ifdef THORVG_SW_RASTER_SUPPORT
+#ifdef THORVG_CPU_ENGINE_SUPPORT
SwRenderer::term();
#endif
}
@@ -119,27 +129,18 @@ SwCanvas::~SwCanvas()
Result SwCanvas::target(uint32_t* buffer, uint32_t stride, uint32_t w, uint32_t h, ColorSpace cs) noexcept
{
-#ifdef THORVG_SW_RASTER_SUPPORT
- if (cs == ColorSpace::Unknown) return Result::InvalidArguments;
- if (cs == ColorSpace::Grayscale8) return Result::NonSupport;
+#ifdef THORVG_CPU_ENGINE_SUPPORT
+ if (pImpl->status == Status::Updating || pImpl->status == Status::Drawing) return Result::InsufficientCondition;
- if (pImpl->status == Status::Updating || pImpl->status == Status::Drawing) {
- return Result::InsufficientCondition;
- }
-
- //We know renderer type, avoid dynamic_cast for performance.
- auto renderer = static_cast<SwRenderer*>(pImpl->renderer);
- if (!renderer) return Result::MemoryCorruption;
+ auto ret = static_cast<SwRenderer*>(pImpl->renderer)->target(buffer, stride, w, h, cs);
+ if (ret != Result::Success) return ret;
- if (!renderer->target(buffer, stride, w, h, cs)) return Result::InvalidArguments;
- pImpl->vport = {{0, 0}, {(int32_t)w, (int32_t)h}};
- renderer->viewport(pImpl->vport);
+ pImpl->vport = {0, 0, (int32_t)w, (int32_t)h};
+ pImpl->renderer->viewport(pImpl->vport);
+ pImpl->status = Status::Damaged; // Paints must be updated again with this new target.
//FIXME: The value must be associated with an individual canvas instance.
- ImageLoader::cs = static_cast<ColorSpace>(cs);
-
- //Paints must be updated again with this new target.
- pImpl->status = Status::Damaged;
+ BitmapLoader::cs = static_cast<ColorSpace>(cs);
return Result::Success;
#endif
@@ -149,7 +150,7 @@ Result SwCanvas::target(uint32_t* buffer, uint32_t stride, uint32_t w, uint32_t
SwCanvas* SwCanvas::gen(EngineOption op) noexcept
{
-#ifdef THORVG_SW_RASTER_SUPPORT
+#ifdef THORVG_CPU_ENGINE_SUPPORT
if (engineInit > 0) {
auto renderer = new SwRenderer(TaskScheduler::threads(), op);
renderer->ref();
@@ -158,6 +159,7 @@ SwCanvas* SwCanvas::gen(EngineOption op) noexcept
return ret;
}
#endif
+ TVGLOG("RENDERER", "SwCanvas is not supported");
return nullptr;
}
@@ -170,7 +172,7 @@ GlCanvas::GlCanvas() = default;
GlCanvas::~GlCanvas()
{
-#ifdef THORVG_GL_RASTER_SUPPORT
+#ifdef THORVG_GL_ENGINE_SUPPORT
GlRenderer::term();
#endif
}
@@ -178,23 +180,18 @@ GlCanvas::~GlCanvas()
Result GlCanvas::target(void* display, void* surface, void* context, int32_t id, uint32_t w, uint32_t h, ColorSpace cs) noexcept
{
-#ifdef THORVG_GL_RASTER_SUPPORT
- if (cs != ColorSpace::ABGR8888S) return Result::NonSupport;
+#ifdef THORVG_GL_ENGINE_SUPPORT
+ if (pImpl->status == Status::Updating || pImpl->status == Status::Drawing) return Result::InsufficientCondition;
- if (pImpl->status == Status::Updating || pImpl->status == Status::Drawing) {
- return Result::InsufficientCondition;
- }
+ auto ret = static_cast<GlRenderer*>(pImpl->renderer)->target(display, surface, context, id, w, h, cs);
+ if (ret != Result::Success) return ret;
- //We know renderer type, avoid dynamic_cast for performance.
- auto renderer = static_cast<GlRenderer*>(pImpl->renderer);
- if (!renderer) return Result::MemoryCorruption;
+ pImpl->vport = {0, 0, (int32_t)w, (int32_t)h};
+ pImpl->renderer->viewport(pImpl->vport);
+ pImpl->status = Status::Damaged; // Paints must be updated again with this new target.
- if (!renderer->target(display, surface, context, id, w, h, cs)) return Result::Unknown;
- pImpl->vport = {{0, 0}, {(int32_t)w, (int32_t)h}};
- renderer->viewport(pImpl->vport);
-
- //Paints must be updated again with this new target.
- pImpl->status = Status::Damaged;
+ //FIXME: The value must be associated with an individual canvas instance.
+ BitmapLoader::cs = static_cast<ColorSpace>(cs);
return Result::Success;
#endif
@@ -204,9 +201,10 @@ Result GlCanvas::target(void* display, void* surface, void* context, int32_t id,
GlCanvas* GlCanvas::gen(EngineOption op) noexcept
{
-#ifdef THORVG_GL_RASTER_SUPPORT
+#ifdef THORVG_GL_ENGINE_SUPPORT
if (engineInit > 0) {
- if (op == EngineOption::SmartRender) TVGLOG("RENDERER", "GlCanvas doesn't support Smart Rendering");
+ if (op & EngineOption::SmartRender) TVGLOG("RENDERER", "GlCanvas doesn't support Smart Rendering");
+ if (op & EngineOption::Aliased) TVGLOG("RENDERER", "GlCanvas doesn't support Aliased");
auto renderer = GlRenderer::gen(TaskScheduler::threads(), op);
if (!renderer) return nullptr;
renderer->ref();
@@ -215,6 +213,7 @@ GlCanvas* GlCanvas::gen(EngineOption op) noexcept
return ret;
}
#endif
+ TVGLOG("RENDERER", "GlCanvas is not supported");
return nullptr;
}
@@ -227,46 +226,44 @@ WgCanvas::WgCanvas() = default;
WgCanvas::~WgCanvas()
{
-#ifdef THORVG_WG_RASTER_SUPPORT
- auto renderer = static_cast<WgRenderer*>(pImpl->renderer);
- renderer->target(nullptr, nullptr, nullptr, 0, 0, ColorSpace::Unknown);
+#ifdef THORVG_WG_ENGINE_SUPPORT
+ static_cast<WgRenderer*>(pImpl->renderer)->target({}, nullptr, 0, 0, ColorSpace::Unknown);
WgRenderer::term();
#endif
}
-
Result WgCanvas::target(void* device, void* instance, void* target, uint32_t w, uint32_t h, ColorSpace cs, int type) noexcept
{
-#ifdef THORVG_WG_RASTER_SUPPORT
- if (cs != ColorSpace::ABGR8888S) return Result::NonSupport;
+ return WgCanvas::target({instance, nullptr, device}, target, w, h, cs, type);
+}
- if (pImpl->status == Status::Updating || pImpl->status == Status::Drawing) {
- return Result::InsufficientCondition;
- }
+Result WgCanvas::target(const Context& context, void* target, uint32_t w, uint32_t h, ColorSpace cs, int type) noexcept
+{
+#ifdef THORVG_WG_ENGINE_SUPPORT
+ if (pImpl->status == Status::Updating || pImpl->status == Status::Drawing) return Result::InsufficientCondition;
- //We know renderer type, avoid dynamic_cast for performance.
- auto renderer = static_cast<WgRenderer*>(pImpl->renderer);
- if (!renderer) return Result::MemoryCorruption;
+ auto ret = static_cast<WgRenderer*>(pImpl->renderer)->target(context, target, w, h, cs, type);
+ if (ret != Result::Success) return ret;
- if (!renderer->target((WGPUDevice)device, (WGPUInstance)instance, target, w, h, cs, type)) return Result::Unknown;
- pImpl->vport = {{0, 0}, {(int32_t)w, (int32_t)h}};
- renderer->viewport(pImpl->vport);
+ pImpl->vport = {0, 0, (int32_t)w, (int32_t)h};
+ pImpl->renderer->viewport(pImpl->vport);
+ pImpl->status = Status::Damaged; // Paints must be updated again with this new target.
- //Paints must be updated again with this new target.
- pImpl->status = Status::Damaged;
+ //FIXME: The value must be associated with an individual canvas instance.
+ BitmapLoader::cs = static_cast<ColorSpace>(cs);
return Result::Success;
#endif
return Result::NonSupport;
}
-
WgCanvas* WgCanvas::gen(EngineOption op) noexcept
{
-#ifdef THORVG_WG_RASTER_SUPPORT
+#ifdef THORVG_WG_ENGINE_SUPPORT
if (engineInit > 0) {
- if (op == EngineOption::SmartRender) TVGLOG("RENDERER", "WgCanvas doesn't support Smart Rendering");
+ if (op & EngineOption::SmartRender) TVGLOG("RENDERER", "WgCanvas doesn't support Smart Rendering");
+ if (op & EngineOption::Aliased) TVGLOG("RENDERER", "WgCanvas doesn't support Aliased");
auto renderer = new WgRenderer(TaskScheduler::threads(), op);
renderer->ref();
auto ret = new WgCanvas;
@@ -274,5 +271,6 @@ WgCanvas* WgCanvas::gen(EngineOption op) noexcept
return ret;
}
#endif
+ TVGLOG("RENDERER", "WgCanvas is not supported");
return nullptr;
}
diff --git a/thirdparty/thorvg/src/renderer/tvgCanvas.h b/thirdparty/thorvg/src/renderer/tvgCanvas.h
index a86df243e1f..71dff708373 100644
--- a/thirdparty/thorvg/src/renderer/tvgCanvas.h
+++ b/thirdparty/thorvg/src/renderer/tvgCanvas.h
@@ -31,7 +31,8 @@ struct Canvas::Impl
{
Scene* scene;
RenderMethod* renderer;
- RenderRegion vport = {{0, 0}, {INT32_MAX, INT32_MAX}};
+ RenderRegion vport = {0, 0, INT32_MAX, INT32_MAX};
+ Array<RenderData> clips;
Status status = Status::Synced;
Impl() : scene(Scene::gen())
@@ -82,7 +83,6 @@ struct Canvas::Impl
return Result::InsufficientCondition;
}
- Array<RenderData> clips;
auto flag = RenderUpdateFlag::None;
//TODO: All is too harsh, can be optimized.
@@ -90,6 +90,8 @@ struct Canvas::Impl
if (!renderer->preUpdate()) return Result::InsufficientCondition;
+ clips.clear();
+
auto m = tvg::identity();
PAINT(scene)->update(renderer, m, clips, 255, flag);
@@ -129,11 +131,11 @@ struct Canvas::Impl
Result viewport(int32_t x, int32_t y, int32_t w, int32_t h)
{
if (status == Status::Synced || status == Status::Damaged) {
- RenderRegion val = {{x, y}, {x + w, y + h}};
+ RenderRegion val = {x, y, x + w, y + h};
//intersect if the target buffer is already set.
auto surface = renderer->mainSurface();
if (surface && surface->w > 0 && surface->h > 0) {
- val.intersect({{0, 0}, {(int32_t)surface->w, (int32_t)surface->h}});
+ val.intersect({0, 0, (int32_t)surface->w, (int32_t)surface->h});
}
if (vport == val) return Result::Success;
renderer->viewport(val);
@@ -144,6 +146,16 @@ struct Canvas::Impl
TVGLOG("RENDERER", "viewport() is only allowed after sync.");
return Result::InsufficientCondition;
}
+
+ uint32_t dirtyRegions() const
+ {
+ return (status == Status::Drawing) ? renderer->dirtyRegions() : 0;
+ }
+
+ Result dirtyRegions(Region* regions, uint32_t cnt) const
+ {
+ return (status == Status::Drawing) ? renderer->dirtyRegions(regions, cnt) : Result::InsufficientCondition;
+ }
};
#endif /* _TVG_CANVAS_H_ */
diff --git a/thirdparty/thorvg/src/renderer/tvgFill.cpp b/thirdparty/thorvg/src/renderer/tvgFill.cpp
index ae0a4d7b000..d9ddc963251 100644
--- a/thirdparty/thorvg/src/renderer/tvgFill.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgFill.cpp
@@ -73,6 +73,7 @@ Fill* Fill::duplicate() const noexcept
{
if (type() == Type::LinearGradient) return CONST_LINEAR(this)->duplicate();
else if (type() == Type::RadialGradient) return CONST_RADIAL(this)->duplicate();
+ else if (type() == Type::ConicGradient) return CONST_CONIC(this)->duplicate();
return nullptr;
}
@@ -137,3 +138,29 @@ Type LinearGradient::type() const noexcept
{
return Type::LinearGradient;
}
+
+/************************************************************************/
+/* ConicGradient Class Implementation */
+/************************************************************************/
+
+ConicGradient::ConicGradient() = default;
+
+Result ConicGradient::conic(float cx, float cy, float angle) noexcept
+{
+ return CONIC(this)->conic(cx, cy, angle);
+}
+
+Result ConicGradient::conic(float* cx, float* cy, float* angle) const noexcept
+{
+ return CONST_CONIC(this)->conic(cx, cy, angle);
+}
+
+ConicGradient* ConicGradient::gen() noexcept
+{
+ return new ConicGradientImpl;
+}
+
+Type ConicGradient::type() const noexcept
+{
+ return Type::ConicGradient;
+}
diff --git a/thirdparty/thorvg/src/renderer/tvgFill.h b/thirdparty/thorvg/src/renderer/tvgFill.h
index ae5bff66f30..fc8b0af1b50 100644
--- a/thirdparty/thorvg/src/renderer/tvgFill.h
+++ b/thirdparty/thorvg/src/renderer/tvgFill.h
@@ -32,6 +32,9 @@
#define RADIAL(A) static_cast<RadialGradientImpl*>(A)
#define CONST_RADIAL(A) static_cast<const RadialGradientImpl*>(A)
+#define CONIC(A) static_cast<ConicGradientImpl*>(A)
+#define CONST_CONIC(A) static_cast<const ConicGradientImpl*>(A)
+
struct Fill::Impl
{
ColorStop* colorStops = nullptr;
@@ -194,5 +197,43 @@ struct LinearGradientImpl : LinearGradient
}
};
+struct ConicGradientImpl : ConicGradient
+{
+ Fill::Impl impl;
+ Point center{};
+ float angle = 0.0f;
+
+ ConicGradientImpl()
+ {
+ Fill::pImpl = &impl;
+ }
+
+ Fill* duplicate() const
+ {
+ auto ret = ConicGradient::gen();
+ CONIC(ret)->impl.copy(this->impl);
+ CONIC(ret)->center = center;
+ CONIC(ret)->angle = angle;
+
+ return ret;
+ }
+
+ Result conic(float cx, float cy, float angle) noexcept
+ {
+ this->center = {cx, cy};
+ this->angle = angle;
+
+ return Result::Success;
+ }
+
+ Result conic(float* cx, float* cy, float* angle) const noexcept
+ {
+ if (cx) *cx = center.x;
+ if (cy) *cy = center.y;
+ if (angle) *angle = this->angle;
+
+ return Result::Success;
+ }
+};
#endif //_TVG_FILL_H_
diff --git a/thirdparty/thorvg/src/renderer/tvgInitializer.cpp b/thirdparty/thorvg/src/renderer/tvgInitializer.cpp
index 6c7777889f2..74502807d8e 100644
--- a/thirdparty/thorvg/src/renderer/tvgInitializer.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgInitializer.cpp
@@ -21,18 +21,19 @@
*/
#include "tvgCommon.h"
+#include "tvgLock.h"
#include "tvgTaskScheduler.h"
-#include "tvgLoader.h"
+#include "tvgLoaderMgr.h"
-#ifdef THORVG_SW_RASTER_SUPPORT
+#ifdef THORVG_CPU_ENGINE_SUPPORT
#include "tvgSwRenderer.h"
#endif
-#ifdef THORVG_GL_RASTER_SUPPORT
+#ifdef THORVG_GL_ENGINE_SUPPORT
#include "tvgGlRenderer.h"
#endif
-#ifdef THORVG_WG_RASTER_SUPPORT
+#ifdef THORVG_WG_ENGINE_SUPPORT
#include "tvgWgRenderer.h"
#endif
@@ -46,7 +47,7 @@ namespace tvg {
}
static uint16_t _version = 0;
-
+static StrictKey _key;
static bool _buildVersionInfo(uint32_t* major, uint32_t* minor, uint32_t* micro)
{
@@ -82,12 +83,14 @@ static bool _buildVersionInfo(uint32_t* major, uint32_t* minor, uint32_t* micro)
Result Initializer::init(uint32_t threads) noexcept
{
+ ScopedLock lock(_key);
if (engineInit++ > 0) return Result::Success;
if (!_buildVersionInfo(nullptr, nullptr, nullptr)) return Result::Unknown;
if (!LoaderMgr::init()) return Result::Unknown;
+ // TODO: TaskScheduler would hinder multithreaded use of ThorVG.
TaskScheduler::init(threads);
return Result::Success;
@@ -96,21 +99,23 @@ Result Initializer::init(uint32_t threads) noexcept
Result Initializer::term() noexcept
{
+ ScopedLock lock(_key);
+
if (engineInit == 0) return Result::InsufficientCondition;
if (--engineInit > 0) return Result::Success;
- #ifdef THORVG_SW_RASTER_SUPPORT
- if (!SwRenderer::term()) return Result::InsufficientCondition;
- #endif
+#ifdef THORVG_CPU_ENGINE_SUPPORT
+ if (!SwRenderer::term()) return Result::InsufficientCondition;
+#endif
- #ifdef THORVG_GL_RASTER_SUPPORT
- if (!GlRenderer::term()) return Result::InsufficientCondition;
- #endif
+#ifdef THORVG_GL_ENGINE_SUPPORT
+ if (!GlRenderer::term()) return Result::InsufficientCondition;
+#endif
- #ifdef THORVG_WG_RASTER_SUPPORT
- if (!WgRenderer::term()) return Result::InsufficientCondition;
- #endif
+#ifdef THORVG_WG_ENGINE_SUPPORT
+ if (!WgRenderer::term()) return Result::InsufficientCondition;
+#endif
TaskScheduler::term();
diff --git a/thirdparty/thorvg/src/renderer/tvgLoadModule.h b/thirdparty/thorvg/src/renderer/tvgLoadModule.h
deleted file mode 100644
index d9fe2783aa7..00000000000
--- a/thirdparty/thorvg/src/renderer/tvgLoadModule.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
-
- * 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.
- */
-
-#ifndef _TVG_LOAD_MODULE_H_
-#define _TVG_LOAD_MODULE_H_
-
-#include <atomic>
-#include "tvgCommon.h"
-#include "tvgRender.h"
-#include "tvgInlist.h"
-
-
-struct AssetResolver
-{
- std::function<bool(Paint* paint, const char* src, void* data)> func;
- void* data;
-};
-
-
-namespace tvg
-{
-
-struct LoadModule
-{
- INLIST_ITEM(LoadModule);
-
- //Use either hashkey(data) or hashpath(path)
- uintptr_t hashkey = 0;
- char* hashpath = nullptr;
-
- FileType type; //current loader file type
- atomic<uint16_t> sharing{}; //reference count
- bool readied = false; //read done already.
- bool cached = false; //cached for sharing
-
- LoadModule(FileType type) : type(type) {}
- virtual ~LoadModule()
- {
- tvg::free(hashpath);
- }
-
- void cache(uintptr_t data)
- {
- hashkey = data;
- cached = true;
- }
-
- void cache(char* data)
- {
- hashpath = data;
- cached = true;
- }
-
- virtual bool open(const char* path) { return false; }
- virtual bool open(const char* data, uint32_t size, const char* rpath, bool copy) { return false; }
- virtual bool resize(Paint* paint, float w, float h) { return false; }
- virtual void sync() {}; //finish immediately if any async update jobs.
-
- virtual bool read()
- {
- if (readied) return false;
- readied = true;
- return true;
- }
-
- virtual bool close()
- {
- if (sharing == 0) return true;
- --sharing;
- return false;
- }
-
- char* open(const char* path, uint32_t& size, bool text = false)
- {
-#ifdef THORVG_FILE_IO_SUPPORT
- auto f = fopen(path, text ? "r" : "rb");
- if (!f) return nullptr;
-
- fseek(f, 0, SEEK_END);
-
- size = ftell(f);
- if (size == 0) {
- fclose(f);
- return nullptr;
- }
-
- auto content = tvg::malloc<char>(sizeof(char) * (text ? size + 1 : size));
- fseek(f, 0, SEEK_SET);
- size = fread(content, sizeof(char), size, f);
- if (text) content[size] = '\0';
-
- fclose(f);
-
- return content;
-#endif
- return nullptr;
- }
-};
-
-
-struct ImageLoader : LoadModule
-{
- static atomic<ColorSpace> cs; //desired value
-
- float w = 0, h = 0; //default image size
- RenderSurface surface;
-
- ImageLoader(FileType type) : LoadModule(type) {}
-
- virtual bool animatable() { return false; } //true if this loader supports animation.
- virtual Paint* paint() { return nullptr; }
- virtual void set(const AssetResolver* resolver) {}
-
- virtual RenderSurface* bitmap()
- {
- if (surface.data) return &surface;
- return nullptr;
- }
-};
-
-
-struct FontMetrics
-{
- Point size; //text width, height
- float scale;
- Point align{}, box{}, spacing{1.0f, 1.0f};
- float fontSize = 0.0f;
- uint32_t lines = 1; //line count
- TextWrap wrap = TextWrap::None;
-
- void *engine = nullptr; //engine extension
-
- ~FontMetrics()
- {
- tvg::free(engine);
- }
-};
-
-
-struct FontLoader : LoadModule
-{
- static constexpr const float DPI = 96.0f / 72.0f; //dpi base?
-
- char* name = nullptr;
-
- FontLoader(FileType type) : LoadModule(type) {}
-
- using LoadModule::read;
-
- virtual bool get(FontMetrics& fm, char* text, uint32_t len, RenderPath& out) = 0;
- virtual void transform(Paint* paint, FontMetrics& fm, float italicShear) = 0;
- virtual void release(FontMetrics& fm) = 0;
- virtual void metrics(const FontMetrics& fm, TextMetrics& out) = 0;
- virtual bool metrics(const FontMetrics& fm, const char* ch, GlyphMetrics& out) = 0;
- virtual void copy(const FontMetrics& in, FontMetrics& out) = 0;
-};
-
-}
-
-#endif //_TVG_LOAD_MODULE_H_
diff --git a/thirdparty/thorvg/src/renderer/tvgLoader.cpp b/thirdparty/thorvg/src/renderer/tvgLoader.cpp
deleted file mode 100644
index 537990c4109..00000000000
--- a/thirdparty/thorvg/src/renderer/tvgLoader.cpp
+++ /dev/null
@@ -1,453 +0,0 @@
-/*
- * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
-
- * 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 <atomic>
-#include "tvgInlist.h"
-#include "tvgStr.h"
-#include "tvgLoader.h"
-#include "tvgLock.h"
-
-#ifdef THORVG_SVG_LOADER_SUPPORT
- #include "tvgSvgLoader.h"
-#endif
-
-#ifdef THORVG_PNG_LOADER_SUPPORT
- #include "tvgPngLoader.h"
-#endif
-
-#ifdef THORVG_JPG_LOADER_SUPPORT
- #include "tvgJpgLoader.h"
-#endif
-
-#ifdef THORVG_WEBP_LOADER_SUPPORT
- #include "tvgWebpLoader.h"
-#endif
-
-#ifdef THORVG_TTF_LOADER_SUPPORT
- #include "tvgTtfLoader.h"
-#endif
-
-#ifdef THORVG_LOTTIE_LOADER_SUPPORT
- #include "tvgLottieLoader.h"
-#endif
-
-#include "tvgRawLoader.h"
-
-
-uintptr_t HASH_KEY(const char* data)
-{
- return reinterpret_cast<uintptr_t>(data);
-}
-
-/************************************************************************/
-/* Internal Class Implementation */
-/************************************************************************/
-
-//TODO: remove it.
-atomic<ColorSpace> ImageLoader::cs{ColorSpace::ARGB8888};
-
-static Key _key;
-static Inlist<tvg::LoadModule> _activeLoaders;
-
-
-static tvg::LoadModule* _find(FileType type)
-{
- switch(type) {
- case FileType::Png: {
-#ifdef THORVG_PNG_LOADER_SUPPORT
- return new PngLoader;
-#endif
- break;
- }
- case FileType::Jpg: {
-#ifdef THORVG_JPG_LOADER_SUPPORT
- return new JpgLoader;
-#endif
- break;
- }
- case FileType::Webp: {
-#ifdef THORVG_WEBP_LOADER_SUPPORT
- return new WebpLoader;
-#endif
- break;
- }
- case FileType::Svg: {
-#ifdef THORVG_SVG_LOADER_SUPPORT
- return new SvgLoader;
-#endif
- break;
- }
- case FileType::Ttf: {
-#ifdef THORVG_TTF_LOADER_SUPPORT
- return new TtfLoader;
-#endif
- break;
- }
- case FileType::Lot: {
-#ifdef THORVG_LOTTIE_LOADER_SUPPORT
- return new LottieLoader;
-#endif
- break;
- }
- case FileType::Raw: {
- return new RawLoader;
- break;
- }
- default: {
- break;
- }
- }
-
-#ifdef THORVG_LOG_ENABLED
- const char *format;
- switch(type) {
- case FileType::Svg: {
- format = "SVG";
- break;
- }
- case FileType::Ttf: {
- format = "TTF";
- break;
- }
- case FileType::Lot: {
- format = "LOT";
- break;
- }
- case FileType::Raw: {
- format = "RAW";
- break;
- }
- case FileType::Png: {
- format = "PNG";
- break;
- }
- case FileType::Jpg: {
- format = "JPG";
- break;
- }
- case FileType::Webp: {
- format = "WEBP";
- break;
- }
- default: {
- format = "???";
- break;
- }
- }
- TVGLOG("RENDERER", "%s format is not supported", format);
-#endif
- return nullptr;
-}
-
-
-#ifdef THORVG_FILE_IO_SUPPORT
-static tvg::LoadModule* _findByPath(const char* filename)
-{
- auto ext = fileext(filename);
- if (!ext) return nullptr;
-
- if (!strcmp(ext, "svg")) return _find(FileType::Svg);
- if (!strcmp(ext, "lot") || !strcmp(ext, "json")) return _find(FileType::Lot);
- if (!strcmp(ext, "png")) return _find(FileType::Png);
- if (!strcmp(ext, "jpg")) return _find(FileType::Jpg);
- if (!strcmp(ext, "webp")) return _find(FileType::Webp);
- if (!strcmp(ext, "ttf") || !strcmp(ext, "ttc")) return _find(FileType::Ttf);
- if (!strcmp(ext, "otf") || !strcmp(ext, "otc")) return _find(FileType::Ttf);
- return nullptr;
-}
-#endif
-
-
-static FileType _convert(const char* mimeType)
-{
- if (!mimeType) return FileType::Unknown;
-
- auto type = FileType::Unknown;
-
- if (!strcmp(mimeType, "svg") || !strcmp(mimeType, "svg+xml")) type = FileType::Svg;
- else if (!strcmp(mimeType, "ttf") || !strcmp(mimeType, "otf")) type = FileType::Ttf;
- else if (!strcmp(mimeType, "lot") || !strcmp(mimeType, "lottie+json")) type = FileType::Lot;
- else if (!strcmp(mimeType, "raw")) type = FileType::Raw;
- else if (!strcmp(mimeType, "png")) type = FileType::Png;
- else if (!strcmp(mimeType, "jpg") || !strcmp(mimeType, "jpeg")) type = FileType::Jpg;
- else if (!strcmp(mimeType, "webp")) type = FileType::Webp;
- else TVGLOG("RENDERER", "Given mimetype is unknown = \"%s\".", mimeType);
-
- return type;
-}
-
-
-static tvg::LoadModule* _findByType(const char* mimeType)
-{
- return _find(_convert(mimeType));
-}
-
-
-static tvg::LoadModule* _findFromCache(const char* filename)
-{
- ScopedLock lock(_key);
- INLIST_FOREACH(_activeLoaders, loader) {
- if (loader->cached && loader->hashpath && !strcmp(loader->hashpath, filename)) {
- ++loader->sharing;
- return loader;
- }
- }
- return nullptr;
-}
-
-
-static tvg::LoadModule* _findFromCache(const char* data, uint32_t size, const char* mimeType)
-{
- auto type = _convert(mimeType);
- if (type == FileType::Unknown) return nullptr;
-
- auto key = HASH_KEY(data);
-
- ScopedLock lock(_key);
-
- INLIST_FOREACH(_activeLoaders, loader) {
- if (loader->type == type && loader->hashkey == key) {
- ++loader->sharing;
- return loader;
- }
- }
- return nullptr;
-}
-
-
-/************************************************************************/
-/* External Class Implementation */
-/************************************************************************/
-
-
-bool LoaderMgr::init()
-{
- return true;
-}
-
-
-bool LoaderMgr::term()
-{
- //clean up the remained font loaders which is globally used.
- INLIST_SAFE_FOREACH(_activeLoaders, loader) {
- if (loader->type != FileType::Ttf) continue;
- auto ret = loader->close();
- _activeLoaders.remove(loader);
- if (ret) delete(loader);
- }
- return true;
-}
-
-
-bool LoaderMgr::retrieve(LoadModule* loader)
-{
- if (!loader) return false;
-
- if (loader->close()) {
- if (loader->cached) {
- _activeLoaders.remove(loader);
- }
- delete(loader);
- }
- return true;
-}
-
-
-tvg::LoadModule* LoaderMgr::loader(const char* filename, bool* invalid)
-{
-#ifdef THORVG_FILE_IO_SUPPORT
- *invalid = false;
-
- //TODO: make lottie sharable.
- auto allowCache = true;
- auto ext = fileext(filename);
- if (ext && (!strcmp(ext, "json") || !strcmp(ext, "lot"))) allowCache = false;
-
- if (allowCache) {
- if (auto loader = _findFromCache(filename)) return loader;
- }
-
- if (auto loader = _findByPath(filename)) {
- if (loader->open(filename)) {
- if (allowCache) {
- loader->cache(duplicate(filename));
- {
- ScopedLock lock(_key);
- _activeLoaders.back(loader);
- }
- }
- return loader;
- }
- delete(loader);
- }
- //Unknown MimeType. Try with the candidates in the order
- for (int i = 0; i < static_cast<int>(FileType::Raw); i++) {
- if (auto loader = _find(static_cast<FileType>(i))) {
- if (loader->open(filename)) {
- if (allowCache) {
- loader->cache(duplicate(filename));
- {
- ScopedLock lock(_key);
- _activeLoaders.back(loader);
- }
- }
- return loader;
- }
- delete(loader);
- }
- }
- *invalid = true;
-#endif
- return nullptr;
-}
-
-
-bool LoaderMgr::retrieve(const char* filename)
-{
- return retrieve(_findFromCache(filename));
-}
-
-
-tvg::LoadModule* LoaderMgr::loader(const char* data, uint32_t size, const char* mimeType, const char* rpath, bool copy)
-{
- //Note that users could use the same data pointer with the different content.
- //Thus caching is only valid for shareable.
- auto allowCache = !copy;
-
- //TODO: make lottie shareable.
- if (allowCache) {
- auto type = _convert(mimeType);
- if (type == FileType::Lot) allowCache = false;
- }
-
- if (allowCache) {
- if (auto loader = _findFromCache(data, size, mimeType)) return loader;
- }
-
- //Try with the given MimeType
- if (mimeType) {
- if (auto loader = _findByType(mimeType)) {
- if (loader->open(data, size, rpath, copy)) {
- if (allowCache) {
- loader->cache(HASH_KEY(data));
- ScopedLock lock(_key);
- _activeLoaders.back(loader);
- }
- return loader;
- } else {
- TVGLOG("LOADER", "Given mimetype \"%s\" seems incorrect or not supported.", mimeType);
- delete(loader);
- }
- }
- }
- //Unknown MimeType. Try with the candidates in the order
- for (int i = 0; i < static_cast<int>(FileType::Raw); i++) {
- auto loader = _find(static_cast<FileType>(i));
- if (loader) {
- if (loader->open(data, size, rpath, copy)) {
- if (allowCache) {
- loader->cache(HASH_KEY(data));
- ScopedLock lock(_key);
- _activeLoaders.back(loader);
- }
- return loader;
- }
- delete(loader);
- }
- }
- return nullptr;
-}
-
-
-tvg::LoadModule* LoaderMgr::loader(const uint32_t *data, uint32_t w, uint32_t h, ColorSpace cs, bool copy)
-{
- //Note that users could use the same data pointer with the different content.
- //Thus caching is only valid for shareable.
- if (!copy) {
- //TODO: should we check premultiplied??
- if (auto loader = _findFromCache((const char*)(data), w * h, "raw")) return loader;
- }
-
- //function is dedicated for raw images only
- auto loader = new RawLoader;
- if (loader->open(data, w, h, cs, copy)) {
- if (!copy) {
- loader->cache(HASH_KEY((const char*)data));
- ScopedLock lock(_key);
- _activeLoaders.back(loader);
- }
- return loader;
- }
- delete(loader);
- return nullptr;
-}
-
-
-//loads fonts from memory - loader is cached (regardless of copy value) in order to access it while setting font
-tvg::LoadModule* LoaderMgr::loader(const char* name, const char* data, uint32_t size, TVG_UNUSED const char* mimeType, bool copy)
-{
-#ifdef THORVG_TTF_LOADER_SUPPORT
- //TODO: add check for mimetype ?
- if (auto loader = font(name)) return loader;
-
- //function is dedicated for ttf loader (the only supported font loader)
- auto loader = new TtfLoader;
- if (loader->open(data, size, "", copy)) {
- loader->name = duplicate(name);
- loader->cached = true; //force it.
- ScopedLock lock(_key);
- _activeLoaders.back(loader);
- return loader;
- }
-
- TVGLOG("LOADER", "The font data \"%s\" could not be loaded.", name);
- delete(loader);
-#endif
- return nullptr;
-}
-
-
-tvg::LoadModule* LoaderMgr::font(const char* name)
-{
- ScopedLock lock(_key);
- INLIST_FOREACH(_activeLoaders, loader) {
- if (loader->type != FileType::Ttf) continue;
- if (loader->cached && tvg::equal(name, static_cast<FontLoader*>(loader)->name)) {
- ++loader->sharing;
- return loader;
- }
- }
- return nullptr;
-}
-
-
-tvg::LoadModule* LoaderMgr::anyfont()
-{
- ScopedLock lock(_key);
- INLIST_FOREACH(_activeLoaders, loader) {
- if (loader->cached && loader->type == FileType::Ttf) {
- ++loader->sharing;
- return loader;
- }
- }
- return nullptr;
-}
diff --git a/thirdparty/thorvg/src/renderer/tvgLoader.h b/thirdparty/thorvg/src/renderer/tvgLoader.h
index 5b345e212f5..3d94785d32e 100644
--- a/thirdparty/thorvg/src/renderer/tvgLoader.h
+++ b/thirdparty/thorvg/src/renderer/tvgLoader.h
@@ -23,25 +23,221 @@
#ifndef _TVG_LOADER_H_
#define _TVG_LOADER_H_
-#include "tvgLoadModule.h"
+#include <atomic>
+#include "tvgCommon.h"
+#include "tvgRender.h"
+#include "tvgInlist.h"
+#include "tvgStr.h"
+#include "tvgAccessor.h"
namespace tvg
{
-struct LoaderMgr
+struct AssetResolver
{
- static bool init();
- static bool term();
- static LoadModule* loader(const char* filename, bool* invalid);
- static LoadModule* loader(const char* data, uint32_t size, const char* mimeType, const char* rpath, bool copy);
- static LoadModule* loader(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, bool copy);
- static LoadModule* loader(const char* name, const char* data, uint32_t size, const char* mimeType, bool copy);
- static LoadModule* font(const char* name);
- static LoadModule* anyfont();
- static bool retrieve(const char* filename);
- static bool retrieve(LoadModule* loader);
+ std::function<bool(Paint* paint, const char* src, void* data)> func;
+ void* data;
};
+// Specifying how ownership of supplied data is handled.
+enum struct Ownership : uint8_t
+{
+ Borrow, ///< The data remains owned by the caller and must stay valid while in use. (do not free it)
+ Copy, ///< The data is copied, and the caller retains ownership of the original. (must free it)
+ Transfer ///< Ownership of the data is transferred to the loaders. (must free it)
+};
+
+struct LoaderOps
+{
+ Type caller; // which requests this?
+ Ownership owner;
+};
+
+struct PictureOps : LoaderOps
+{
+ AssetResolver* resolver;
+ const char* rpath; // decide the relative path file if the file is loaded from memory
+ bool accessible; // allow the accessor
+
+ PictureOps(Ownership owner, AssetResolver* resolver, const char* rpath, bool accessible) :
+ LoaderOps{Type::Picture, owner}, resolver(resolver), rpath(rpath), accessible(accessible) {}
+};
+
+struct Loader
+{
+ INLIST_ITEM(Loader);
+
+ // Use either hashkey(data) or hashpath(path)
+ uintptr_t hashkey = 0;
+ char* hashpath = nullptr;
+
+ FileType type; // current loader file type
+ atomic<uint16_t> sharing{}; // reference count
+ Ownership owner = Ownership::Borrow;
+ bool readied = false; // read done already
+ bool cached = false; // cached for sharing
+
+ Loader(FileType type) : type(type) {}
+
+ virtual ~Loader()
+ {
+ tvg::free(hashpath);
+ }
+
+ bool allowCache()
+ {
+ if (type == FileType::Lot) return false;
+ if (type == FileType::Gif) return false;
+ if (type == FileType::Media) return false;
+
+ return true;
+ }
+
+ bool cache(uintptr_t data)
+ {
+ if (!allowCache()) return false;
+ hashkey = data;
+ cached = true;
+ return true;
+ }
+
+ bool cache(const char* path)
+ {
+ if (!allowCache()) return false;
+
+ hashpath = tvg::duplicate(path);
+ cached = true;
+ return true;
+ }
+
+ virtual Result open(const char* path, const LoaderOps& ops) { return Result::NonSupport; }
+ virtual Result open(const char* data, uint32_t size, const LoaderOps& ops) { return Result::NonSupport; }
+ virtual bool resize(Paint* paint, float w, float h) { return false; }
+ virtual bool sync() { return false; }; // finish immediately if any async update jobs, return true if something has been updated.
+
+ virtual bool read()
+ {
+ if (readied) return false;
+ readied = true;
+ return true;
+ }
+
+ virtual bool close()
+ {
+ if (sharing == 0) return true;
+ --sharing;
+ return false;
+ }
+
+ char* open(const char* path, uint32_t& size, bool text = false)
+ {
+#ifdef THORVG_FILE_IO_SUPPORT
+ auto f = fopen(path, text ? "r" : "rb");
+ if (!f) return nullptr;
+
+ fseek(f, 0, SEEK_END);
+
+ size = ftell(f);
+ if (size == 0) {
+ fclose(f);
+ return nullptr;
+ }
+
+ auto content = tvg::malloc<char>(sizeof(char) * (text ? size + 1 : size));
+ fseek(f, 0, SEEK_SET);
+ size = fread(content, sizeof(char), size, f);
+ if (text) content[size] = '\0';
+
+ fclose(f);
+
+ return content;
+#endif
+ return nullptr;
+ }
+};
+
+struct ImageLoader : Loader
+{
+ float w = 0, h = 0; // default image size
+ bool playable; // true if this loader supports playback
+
+ ImageLoader(FileType type, bool playable = false) : Loader(type), playable(playable) {}
+
+ virtual const AccessorEntity* access(uint32_t id) { return nullptr; }
+ virtual void access(AccessorCallback& cb) {}
+ virtual Paint* paint() { return nullptr; }
+ virtual RenderSurface* bitmap() { return nullptr; }
+};
+
+struct BitmapLoader : ImageLoader
+{
+ static atomic<ColorSpace> cs; // desired value
+
+ RenderSurface surface;
+
+ BitmapLoader(FileType type, bool playable = false) : ImageLoader(type, playable) {}
+
+ RenderSurface* bitmap() override
+ {
+ return surface.data ? &surface : nullptr;
+ }
+};
+
+struct AnimLoader : ImageLoader
+{
+ float segmentBegin = 0.0f;
+ float segmentEnd; // initialize the value with the total frame number
+
+ AnimLoader(FileType type) : ImageLoader(type, true) {}
+ virtual ~AnimLoader() {}
+
+ virtual bool frame(float no) = 0; // set the current frame number
+ virtual float totalFrame() = 0; // return the total frame count
+ virtual float curFrame() = 0; // return the current frame number
+ virtual float duration() = 0; // return the animation duration in seconds
+ virtual Result segment(float begin, float end) = 0;
+
+ void segment(float* begin, float* end)
+ {
+ if (begin) *begin = segmentBegin;
+ if (end) *end = segmentEnd;
+ }
+};
+
+struct FontMetrics
+{
+ Point size; // text width, height
+ float scale;
+ Point align{}, box{}, spacing{1.0f, 1.0f};
+ float fontSize = 0.0f;
+ uint32_t lines = 1; // line count
+ TextWrap wrap = TextWrap::None;
+
+ void* engine = nullptr; // engine extension
+
+ ~FontMetrics()
+ {
+ tvg::free(engine);
+ }
+};
+
+struct FontLoader : Loader
+{
+ static constexpr const float DPI = 96.0f / 72.0f; // dpi base?
+
+ char* name = nullptr;
+
+ FontLoader(FileType type) : Loader(type) {}
+
+ using Loader::read;
+
+ virtual bool get(FontMetrics& fm, char* text, uint32_t len, RenderPath& out) = 0;
+ virtual void transform(Paint* paint, FontMetrics& fm, float italicShear) = 0;
+ virtual void release(FontMetrics& fm) = 0;
+ virtual void metrics(const FontMetrics& fm, TextMetrics& out) = 0;
+ virtual bool metrics(const FontMetrics& fm, const char* ch, GlyphMetrics& out, const char** next) = 0;
+ virtual void copy(const FontMetrics& in, FontMetrics& out) = 0;
+};
}
#endif //_TVG_LOADER_H_
diff --git a/thirdparty/thorvg/src/renderer/tvgLoaderMgr.cpp b/thirdparty/thorvg/src/renderer/tvgLoaderMgr.cpp
new file mode 100644
index 00000000000..e67598c7bb0
--- /dev/null
+++ b/thirdparty/thorvg/src/renderer/tvgLoaderMgr.cpp
@@ -0,0 +1,391 @@
+/*
+ * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
+
+ * 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 <atomic>
+#include "tvgInlist.h"
+#include "tvgLoaderMgr.h"
+#include "tvgLock.h"
+
+#ifdef THORVG_SVG_LOADER_SUPPORT
+ #include "tvgSvgLoader.h"
+#endif
+
+#ifdef THORVG_PNG_LOADER_SUPPORT
+ #include "tvgPngLoader.h"
+#endif
+
+#ifdef THORVG_JPG_LOADER_SUPPORT
+ #include "tvgJpgLoader.h"
+#endif
+
+#ifdef THORVG_WEBP_LOADER_SUPPORT
+ #include "tvgWebpLoader.h"
+#endif
+
+#ifdef THORVG_SFNT_LOADER_SUPPORT
+ #include "tvgSfntLoader.h"
+#endif
+
+#ifdef THORVG_LOTTIE_LOADER_SUPPORT
+ #include "tvgLottieLoader.h"
+#endif
+
+#ifdef THORVG_MEDIA_LOADER_SUPPORT
+ #include "tvgMediaLoader.h"
+#endif
+
+#include "tvgRawLoader.h"
+
+uintptr_t HASH_KEY(const char* data)
+{
+ return reinterpret_cast<uintptr_t>(data);
+}
+
+/************************************************************************/
+/* Internal Class Implementation */
+/************************************************************************/
+
+// TODO: remove it.
+atomic<ColorSpace> BitmapLoader::cs{ColorSpace::ARGB8888};
+
+static Key _key;
+static Inlist<tvg::Loader> _activeLoaders;
+
+static tvg::Loader* _find(FileType type)
+{
+ switch (type) {
+#ifdef THORVG_SVG_LOADER_SUPPORT
+ case FileType::Svg: return new SvgLoader;
+#endif
+#ifdef THORVG_LOTTIE_LOADER_SUPPORT
+ case FileType::Lot: return new LottieLoader;
+#endif
+#ifdef THORVG_SFNT_LOADER_SUPPORT
+ case FileType::Sfnt: return new SfntLoader;
+#endif
+#ifdef THORVG_PNG_LOADER_SUPPORT
+ case FileType::Png: return new PngLoader;
+#endif
+#ifdef THORVG_JPG_LOADER_SUPPORT
+ case FileType::Jpg: return new JpgLoader;
+#endif
+#ifdef THORVG_WEBP_LOADER_SUPPORT
+ case FileType::Webp: return new WebpLoader;
+#endif
+#ifdef THORVG_MEDIA_LOADER_SUPPORT
+ case FileType::Media: return MediaLoader::gen();
+#endif
+ case FileType::Raw: return new RawLoader;
+ default: break;
+ }
+
+#ifdef THORVG_LOG_ENABLED
+ auto toString = [](FileType type) {
+ switch (type) {
+ case FileType::Svg: return "SVG";
+ case FileType::Lot: return "LOT";
+ case FileType::Sfnt: return "SFNT";
+ case FileType::Png: return "PNG";
+ case FileType::Jpg: return "JPG";
+ case FileType::Webp: return "WEBP";
+ case FileType::Media: return "MEDIA";
+ case FileType::Raw: return "RAW";
+ case FileType::Gif: return "GIF";
+ default: return "???";
+ }
+ };
+ TVGLOG("RENDERER", "%s format is not supported", toString(type));
+#endif
+ return nullptr;
+}
+
+#ifdef THORVG_FILE_IO_SUPPORT
+static tvg::Loader* _findByPath(const char* filename, Result& ret)
+{
+ auto ext = fileext(filename);
+ if (ext) {
+ auto type = FileType::Unknown;
+ if (!strcmp(ext, "svg")) type = FileType::Svg;
+ else if (!strcmp(ext, "lot") || !strcmp(ext, "json")) type = FileType::Lot;
+ else if (!strcmp(ext, "ttf") || !strcmp(ext, "ttc") || !strcmp(ext, "otf") || !strcmp(ext, "otc")) type = FileType::Sfnt;
+ else if (!strcmp(ext, "png")) type = FileType::Png;
+ else if (!strcmp(ext, "jpg")) type = FileType::Jpg;
+ else if (!strcmp(ext, "webp")) type = FileType::Webp;
+ else if (!strcmp(ext, "mp4")) type = FileType::Media; // TODO: add common media formats
+ if (type != FileType::Unknown) {
+ ret = Result::NonSupport;
+ return _find(type);
+ }
+ }
+ return nullptr;
+}
+#endif
+
+static FileType _convert(const char* mimeType)
+{
+ if (!mimeType) return FileType::Unknown;
+
+ auto type = FileType::Unknown;
+
+ if (!strcmp(mimeType, "svg") || !strcmp(mimeType, "svg+xml")) type = FileType::Svg;
+ else if (!strcmp(mimeType, "lot") || !strcmp(mimeType, "lottie+json")) type = FileType::Lot;
+ else if (!strcmp(mimeType, "ttf") || !strcmp(mimeType, "otf")) type = FileType::Sfnt;
+ else if (!strcmp(mimeType, "png")) type = FileType::Png;
+ else if (!strcmp(mimeType, "jpg") || !strcmp(mimeType, "jpeg")) type = FileType::Jpg;
+ else if (!strcmp(mimeType, "webp")) type = FileType::Webp;
+ else if (!strcmp(mimeType, "mp4")) type = FileType::Media; // TODO: add common media formats
+ else if (!strcmp(mimeType, "raw")) type = FileType::Raw;
+ else TVGLOG("RENDERER", "Given mimetype is unknown = \"%s\".", mimeType);
+
+ return type;
+}
+
+static tvg::Loader* _findFromCache(const char* filename)
+{
+ ScopedLock lock(_key);
+ INLIST_FOREACH(_activeLoaders, loader) {
+ if (loader->cached && loader->hashpath && !strcmp(loader->hashpath, filename)) {
+ ++loader->sharing;
+ return loader;
+ }
+ }
+ return nullptr;
+}
+
+static tvg::Loader* _findFromCache(const char* data, uint32_t size, const char* mimeType)
+{
+ auto type = _convert(mimeType);
+ if (type == FileType::Unknown) return nullptr;
+
+ auto key = HASH_KEY(data);
+
+ ScopedLock lock(_key);
+
+ INLIST_FOREACH(_activeLoaders, loader) {
+ if (loader->type == type && loader->hashkey == key) {
+ ++loader->sharing;
+ return loader;
+ }
+ }
+ return nullptr;
+}
+
+/************************************************************************/
+/* External Class Implementation */
+/************************************************************************/
+
+bool LoaderMgr::init()
+{
+ return true;
+}
+
+bool LoaderMgr::term()
+{
+ // force clean up the font loaders which is globally used.
+ INLIST_SAFE_FOREACH(_activeLoaders, loader) {
+ if (loader->type != FileType::Sfnt) continue;
+ _activeLoaders.remove(loader);
+ delete (loader);
+ }
+ return true;
+}
+
+bool LoaderMgr::retrieve(Loader* loader)
+{
+ if (!loader) return false;
+
+ if (loader->close()) {
+ if (loader->cached) _activeLoaders.remove(loader);
+ delete (loader);
+ }
+ return true;
+}
+
+tvg::Loader* LoaderMgr::loader(const char* filename, LoaderOps& ops, Result& ret)
+{
+#ifdef THORVG_FILE_IO_SUPPORT
+ if (!filename) return nullptr;
+
+ if (auto loader = _findFromCache(filename)) return loader;
+
+ ret = Result::InvalidArguments;
+
+ if (auto loader = _findByPath(filename, ret)) {
+ // respect the return value here, but ignore trials with unknown MIME types.
+ ret = loader->open(filename, ops);
+ if (ret == Result::Success) {
+ if (loader->cache(filename)) {
+ ScopedLock lock(_key);
+ _activeLoaders.back(loader);
+ }
+ return loader;
+ }
+ delete (loader);
+ }
+
+ if (ret == Result::NonSupport) return nullptr;
+
+ // Unknown MimeType. Try with the candidates in the order
+ for (int i = 0; i < static_cast<int>(FileType::Unknown); i++) {
+ if (auto loader = _find(static_cast<FileType>(i))) {
+ if (loader->open(filename, ops) == Result::Success) {
+ if (loader->cache(filename)) {
+ ScopedLock lock(_key);
+ _activeLoaders.back(loader);
+ }
+ return loader;
+ }
+ delete (loader);
+ }
+ }
+#else
+ TVGLOG("RENDERER", "FILE IO is disabled!");
+ ret = Result::NonSupport;
+#endif
+ return nullptr;
+}
+
+bool LoaderMgr::retrieve(const char* filename)
+{
+ return retrieve(_findFromCache(filename));
+}
+
+tvg::Loader* LoaderMgr::loader(const char* data, uint32_t size, const char* mimeType, LoaderOps& ops, Result& ret)
+{
+ // Note that users could use the same data pointer with the different content.
+ // Thus caching is only valid for shareable.
+ if (ops.owner == Ownership::Borrow) {
+ if (auto loader = _findFromCache(data, size, mimeType)) return loader;
+ }
+
+ // Try with the given MimeType
+ if (mimeType) {
+ auto type = _convert(mimeType);
+ if (type != FileType::Unknown) ret = Result::NonSupport;
+ if (auto loader = _find(type)) {
+ // respect the return value here, but ignore trials with unknown MIME types.
+ ret = loader->open(data, size, ops);
+ if (ret == Result::Success) {
+ if (ops.owner == Ownership::Borrow && loader->cache(HASH_KEY(data))) {
+ ScopedLock lock(_key);
+ _activeLoaders.back(loader);
+ }
+ return loader;
+ } else {
+ TVGLOG("LOADER", "Given mimetype \"%s\" seems incorrect or not supported.", mimeType);
+ delete (loader);
+ }
+ }
+ }
+
+ if (ret == Result::NonSupport) return nullptr;
+
+ // Unknown MimeType. Try with the candidates in the order
+ for (int i = 0; i < static_cast<int>(FileType::Unknown); i++) {
+ auto loader = _find(static_cast<FileType>(i));
+ if (!loader) continue;
+ if (loader->open(data, size, ops) == Result::Success) {
+ if (ops.owner == Ownership::Borrow && loader->cache(HASH_KEY(data))) {
+ ScopedLock lock(_key);
+ _activeLoaders.back(loader);
+ }
+ return loader;
+ }
+ delete (loader);
+ }
+ return nullptr;
+}
+
+tvg::Loader* LoaderMgr::loader(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, Ownership owner)
+{
+ // Note that users could use the same data pointer with the different content.
+ // Thus caching is only valid for shareable.
+ if (owner == Ownership::Borrow) {
+ // TODO: should we check premultiplied??
+ if (auto loader = _findFromCache((const char*)(data), w * h, "raw")) return loader;
+ }
+
+ // function is dedicated for raw images only
+ auto loader = new RawLoader;
+ if (loader->open(data, w, h, cs, owner)) {
+ if (owner == Ownership::Borrow && loader->cache(HASH_KEY((const char*)data))) {
+ ScopedLock lock(_key);
+ _activeLoaders.back(loader);
+ }
+ return loader;
+ }
+ delete (loader);
+ return nullptr;
+}
+
+// Loads fonts from memory. The loader is always cached so it remains available while setting the font.
+tvg::Loader* LoaderMgr::loader(const char* name, const char* data, uint32_t size, TVG_UNUSED const char* mimeType, const LoaderOps& ops)
+{
+#ifdef THORVG_SFNT_LOADER_SUPPORT
+ if (auto loader = font(name)) {
+ // user owned memory can be freed anytime.
+ if (loader->owner != Ownership::Borrow) {
+ if (ops.owner == Ownership::Transfer) tvg::free((char*)data);
+ return loader;
+ }
+ }
+
+ // function is dedicated for SFNT-based font loading
+ auto loader = new SfntLoader;
+ if (loader->open(data, size, ops) == Result::Success) {
+ loader->name = duplicate(name);
+ loader->cached = true; // force it.
+ ScopedLock lock(_key);
+ _activeLoaders.back(loader);
+ return loader;
+ }
+
+ TVGLOG("LOADER", "The font data \"%s\" could not be loaded.", name);
+ delete (loader);
+#endif
+ return nullptr;
+}
+
+tvg::Loader* LoaderMgr::font(const char* name)
+{
+ ScopedLock lock(_key);
+ INLIST_FOREACH(_activeLoaders, loader) {
+ if (loader->type != FileType::Sfnt) continue;
+ if (loader->cached && tvg::equal(name, static_cast<FontLoader*>(loader)->name)) {
+ ++loader->sharing;
+ return loader;
+ }
+ }
+ return nullptr;
+}
+
+tvg::Loader* LoaderMgr::anyfont()
+{
+ ScopedLock lock(_key);
+ INLIST_FOREACH(_activeLoaders, loader) {
+ if (loader->cached && loader->type == FileType::Sfnt) {
+ ++loader->sharing;
+ return loader;
+ }
+ }
+ return nullptr;
+}
diff --git a/thirdparty/thorvg/src/renderer/tvgFrameModule.h b/thirdparty/thorvg/src/renderer/tvgLoaderMgr.h
similarity index 52%
rename from thirdparty/thorvg/src/renderer/tvgFrameModule.h
rename to thirdparty/thorvg/src/renderer/tvgLoaderMgr.h
index b2acfe16c9c..32ce82745e7 100644
--- a/thirdparty/thorvg/src/renderer/tvgFrameModule.h
+++ b/thirdparty/thorvg/src/renderer/tvgLoaderMgr.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2023 - 2026 ThorVG project. All rights reserved.
+ * Copyright (c) 2020 - 2026 ThorVG project. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@@ -20,38 +20,28 @@
* SOFTWARE.
*/
-#ifndef _TVG_FRAME_MODULE_H_
-#define _TVG_FRAME_MODULE_H_
+#ifndef _TVG_LOADER_MGR_H_
+#define _TVG_LOADER_MGR_H_
-#include "tvgLoadModule.h"
+#include "tvgLoader.h"
namespace tvg
{
-class FrameModule: public ImageLoader
+struct LoaderMgr
{
-public:
- float segmentBegin = 0.0f;
- float segmentEnd; //Initialize the value with the total frame number
-
- FrameModule(FileType type) : ImageLoader(type) {}
- virtual ~FrameModule() {}
-
- virtual bool frame(float no) = 0; //set the current frame number
- virtual float totalFrame() = 0; //return the total frame count
- virtual float curFrame() = 0; //return the current frame number
- virtual float duration() = 0; //return the animation duration in seconds
- virtual Result segment(float begin, float end) = 0;
-
- void segment(float* begin, float* end)
- {
- if (begin) *begin = segmentBegin;
- if (end) *end = segmentEnd;
- }
-
- virtual bool animatable() override { return true; }
+ static bool init();
+ static bool term();
+ static Loader* loader(const char* filename, LoaderOps& ops, Result& ret);
+ static Loader* loader(const char* data, uint32_t size, const char* mimeType, LoaderOps& ops, Result& ret);
+ static Loader* loader(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, Ownership owner);
+ static Loader* loader(const char* name, const char* data, uint32_t size, const char* mimeType, const LoaderOps& ops);
+ static Loader* font(const char* name);
+ static Loader* anyfont();
+ static bool retrieve(const char* filename);
+ static bool retrieve(Loader* loader);
};
-}
+} // namespace tvg
-#endif //_TVG_FRAME_MODULE_H_
+#endif //_TVG_LOADER_MGR_H_
diff --git a/thirdparty/thorvg/src/renderer/tvgPaint.cpp b/thirdparty/thorvg/src/renderer/tvgPaint.cpp
index 14dad43e32e..44e8f724f3f 100644
--- a/thirdparty/thorvg/src/renderer/tvgPaint.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgPaint.cpp
@@ -60,10 +60,10 @@ static bool _clipRect(RenderMethod* renderer, const Point* pts, const Matrix& m,
return ((b1 == b2) && (b2 == b3) && (b3 == b4));
};
- if (!pointInConvexQuad({float(before.min.x), float(before.min.y)}, c)) return false;
- if (!pointInConvexQuad({float(before.max.x), float(before.min.y)}, c)) return false;
- if (!pointInConvexQuad({float(before.max.x), float(before.max.y)}, c)) return false;
- if (!pointInConvexQuad({float(before.min.x), float(before.max.y)}, c)) return false;
+ if (!pointInConvexQuad({float(before.xMin), float(before.yMin)}, c)) return false;
+ if (!pointInConvexQuad({float(before.xMax), float(before.yMin)}, c)) return false;
+ if (!pointInConvexQuad({float(before.xMax), float(before.yMax)}, c)) return false;
+ if (!pointInConvexQuad({float(before.xMin), float(before.yMax)}, c)) return false;
//same viewport
return true;
@@ -110,13 +110,13 @@ static bool _compFastTrack(RenderMethod* renderer, Paint* cmpTarget, const Matri
if (v1.x > v2.x) std::swap(v1.x, v2.x);
if (v1.y > v2.y) std::swap(v1.y, v2.y);
- after.min.x = static_cast<int32_t>(nearbyint(v1.x));
- after.min.y = static_cast<int32_t>(nearbyint(v1.y));
- after.max.x = static_cast<int32_t>(nearbyint(v2.x));
- after.max.y = static_cast<int32_t>(nearbyint(v2.y));
+ after.xMin = static_cast<int32_t>(nearbyint(v1.x));
+ after.yMin = static_cast<int32_t>(nearbyint(v1.y));
+ after.xMax = static_cast<int32_t>(nearbyint(v2.x));
+ after.yMax = static_cast<int32_t>(nearbyint(v2.y));
- if (after.max.x < after.min.x) after.max.x = after.min.x;
- if (after.max.y < after.min.y) after.max.y = after.min.y;
+ if (after.xMax < after.xMin) after.xMax = after.xMin;
+ if (after.yMax < after.yMin) after.yMax = after.yMin;
after.intersect(before);
renderer->viewport(after);
@@ -134,10 +134,9 @@ RenderRegion Paint::Impl::bounds()
return ret;
}
-
-Iterator* Paint::Impl::iterator()
+AccessorIterator* Paint::Impl::iterator()
{
- Iterator* ret;
+ AccessorIterator* ret;
PAINT_METHOD(ret, iterator());
return ret;
}
@@ -214,7 +213,6 @@ RenderData Paint::Impl::update(RenderMethod* renderer, const Matrix& pm, Array<R
if (renderFlag & RenderUpdateFlag::Transform) tr.update();
/* 1. Composition Pre Processing */
- RenderData trd = nullptr; //composite target render data
RenderRegion viewport;
auto compFastTrack = false;
@@ -239,9 +237,7 @@ RenderData Paint::Impl::update(RenderMethod* renderer, const Matrix& pm, Array<R
}
}
}
- if (!compFastTrack) {
- trd = PAINT(target)->update(renderer, pm, clips, 255, flag, false);
- }
+ if (!compFastTrack) PAINT(target)->update(renderer, pm, clips, 255, flag, false);
}
/* 2. Clipping */
@@ -254,8 +250,8 @@ RenderData Paint::Impl::update(RenderMethod* renderer, const Matrix& pm, Array<R
compFastTrack = true;
} else {
mark(RenderUpdateFlag::Clip);
- trd = pclip->update(renderer, pm, clips, 255, flag, true);
- clips.push(trd);
+ Array<RenderData> noClip;
+ clips.push(pclip->update(renderer, pm, noClip, 255, flag, true));
}
}
@@ -280,12 +276,12 @@ bool Paint::Impl::bounds(Point* pt4, const Matrix* pm, bool obb)
return ret;
}
-
-bool Paint::Impl::intersects(const RenderRegion& region)
+bool Paint::Impl::intersects(const RenderRegion& region, bool visibleOnly)
{
+ if (visibleOnly && hidden) return false;
if (renderer) {
bool ret;
- PAINT_METHOD(ret, intersects(region));
+ PAINT_METHOD(ret, intersects(region, visibleOnly));
return ret;
}
return false;
@@ -370,11 +366,15 @@ Result Paint::bounds(Point* pt4) noexcept
return Result::InsufficientCondition;
}
-
bool Paint::intersects(int32_t x, int32_t y, int32_t w, int32_t h) noexcept
+{
+ return intersects(x, y, w, h, false);
+}
+
+bool Paint::intersects(int32_t x, int32_t y, int32_t w, int32_t h, bool visibleOnly) noexcept
{
if (w <= 0 || h <= 0) return false;
- return pImpl->intersects({{x, y}, {x + w, y + h}});
+ return pImpl->intersects({x, y, x + w, y + h}, visibleOnly);
}
diff --git a/thirdparty/thorvg/src/renderer/tvgPaint.h b/thirdparty/thorvg/src/renderer/tvgPaint.h
index dac3904717d..e9613858430 100644
--- a/thirdparty/thorvg/src/renderer/tvgPaint.h
+++ b/thirdparty/thorvg/src/renderer/tvgPaint.h
@@ -27,20 +27,12 @@
#include "tvgRender.h"
#include "tvgMath.h"
-
#define PAINT(A) ((Paint::Impl*)A->pImpl)
namespace tvg
{
enum ContextFlag : uint8_t {Default = 0, FastTrack = 1};
-
-struct Iterator
-{
- virtual ~Iterator() {}
- virtual const Paint* next() = 0;
- virtual uint32_t count() = 0;
- virtual void begin() = 0;
-};
+struct AccessorIterator;
struct Mask
{
@@ -113,9 +105,16 @@ struct Paint::Impl
return ++refCnt;
}
+ void attachTo(Paint* parent)
+ {
+ this->parent = parent;
+ if (clipper) PAINT(clipper)->attachTo(parent);
+ if (maskData) PAINT(maskData->target)->attachTo(parent);
+ }
+
uint16_t unref(bool free = true)
{
- parent = nullptr;
+ attachTo(nullptr);
return unrefx(free);
}
@@ -195,7 +194,7 @@ struct Paint::Impl
clipper = clp;
if (clp) {
clp->ref();
- PAINT(clp)->parent = parent;
+ PAINT(clp)->attachTo(parent);
}
return Result::Success;
}
@@ -215,7 +214,7 @@ struct Paint::Impl
maskData = tvg::malloc<Mask>(sizeof(Mask));
target->ref();
maskData->target = target;
- PAINT(target)->parent = parent;
+ PAINT(target)->attachTo(parent);
maskData->source = paint;
maskData->method = method;
return Result::Success;
@@ -306,10 +305,10 @@ struct Paint::Impl
return Result::Success;
}
- bool intersects(const RenderRegion& region);
+ bool intersects(const RenderRegion& region, bool visibleOnly);
RenderRegion bounds();
bool bounds(Point* pt4, const Matrix* pm, bool obb);
- Iterator* iterator();
+ AccessorIterator* iterator();
RenderData update(RenderMethod* renderer, const Matrix& pm, Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag pFlag, bool clipper = false);
bool render(RenderMethod* renderer, CompositionFlag flag = CompositionFlag::Invalid);
Paint* duplicate(Paint* ret = nullptr);
@@ -317,4 +316,4 @@ struct Paint::Impl
}
-#endif //_TVG_PAINT_H_
+#endif //_TVG_PAINT_H_
diff --git a/thirdparty/thorvg/src/renderer/tvgPicture.cpp b/thirdparty/thorvg/src/renderer/tvgPicture.cpp
index 0d8418dbe92..dc1976aff0e 100644
--- a/thirdparty/thorvg/src/renderer/tvgPicture.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgPicture.cpp
@@ -40,25 +40,20 @@ Type Picture::type() const noexcept
Result Picture::load(const char* filename) noexcept
{
-#ifdef THORVG_FILE_IO_SUPPORT
if (!filename) return Result::InvalidArguments;
return to<PictureImpl>(this)->load(filename);
-#else
- TVGLOG("RENDERER", "FILE IO is disabled!");
- return Result::NonSupport;
-#endif
}
Result Picture::load(const char* data, uint32_t size, const char* mimeType, const char* rpath, bool copy) noexcept
{
- return to<PictureImpl>(this)->load(data, size, mimeType, rpath, copy);
+ return to<PictureImpl>(this)->load(data, size, mimeType, rpath, copy ? Ownership::Copy : Ownership::Borrow);
}
Result Picture::load(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, bool copy) noexcept
{
- return to<PictureImpl>(this)->load(data, w, h, cs, copy);
+ return to<PictureImpl>(this)->load(data, w, h, cs, copy ? Ownership::Copy : Ownership::Borrow);
}
@@ -99,6 +94,12 @@ Result Picture::origin(float* x, float* y) const noexcept
const Paint* Picture::paint(uint32_t id) noexcept
{
+ if (accessible) {
+ auto entity = to<PictureImpl>(this)->access(id);
+ return entity ? entity->paint : nullptr;
+ }
+
+ // TODO: remove at thorvg v2 release (for backward compat)
struct Value
{
uint32_t id;
diff --git a/thirdparty/thorvg/src/renderer/tvgPicture.h b/thirdparty/thorvg/src/renderer/tvgPicture.h
index 44ac81b3353..b9605b0de37 100644
--- a/thirdparty/thorvg/src/renderer/tvgPicture.h
+++ b/thirdparty/thorvg/src/renderer/tvgPicture.h
@@ -25,38 +25,12 @@
#include "tvgPaint.h"
#include "tvgScene.h"
-#include "tvgLoader.h"
+#include "tvgAccessor.h"
+#include "tvgLoaderMgr.h"
namespace tvg
{
-struct PictureIterator : Iterator
-{
- Paint* paint = nullptr;
- Paint* ptr = nullptr;
-
- PictureIterator(Paint* p) : paint(p) {}
-
- const Paint* next() override
- {
- if (!ptr) ptr = paint;
- else ptr = nullptr;
- return ptr;
- }
-
- uint32_t count() override
- {
- if (paint) return 1;
- else return 0;
- }
-
- void begin() override
- {
- ptr = nullptr;
- }
-};
-
-
struct PictureImpl : Picture
{
Paint::Impl impl;
@@ -82,17 +56,22 @@ struct PictureImpl : Picture
bool skip(RenderUpdateFlag flag)
{
- if (flag == RenderUpdateFlag::None) return true;
- return false;
+ // The media have its own playback update
+ return !loader || (flag == RenderUpdateFlag::None && loader->type != FileType::Media);
}
bool update(RenderMethod* renderer, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flag, TVG_UNUSED bool clipper)
{
- load();
+ flag |= load();
+ if (flag == RenderUpdateFlag::None) return true;
auto pivot = Point{-origin.x * float(w), -origin.y * float(h)};
if (bitmap) {
+ if (bitmap->cs == ColorSpace::Unknown) {
+ TVGERR("RENDERER", "Unknown colorspace picture data");
+ return false;
+ }
//Overriding Transformation by the desired image size
auto sx = w / loader->w;
auto sy = h / loader->h;
@@ -136,12 +115,12 @@ struct PictureImpl : Picture
return Result::Success;
}
- bool intersects(const RenderRegion& region)
+ bool intersects(const RenderRegion& region, bool visibleOnly)
{
if (!impl.renderer) return false;
- load();
+ impl.mark(load());
if (impl.rd) return impl.renderer->intersectsImage(impl.rd, region);
- else if (vector) return to<SceneImpl>(vector)->intersects(region);
+ else if (vector) return PAINT(vector)->intersects(region, visibleOnly);
return false;
}
@@ -158,33 +137,29 @@ struct PictureImpl : Picture
{
if (vector || bitmap) return Result::InsufficientCondition;
- bool invalid; //Invalid Path
- auto loader = static_cast<ImageLoader*>(LoaderMgr::loader(filename, &invalid));
- if (!loader) {
- if (invalid) return Result::InvalidArguments;
- return Result::NonSupport;
- }
- return load(loader);
+ PictureOps ops = {Ownership::Transfer, resolver, nullptr, accessible};
+ auto ret = Result::InvalidArguments;
+ auto loader = LoaderMgr::loader(filename, ops, ret);
+ return loader ? load(loader) : ret;
}
- Result load(const char* data, uint32_t size, const char* mimeType, const char* rpath, bool copy)
+ Result load(const char* data, uint32_t size, const char* mimeType, const char* rpath, const Ownership owner)
{
if (!data || size <= 0) return Result::InvalidArguments;
if (vector || bitmap) return Result::InsufficientCondition;
- auto loader = static_cast<ImageLoader*>(LoaderMgr::loader(data, size, mimeType, rpath, copy));
- if (!loader) return Result::NonSupport;
- return load(loader);
+
+ PictureOps ops = {owner, resolver, rpath, accessible};
+ auto ret = Result::InvalidArguments;
+ auto loader = LoaderMgr::loader(data, size, mimeType, ops, ret);
+ return loader ? load(loader) : ret;
}
- Result load(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, bool copy)
+ Result load(const uint32_t* data, uint32_t w, uint32_t h, ColorSpace cs, Ownership owner)
{
if (!data || w <= 0 || h <= 0 || cs == ColorSpace::Unknown) return Result::InvalidArguments;
- if (vector || bitmap) return Result::InsufficientCondition;
-
- auto loader = static_cast<ImageLoader*>(LoaderMgr::loader(data, w, h, cs, copy));
- if (!loader) return Result::FailedAllocation;
-
- return load(loader);
+ if (vector) return Result::InsufficientCondition;
+ auto loader = LoaderMgr::loader(data, w, h, cs, owner);
+ return loader ? load(loader) : Result::NonSupport;
}
Result set(std::function<bool(Paint* paint, const char* src, void* data)> resolver, void* data)
@@ -206,7 +181,7 @@ struct PictureImpl : Picture
{
if (ret) TVGERR("RENDERER", "TODO: duplicate()");
- load();
+ impl.mark(load());
auto picture = Picture::gen();
auto dup = to<PictureImpl>(picture);
@@ -232,34 +207,38 @@ struct PictureImpl : Picture
return picture;
}
- Iterator* iterator()
+ AccessorIterator* iterator()
{
- load();
+ impl.mark(load());
+
+ struct PictureIterator : AccessorIterator
+ {
+ Paint* ptr = nullptr;
+
+ PictureIterator(Paint* p) : ptr(p) {}
+
+ const Paint* next() override
+ {
+ auto ret = ptr;
+ ptr = nullptr;
+ return ret;
+ }
+ };
+
return new PictureIterator(vector);
}
- uint32_t* data(uint32_t* w, uint32_t* h)
+ RenderUpdateFlag load()
{
- //Try it, If not loaded yet.
- load();
+ if (!loader) return RenderUpdateFlag::None;
- if (loader) {
- if (w) *w = static_cast<uint32_t>(loader->w);
- if (h) *h = static_cast<uint32_t>(loader->h);
+ // reload the next frame if any
+ if (vector || bitmap) {
+ // sync call must be guaranteed.
+ if (loader->sync() && bitmap) return RenderUpdateFlag::Image;
+ // load the first frame
} else {
- if (w) *w = 0;
- if (h) *h = 0;
- }
- if (bitmap) return bitmap->buf32;
- else return nullptr;
- }
-
- void load()
- {
- if (loader) {
- if (vector) {
- loader->sync();
- } else if ((vector = loader->paint())) {
+ if ((vector = loader->paint())) {
vector->ref();
PAINT(vector)->parent = this;
if (w != loader->w || h != loader->h) {
@@ -270,10 +249,13 @@ struct PictureImpl : Picture
loader->resize(vector, w, h);
resizing = false;
}
- } else if (!bitmap) {
+ } else {
bitmap = loader->bitmap();
+ if (bitmap) return RenderUpdateFlag::Image;
}
}
+ // animations updates the properties essentially. here update is not necessary.
+ return RenderUpdateFlag::None;
}
void needComposition(uint8_t opacity)
@@ -312,30 +294,52 @@ struct PictureImpl : Picture
RenderRegion bounds()
{
if (vector) return vector->pImpl->bounds();
- return impl.renderer->region(impl.rd);
+ else if (impl.renderer) return impl.renderer->region(impl.rd);
+ return {};
}
- Result load(ImageLoader* loader)
+ Result load(Loader* loader)
{
//Same resource has been loaded.
if (this->loader == loader) {
this->loader->sharing--; //make it sure the reference counting.
+ if (bitmap) impl.mark(RenderUpdateFlag::Image); // force the bitmap updated
return Result::Success;
} else if (this->loader) {
LoaderMgr::retrieve(this->loader);
}
- this->loader = loader;
- loader->set(resolver);
+ this->loader = static_cast<ImageLoader*>(loader);
if (!loader->read()) return Result::Unknown;
- this->w = loader->w;
- this->h = loader->h;
+ this->w = this->loader->w;
+ this->h = this->loader->h;
impl.mark(RenderUpdateFlag::All);
return Result::Success;
}
+
+ const AccessorEntity* access(uint32_t id)
+ {
+ if (loader) return loader->access(id);
+ return nullptr;
+ }
+
+ void access(AccessorCallback& cb)
+ {
+ if (loader) loader->access(cb);
+ }
+
+ template<class T>
+ T* fetch(FileType expect)
+ {
+ if (loader) {
+ if (loader->type == expect) return static_cast<T*>(loader);
+ TVGERR("RENDERER", "Invalid loaded data type (expected: %d, got: %d)", (int)expect, (int)loader->type);
+ }
+ return nullptr;
+ }
};
}
diff --git a/thirdparty/thorvg/src/renderer/tvgRender.cpp b/thirdparty/thorvg/src/renderer/tvgRender.cpp
index 0d4f82747b9..c934b0370c5 100644
--- a/thirdparty/thorvg/src/renderer/tvgRender.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgRender.cpp
@@ -24,7 +24,42 @@
#include "tvgRender.h"
/************************************************************************/
-/* RenderMethod Class Implementation */
+/* RenderSurface */
+/************************************************************************/
+
+RenderSurface::RenderSurface(const RenderSurface* rhs)
+{
+ data = rhs->data;
+ stride = rhs->stride;
+ w = rhs->w;
+ h = rhs->h;
+ cs = rhs->cs;
+ channelSize = rhs->channelSize;
+ premultiplied = rhs->premultiplied;
+ opaque = rhs->opaque;
+}
+
+void RenderSurface::setup(pixel_t* data, uint32_t stride, uint32_t w, uint32_t h, uint8_t channelSize, ColorSpace cs)
+{
+ if (cs == ColorSpace::XBGR8888) {
+ cs = ColorSpace::ABGR8888;
+ this->opaque = true;
+ } else if (cs == ColorSpace::XRGB8888) {
+ cs = ColorSpace::ARGB8888;
+ this->opaque = true;
+ }
+
+ this->data = data;
+ this->stride = stride;
+ this->w = w;
+ this->h = h;
+ this->channelSize = channelSize;
+ this->cs = cs;
+ this->premultiplied = (cs == ColorSpace::ABGR8888 || cs == ColorSpace::ARGB8888);
+}
+
+/************************************************************************/
+/* RenderMethod */
/************************************************************************/
uint32_t RenderMethod::ref()
@@ -55,9 +90,19 @@ bool RenderMethod::viewport(const RenderRegion& vp)
/************************************************************************/
-/* RenderPath Class Implementation */
+/* RenderPath */
/************************************************************************/
+// used as a temporary buffer
+RenderPath& RenderPath::scratch()
+{
+ static thread_local RenderPath dbuffers[3]; // tripple-buffering
+ static thread_local int idx = 0;
+ if (++idx > 2) idx = 0;
+ dbuffers[(idx)].clear();
+ return dbuffers[(int)idx];
+}
+
void RenderPath::addCircle(float cx, float cy, float rx, float ry, bool cw)
{
auto rxKappa = rx * PATH_KAPPA;
@@ -190,6 +235,8 @@ bool RenderPath::bounds(const Matrix* m, BBox& box)
{
if (cmds.empty() || cmds.first() == PathCommand::CubicTo) return false;
+ box.init();
+
auto pt = pts.begin();
auto cmd = cmds.begin();
@@ -230,177 +277,20 @@ bool RenderPath::bounds(const Matrix* m, BBox& box)
return true;
}
-
-void RenderPath::optimize(RenderPath& out, const Matrix& matrix, bool& thin) const
-{
-#if defined(THORVG_GL_RASTER_SUPPORT) || defined (THORVG_WG_RASTER_SUPPORT)
- static constexpr auto PX_TOLERANCE = 0.25f;
-
- thin = false;
- if (empty()) return;
-
- out.cmds.clear();
- out.pts.clear();
- out.cmds.reserve(cmds.count);
- out.pts.reserve(pts.count);
-
- auto cmds = this->cmds.data;
- auto cmdCnt = this->cmds.count;
- auto pts = this->pts.data;
-
- Point lastOutT{}; // The suffix "T" indicates that the point is transformed.
- Point subpathStartT{};
- Point thinLineStart{};
- Point thinLineVec{};
- auto drawableSubpathCnt = 0u;
- auto thinLineVecLen = 0.0f;
- auto thinCandidate = true;
- auto thinLineReady = false;
- auto subpathOpen = false;
- auto subpathHasSegment = false;
-
- auto finalizeSubpath = [&]() {
- if (!subpathHasSegment) return;
- ++drawableSubpathCnt;
- if (drawableSubpathCnt > 1) thinCandidate = false;
- subpathHasSegment = false;
- };
-
- //vecLen is guaranteed to be non-zero since closed points are already merged
- auto point2Line = [](const Point& point, const Point& start, const Point& vec, float vecLen, float& maxDist, float& minT, float& maxT) {
- Point offset = point - start;
- auto dist = fabsf(tvg::cross(vec, offset)) / vecLen;
- if (dist > maxDist) maxDist = dist;
- auto t = tvg::dot(offset, vec) / (vecLen * vecLen);
- if (t < minT) minT = t;
- if (t > maxT) maxT = t;
- };
-
- auto validateCubic = [&point2Line](const Point& start, const Point& ctrl1, const Point& ctrl2, const Point& end, float& maxDist, float& minT, float& maxT, float& vecLen) {
- auto vec = end - start;
- vecLen = sqrtf(vec.x * vec.x + vec.y * vec.y);
- maxDist = 0.0f;
- minT = FLT_MAX;
- maxT = FLT_MIN;
- point2Line(ctrl1, start, vec, vecLen, maxDist, minT, maxT);
- point2Line(ctrl2, start, vec, vecLen, maxDist, minT, maxT);
- };
-
- auto checkThinPoint = [&](const Point& ptT) {
- if (!thinCandidate || !thinLineReady) return;
- auto dist = fabsf(tvg::cross(thinLineVec, ptT - thinLineStart)) / thinLineVecLen;
- if (dist > PX_TOLERANCE) thinCandidate = false;
- };
-
- auto collectThinSegment = [&](const Point& startT, const Point& endT) {
- subpathHasSegment = true;
- if (!thinCandidate) return;
-
- if (!thinLineReady) {
- if (!tvg::closed(startT, endT, PX_TOLERANCE)) {
- thinLineStart = startT;
- thinLineVec = endT - startT;
- thinLineVecLen = sqrtf(thinLineVec.x * thinLineVec.x + thinLineVec.y * thinLineVec.y);
- if (!tvg::zero(thinLineVecLen)) thinLineReady = true;
- }
- } else {
- checkThinPoint(startT);
- checkThinPoint(endT);
- }
- };
-
- auto addLineCmd = [&](const Point& startT, const Point& ptT) {
- out.cmds.push(PathCommand::LineTo);
- out.pts.push(ptT);
- lastOutT = ptT;
- collectThinSegment(startT, ptT);
- };
-
- auto processCubicTo = [&](const Point* cubicPts, const Point& startT) {
- auto ctrl1T = cubicPts[0] * matrix;
- auto ctrl2T = cubicPts[1] * matrix;
- auto endT = cubicPts[2] * matrix;
- if (tvg::closed(startT, endT, PX_TOLERANCE)) return;
- float maxDist, minT, maxT, vecLen;
- validateCubic(startT, ctrl1T, ctrl2T, endT, maxDist, minT, maxT, vecLen);
- auto flat = (maxDist <= PX_TOLERANCE);
- auto tEps = PX_TOLERANCE / vecLen;
- auto inSpan = (minT >= -tEps) && (maxT <= 1.0f + tEps);
- if (flat && inSpan) {
- addLineCmd(startT, endT);
- } else {
- out.cmds.push(PathCommand::CubicTo);
- out.pts.push(ctrl1T);
- out.pts.push(ctrl2T);
- out.pts.push(endT);
- lastOutT = endT;
- subpathHasSegment = true;
- thinCandidate = false;
- }
- };
-
- for (uint32_t i = 0; i < cmdCnt; i++) {
- switch (cmds[i]) {
- case PathCommand::MoveTo: {
- finalizeSubpath();
- auto ptT = (*pts) * matrix;
- out.cmds.push(PathCommand::MoveTo);
- out.pts.push(ptT);
- lastOutT = ptT;
- subpathStartT = ptT;
- subpathOpen = true;
- pts++;
- break;
- }
- case PathCommand::LineTo: {
- auto startT = lastOutT;
- auto ptT = (*pts) * matrix;
- if (tvg::closed(startT, ptT, PX_TOLERANCE)) {
- pts++;
- break;
- }
- addLineCmd(startT, ptT);
- pts++;
- break;
- }
- case PathCommand::CubicTo: {
- processCubicTo(pts, lastOutT);
- pts += 3;
- break;
- }
- case PathCommand::Close: {
- if (subpathOpen && !tvg::closed(lastOutT, subpathStartT, PX_TOLERANCE)) collectThinSegment(lastOutT, subpathStartT);
- out.cmds.push(PathCommand::Close);
- lastOutT = subpathStartT;
- break;
- }
- default: break;
- }
- }
- finalizeSubpath();
- thin = thinCandidate && thinLineReady && (drawableSubpathCnt == 1);
-#else
- thin = false;
- TVGLOG("RENDERER", "RenderPath transformed optimization is disabled");
-#endif
-}
-
-
/************************************************************************/
-/* RenderRegion Class Implementation */
+/* RenderRegion */
/************************************************************************/
-
void RenderRegion::intersect(const RenderRegion& rhs)
{
- if (min.x < rhs.min.x) min.x = rhs.min.x;
- if (min.y < rhs.min.y) min.y = rhs.min.y;
- if (max.x > rhs.max.x) max.x = rhs.max.x;
- if (max.y > rhs.max.y) max.y = rhs.max.y;
+ if (xMin < rhs.xMin) xMin = rhs.xMin;
+ if (yMin < rhs.yMin) yMin = rhs.yMin;
+ if (xMax > rhs.xMax) xMax = rhs.xMax;
+ if (yMax > rhs.yMax) yMax = rhs.yMax;
// Not intersected: collapse to zero-area region
- if (max.x < min.x) max.x = min.x;
- if (max.y < min.y) max.y = min.y;
+ if (xMax < xMin) xMax = xMin;
+ if (yMax < yMin) yMax = yMin;
}
#ifdef THORVG_PARTIAL_RENDER_SUPPORT
@@ -421,11 +311,13 @@ void RenderDirtyRegion::init(uint32_t w, uint32_t h)
auto& partition = partitions[y * cnt + x];
partition.list[0].reserve(64);
auto& region = partition.region;
- region.min = {x * px, y * py};
- region.max = {region.min.x + px, region.min.y + py};
+ region.xMin = x * px;
+ region.yMin = y * py;
+ region.xMax = region.xMin + px;
+ region.yMax = region.yMin + py;
//leftovers
- if (x == cnt -1) region.max.x += lx;
- if (y == cnt -1) region.max.y += ly;
+ if (x == cnt - 1) region.xMax += lx;
+ if (y == cnt - 1) region.yMax += ly;
}
}
}
@@ -435,7 +327,7 @@ bool RenderDirtyRegion::add(const RenderRegion& bbox)
{
for (int idx = 0; idx < PARTITIONING; ++idx) {
auto& partition = partitions[idx];
- if (bbox.max.y <= partition.region.min.y) break;
+ if (bbox.yMax <= partition.region.yMin) break;
if (bbox.intersected(partition.region)) {
ScopedLock lock(key);
partition.list[partition.current].push(RenderRegion::intersect(bbox, partition.region));
@@ -479,18 +371,18 @@ void RenderDirtyRegion::subdivide(Array<RenderRegion>& targets, uint32_t idx, Re
uint32_t cnt = 0;
//subtract top
- if (rhs.min.y < lhs.min.y) {
- temp[cnt++] = {{rhs.min.x, rhs.min.y}, {rhs.max.x, lhs.min.y}};
- rhs.min.y = lhs.min.y;
+ if (rhs.yMin < lhs.yMin) {
+ temp[cnt++] = {rhs.xMin, rhs.yMin, rhs.xMax, lhs.yMin};
+ rhs.yMin = lhs.yMin;
}
//subtract bottom
- if (rhs.max.y > lhs.max.y) {
- temp[cnt++] = {{rhs.min.x, lhs.max.y}, {rhs.max.x, rhs.max.y}};
- rhs.max.y = lhs.max.y;
+ if (rhs.yMax > lhs.yMax) {
+ temp[cnt++] = {rhs.xMin, lhs.yMax, rhs.xMax, rhs.yMax};
+ rhs.yMax = lhs.yMax;
}
//subtract right
- if (rhs.max.x > lhs.max.x) {
- temp[cnt++] = {{lhs.max.x, rhs.min.y}, {rhs.max.x, rhs.max.y}};
+ if (rhs.xMax > lhs.xMax) {
+ temp[cnt++] = {lhs.xMax, rhs.yMin, rhs.xMax, rhs.yMax};
}
//Please reserve memory enough with targets.reserve()
@@ -509,9 +401,9 @@ void RenderDirtyRegion::subdivide(Array<RenderRegion>& targets, uint32_t idx, Re
targets.count += (cnt - 1);
//sorting by x coord again, only for the updated region
- while (dst < targets.end() && dst->min.x < rhs.max.x) ++dst;
+ while (dst < targets.end() && dst->xMin < rhs.xMax) ++dst;
stable_sort(&targets[idx], dst, [](const RenderRegion& a, const RenderRegion& b) -> bool {
- return a.min.x < b.min.x;
+ return a.xMin < b.xMin;
});
}
@@ -535,7 +427,7 @@ void RenderDirtyRegion::commit()
//sorting by x coord. guarantee the stable performance: O(NlogN)
stable_sort(targets.begin(), targets.end(), [](const RenderRegion& a, const RenderRegion& b) -> bool {
- return a.min.x < b.min.x;
+ return a.xMin < b.xMin;
});
//Optimized using sweep-line algorithm: O(NlogN)
@@ -547,7 +439,7 @@ void RenderDirtyRegion::commit()
for (uint32_t j = i + 1; j < targets.count; ++j) {
auto& rhs = targets[j];
if (rhs.invalid()) continue;
- if (lhs.max.x < rhs.min.x) break; //line sweeping
+ if (lhs.xMax < rhs.xMin) break; // line sweeping
//fully overlapped. drop lhs
if (rhs.contained(lhs)) {
@@ -560,19 +452,19 @@ void RenderDirtyRegion::commit()
continue;
}
//just merge & expand on x axis
- if (lhs.min.y == rhs.min.y && lhs.max.y == rhs.max.y) {
- if (lhs.max.x >= rhs.min.x) {
- lhs.max.x = rhs.max.x;
+ if (lhs.yMin == rhs.yMin && lhs.yMax == rhs.yMax) {
+ if (lhs.xMax >= rhs.xMin) {
+ lhs.xMax = rhs.xMax;
rhs = {};
j = i; //lhs dirty region has been damaged, try again.
continue;
}
}
//just merge & expand on y axis
- if (lhs.min.x == rhs.min.x && lhs.max.x == rhs.max.x) {
- if (lhs.min.y <= rhs.max.y && rhs.min.y <= lhs.max.y) {
- rhs.min.y = std::min(lhs.min.y, rhs.min.y);
- rhs.max.y = std::max(lhs.max.y, rhs.max.y);
+ if (lhs.xMin == rhs.xMin && lhs.xMax == rhs.xMax) {
+ if (lhs.yMin <= rhs.yMax && rhs.yMin <= lhs.yMax) {
+ rhs.yMin = std::min(lhs.yMin, rhs.yMin);
+ rhs.yMax = std::max(lhs.yMax, rhs.yMax);
merged = true;
break;
}
@@ -592,7 +484,7 @@ void RenderDirtyRegion::commit()
#endif
/************************************************************************/
-/* RenderTrimPath Class Implementation */
+/* RenderTrimPath */
/************************************************************************/
#define EPSILON 1e-4f
@@ -768,8 +660,10 @@ static void _trim(const PathCommand* inCmds, uint32_t inCmdsCnt, const Point* in
auto trimEnd = end * totalLength;
if (begin >= end) {
+ auto cnt = out.cmds.count;
_trimPath(inCmds, inCmdsCnt, inPts, inPtsCnt, trimStart, totalLength, out);
- _trimPath(inCmds, inCmdsCnt, inPts, inPtsCnt, 0.0f, trimEnd, out, connect);
+ //nothing to connect to when the first part is empty
+ _trimPath(inCmds, inCmdsCnt, inPts, inPtsCnt, 0.0f, trimEnd, out, connect && out.cmds.count > cnt);
} else {
_trimPath(inCmds, inCmdsCnt, inPts, inPtsCnt, trimStart, trimEnd, out);
}
@@ -847,215 +741,3 @@ bool RenderTrimPath::trim(const RenderPath& in, RenderPath& out) const
return out.pts.count >= 2;
}
-
-/************************************************************************/
-/* StrokeDashPath Class Implementation */
-/************************************************************************/
-
-//TODO: use this common function from sw engine
-#if defined(THORVG_GL_RASTER_SUPPORT) || defined(THORVG_WG_RASTER_SUPPORT)
-
-struct StrokeDashPath
-{
-public:
- StrokeDashPath(RenderStroke::Dash dash) : dash(dash) {}
- bool gen(const RenderPath& in, RenderPath& out, bool drawPoint, const Matrix* transform = nullptr);
-
-private:
- void lineTo(RenderPath& out, const Point& pt, bool drawPoint);
- void cubicTo(RenderPath& out, const Point& pt1, const Point& pt2, const Point& pt3, bool drawPoint);
- void point(RenderPath& out, const Point& p);
- Point map(const Point& pt) const { return applyTransform ? pt * (*transform) : pt; }
- template<typename Segment, typename LengthFn, typename SplitFn, typename DrawFn, typename PointFn>
- void segment(Segment seg, float len, RenderPath& out, bool allowDot, LengthFn lengthFn, SplitFn splitFn, DrawFn drawFn, PointFn getStartPt, const Point& endPos);
-
- RenderStroke::Dash dash;
- float curLen = 0.0f;
- int32_t curIdx = 0;
- Point curPos{};
- bool opGap = false;
- bool move = true;
- const Matrix* transform = nullptr;
- bool applyTransform = false;
-};
-
-
-template<typename Segment, typename LengthFn, typename SplitFn, typename DrawFn, typename PointFn>
-void StrokeDashPath::segment(Segment seg, float len, RenderPath& out, bool allowDot, LengthFn lengthFn, SplitFn splitFn, DrawFn drawFn, PointFn getStartPt, const Point& end)
-{
- #define MIN_CURR_LEN_THRESHOLD 0.1f
-
- if (tvg::zero(len)) {
- out.moveTo(map(curPos));
- } else if (len <= curLen) {
- curLen -= len;
- if (!opGap) {
- if (move) {
- out.moveTo(map(curPos));
- move = false;
- }
- drawFn(seg);
- }
- } else {
- Segment left, right;
- while (len - curLen > DASH_PATTERN_THRESHOLD) {
- if (curLen > 0.0f) {
- splitFn(seg, curLen, left, right);
- len -= curLen;
- if (!opGap) {
- if (move || dash.pattern[curIdx] - curLen < FLOAT_EPSILON) {
- out.moveTo(map(getStartPt(left)));
- move = false;
- }
- drawFn(left);
- }
- } else {
- if (allowDot && !opGap) point(out, getStartPt(seg));
- right = seg;
- }
-
- curIdx = (curIdx + 1) % dash.count;
- curLen = dash.pattern[curIdx];
- opGap = !opGap;
- seg = right;
- curPos = getStartPt(seg);
- move = true;
- }
- curLen -= len;
- if (!opGap) {
- if (move) {
- out.moveTo(map(getStartPt(seg)));
- move = false;
- }
- drawFn(seg);
- }
- if (curLen < MIN_CURR_LEN_THRESHOLD) {
- curIdx = (curIdx + 1) % dash.count;
- curLen = dash.pattern[curIdx];
- opGap = !opGap;
- }
- }
- curPos = end;
-}
-
-
-//allowDot: zero length segment with non-butt cap still should be rendered as a point - only the caps are visible
-bool StrokeDashPath::gen(const RenderPath& in, RenderPath& out, bool allowDot, const Matrix* transform)
-{
- this->transform = transform;
- this->applyTransform = (transform && !tvg::identity(transform));
-
- int32_t idx = 0;
- auto offset = dash.offset;
- auto gap = false;
- if (!tvg::zero(dash.offset)) {
- auto length = (dash.count % 2) ? dash.length * 2 : dash.length;
- offset = fmodf(offset, length);
- if (offset < 0) offset += length;
-
- for (uint32_t i = 0; i < dash.count * (dash.count % 2 + 1); ++i, ++idx) {
- auto curPattern = dash.pattern[i % dash.count];
- if (offset < curPattern) break;
- offset -= curPattern;
- gap = !gap;
- }
- idx = idx % dash.count;
- }
-
- auto pts = in.pts.data;
- Point start{};
-
- ARRAY_FOREACH(cmd, in.cmds) {
- switch (*cmd) {
- case PathCommand::Close: {
- lineTo(out, start, allowDot);
- break;
- }
- case PathCommand::MoveTo: {
- // reset the dash state
- curIdx = idx;
- curLen = dash.pattern[idx] - offset;
- opGap = gap;
- move = true;
- start = curPos = *pts;
- pts++;
- break;
- }
- case PathCommand::LineTo: {
- lineTo(out, *pts, allowDot);
- pts++;
- break;
- }
- case PathCommand::CubicTo: {
- cubicTo(out, pts[0], pts[1], pts[2], allowDot);
- pts += 3;
- break;
- }
- default: break;
- }
- }
- return true;
-}
-
-
-void StrokeDashPath::point(RenderPath& out, const Point& p)
-{
- if (move || dash.pattern[curIdx] < FLOAT_EPSILON) {
- out.moveTo(map(p));
- move = false;
- }
- out.lineTo(map(p));
-}
-
-
-void StrokeDashPath::lineTo(RenderPath& out, const Point& to, bool allowDot)
-{
- Line line = {curPos, to};
- auto len = length(to - curPos);
- segment<Line>(line, len, out, allowDot,
- [](const Line& l) { return length(l.pt2 - l.pt1); },
- [](const Line& l, float len, Line& left, Line& right) { l.split(len, left, right); },
- [&](const Line& l) { out.lineTo(map(l.pt2)); },
- [](const Line& l) { return l.pt1; },
- to
- );
-}
-
-
-void StrokeDashPath::cubicTo(RenderPath& out, const Point& cnt1, const Point& cnt2, const Point& end, bool allowDot)
-{
- Bezier curve = {curPos, cnt1, cnt2, end};
- auto len = curve.length();
- segment<Bezier>(curve, len, out, allowDot,
- [](const Bezier& b) { return b.length(); },
- [](const Bezier& b, float len, Bezier& left, Bezier& right) { b.split(len, left, right); },
- [&](const Bezier& b) { out.cubicTo(map(b.ctrl1), map(b.ctrl2), map(b.end)); },
- [](const Bezier& b) { return b.start; },
- end
- );
-}
-
-
-bool RenderShape::strokeDash(RenderPath& out, const Matrix* transform) const
-{
- if (!stroke || stroke->dash.count == 0 || stroke->dash.length < DASH_PATTERN_THRESHOLD) return false;
-
- out.cmds.reserve(20 * path.cmds.count);
- out.pts.reserve(20 * path.pts.count);
-
- StrokeDashPath dash(stroke->dash);
- auto allowDot = stroke->cap != StrokeCap::Butt;
-
- if (trimpath()) {
- RenderPath tpath;
- if (stroke->trim.trim(path, tpath)) return dash.gen(tpath, out, allowDot, transform);
- else return false;
- }
- return dash.gen(path, out, allowDot, transform);
-}
-#else
-bool RenderShape::strokeDash(RenderPath& out, const Matrix* transform) const
-{
- return false;
-}
-#endif
diff --git a/thirdparty/thorvg/src/renderer/tvgRender.h b/thirdparty/thorvg/src/renderer/tvgRender.h
index c1c1f582859..9f007d14fc0 100644
--- a/thirdparty/thorvg/src/renderer/tvgRender.h
+++ b/thirdparty/thorvg/src/renderer/tvgRender.h
@@ -41,7 +41,22 @@ using pixel_t = uint32_t;
#define DASH_PATTERN_THRESHOLD 0.001f
//TODO: Separate Color & Opacity for more detailed conditional check
-enum RenderUpdateFlag : uint16_t {None = 0, Path = 1, Color = 2, Gradient = 4, Stroke = 8, Transform = 16, Image = 32, GradientStroke = 64, Blend = 128, Clip = 256, All = 0xffff};
+enum RenderUpdateFlag : uint16_t
+{
+ None = 0,
+ Path = 1 << 0,
+ Color = 1 << 1,
+ Gradient = 1 << 2,
+ Stroke = 1 << 3,
+ Transform = 1 << 4,
+ Image = 1 << 5,
+ GradientStroke = 1 << 6,
+ Blend = 1 << 7,
+ Clip = 1 << 8,
+ Children = 1 << 9, // Force update propagation to child paints
+ All = 0xffff
+};
+
enum CompositionFlag : uint8_t {Invalid = 0, Opacity = 1, Blending = 2, Masking = 4, PostProcessing = 8}; //Composition Purpose
static inline void operator|=(RenderUpdateFlag& a, const RenderUpdateFlag b)
@@ -54,6 +69,11 @@ static inline RenderUpdateFlag operator|(const RenderUpdateFlag a, const RenderU
return RenderUpdateFlag(uint16_t(a) | uint16_t(b));
}
+static inline bool operator&(const EngineOption a, const EngineOption b)
+{
+ return (uint8_t(a) & uint8_t(b));
+}
+
struct RenderSurface
{
union {
@@ -67,21 +87,11 @@ struct RenderSurface
ColorSpace cs = ColorSpace::Unknown;
uint8_t channelSize = 0;
bool premultiplied = false; //Alpha-premultiplied
+ bool opaque = false; // If true, the alpha channel can be ignored.
- RenderSurface()
- {
- }
-
- RenderSurface(const RenderSurface* rhs)
- {
- data = rhs->data;
- stride = rhs->stride;
- w = rhs->w;
- h = rhs->h;
- cs = rhs->cs;
- channelSize = rhs->channelSize;
- premultiplied = rhs->premultiplied;
- }
+ RenderSurface() = default;
+ RenderSurface(const RenderSurface* rhs);
+ void setup(pixel_t* data, uint32_t stride, uint32_t w, uint32_t h, uint8_t channelSize, ColorSpace cs);
};
struct RenderCompositor
@@ -90,63 +100,63 @@ struct RenderCompositor
uint8_t opacity;
};
-struct RenderRegion
+struct RenderRegion : Region
{
- struct {
- int32_t x, y;
- } min;
-
- struct {
- int32_t x, y;
- } max;
+ RenderRegion() = default;
+ constexpr RenderRegion(int32_t xMin, int32_t yMin, int32_t xMax, int32_t yMax) : Region{xMin, yMin, xMax, yMax} {}
static constexpr RenderRegion intersect(const RenderRegion& lhs, const RenderRegion& rhs)
{
- RenderRegion ret = {{std::max(lhs.min.x, rhs.min.x), std::max(lhs.min.y, rhs.min.y)}, {std::min(lhs.max.x, rhs.max.x), std::min(lhs.max.y, rhs.max.y)}};
+ RenderRegion ret = {std::max(lhs.xMin, rhs.xMin), std::max(lhs.yMin, rhs.yMin), std::min(lhs.xMax, rhs.xMax), std::min(lhs.yMax, rhs.yMax)};
// Not intersected: collapse to zero-area region
- if (ret.min.x > ret.max.x) ret.max.x = ret.min.x;
- if (ret.min.y > ret.max.y) ret.max.y = ret.min.y;
+ if (ret.xMin > ret.xMax) ret.xMax = ret.xMin;
+ if (ret.yMin > ret.yMax) ret.yMax = ret.yMin;
return ret;
}
static constexpr RenderRegion add(const RenderRegion& lhs, const RenderRegion& rhs)
{
- return {{std::min(lhs.min.x, rhs.min.x), std::min(lhs.min.y, rhs.min.y)}, {std::max(lhs.max.x, rhs.max.x), std::max(lhs.max.y, rhs.max.y)}};
+ return {std::min(lhs.xMin, rhs.xMin), std::min(lhs.yMin, rhs.yMin), std::max(lhs.xMax, rhs.xMax), std::max(lhs.yMax, rhs.yMax)};
}
void intersect(const RenderRegion& rhs);
void add(const RenderRegion& rhs)
{
- if (rhs.min.x < min.x) min.x = rhs.min.x;
- if (rhs.min.y < min.y) min.y = rhs.min.y;
- if (rhs.max.x > max.x) max.x = rhs.max.x;
- if (rhs.max.y > max.y) max.y = rhs.max.y;
+ if (rhs.xMin < xMin) xMin = rhs.xMin;
+ if (rhs.yMin < yMin) yMin = rhs.yMin;
+ if (rhs.xMax > xMax) xMax = rhs.xMax;
+ if (rhs.yMax > yMax) yMax = rhs.yMax;
+ }
+
+ bool inside(const Point& pt) const
+ {
+ return (pt.x >= xMin && pt.x < xMax && pt.y >= yMin && pt.y < yMax);
}
bool contained(const RenderRegion& rhs) const
{
- return (min.x <= rhs.min.x && max.x >= rhs.max.x && min.y <= rhs.min.y && max.y >= rhs.max.y);
+ return (xMin <= rhs.xMin && xMax >= rhs.xMax && yMin <= rhs.yMin && yMax >= rhs.yMax);
}
bool intersected(const RenderRegion& rhs) const
{
- return (rhs.min.x < max.x && rhs.max.x > min.x && rhs.min.y < max.y && rhs.max.y > min.y);
+ return (rhs.xMin < xMax && rhs.xMax > xMin && rhs.yMin < yMax && rhs.yMax > yMin);
}
bool operator==(const RenderRegion& rhs) const
{
- return (min.x == rhs.min.x && min.y == rhs.min.y && max.x == rhs.max.x && max.y == rhs.max.y);
+ return (xMin == rhs.xMin && yMin == rhs.yMin && xMax == rhs.xMax && yMax == rhs.yMax);
}
- void reset() { min.x = min.y = max.x = max.y = 0; }
- bool valid() const { return (max.x > min.x && max.y > min.y); }
+ void reset() { xMin = yMin = xMax = yMax = 0; }
+ bool valid() const { return (xMax > xMin && yMax > yMin); }
bool invalid() const { return !valid(); }
- int32_t sx() const { return min.x; }
- int32_t sy() const { return min.y; }
- int32_t sw() const { return max.x - min.x; }
- int32_t sh() const { return max.y - min.y; }
+ int32_t sx() const { return xMin; }
+ int32_t sy() const { return yMin; }
+ int32_t sw() const { return xMax - xMin; }
+ int32_t sh() const { return yMax - yMin; }
uint32_t x() const { return (uint32_t) sx(); }
uint32_t y() const { return (uint32_t) sy(); }
@@ -174,7 +184,7 @@ struct RenderRegion
return on;
}
- bool deactivated()
+ bool deactivated() const
{
return (!support || disabled);
}
@@ -184,11 +194,20 @@ struct RenderRegion
return partitions[idx].region;
}
- const Array<RenderRegion>& get(int idx)
+ const Array<RenderRegion>& get(int idx) const
{
return partitions[idx].list[partitions[idx].current];
}
+ uint32_t count() const
+ {
+ uint32_t count = 0;
+ for (int idx = 0; idx < PARTITIONING; ++idx) {
+ count += get(idx).count;
+ }
+ return count;
+ }
+
private:
void subdivide(Array<RenderRegion>& targets, uint32_t idx, RenderRegion& lhs, RenderRegion& rhs);
@@ -214,10 +233,15 @@ struct RenderRegion
bool add(TVG_UNUSED const RenderRegion& bbox) { return true; }
bool add(TVG_UNUSED const RenderRegion& prv, TVG_UNUSED const RenderRegion& cur) { return true; }
void clear() {}
+ uint32_t count() const { return 0; }
bool deactivate(TVG_UNUSED bool on) { return true; }
- bool deactivated() { return true; }
+ bool deactivated() const { return true; }
const RenderRegion& partition(TVG_UNUSED int idx) { static RenderRegion tmp{}; return tmp; }
- const Array<RenderRegion>& get(TVG_UNUSED int idx) { static Array<RenderRegion> tmp; return tmp; }
+ const Array<RenderRegion>& get(TVG_UNUSED int idx) const
+ {
+ static Array<RenderRegion> tmp;
+ return tmp;
+ }
};
#endif
@@ -227,6 +251,13 @@ struct RenderPath
Array<PathCommand> cmds;
Array<Point> pts;
+ void dismiss()
+ {
+ // If you moved the data manually, destroy the RenderPath instance safely
+ cmds.data = nullptr;
+ pts.data = nullptr;
+ }
+
bool empty() const
{
return pts.empty();
@@ -312,12 +343,11 @@ struct RenderPath
return curr;
}
- /* Optimize path in screen space by collapsing zero length lines
- and removing unnecessary cubic beziers. */
- void optimize(RenderPath& out, const Matrix& matrix, bool& thin) const;
bool bounds(const Matrix* m, BBox& box);
void addCircle(float cx, float cy, float rx, float ry, bool cw);
void addRect(float x, float y, float w, float h, float rx, float ry, bool cw);
+
+ static RenderPath& scratch();
};
struct RenderTrimPath
@@ -458,8 +488,6 @@ struct RenderShape
{
return stroke ? stroke->miterlimit : 4.0f;
}
-
- bool strokeDash(RenderPath& out, const Matrix* transform = nullptr) const;
};
struct RenderEffect
@@ -491,6 +519,47 @@ struct RenderEffectGaussianBlur : RenderEffect
}
};
+struct RenderEffectMotionBlur : RenderEffect
+{
+ float distance;
+ float angle;
+ uint8_t quality;
+
+ // computes the transformed blur offset and quality-based sample count
+ bool update(const Matrix& transform, Point& offset, int& samples)
+ {
+ valid = false;
+
+ // transform the local blur vector, without translating it.
+ auto radian = tvg::deg2rad(angle);
+ auto vx = distance * cosf(radian);
+ auto vy = distance * sinf(radian);
+ offset = {transform.e11 * vx + transform.e12 * vy, transform.e21 * vx + transform.e22 * vy};
+
+ // avoid spurious one-pixel expansion at exact cardinal angles.
+ if (fabsf(offset.x) < 0.001f) offset.x = 0.0f;
+ if (fabsf(offset.y) < 0.001f) offset.y = 0.0f;
+ auto length = std::max(fabsf(offset.x), fabsf(offset.y));
+ if (tvg::zero(length)) return false;
+
+ // confirm the samples count; Uniform midpoint samples, including the original position.
+ auto density = 0.25f + quality * 0.0075f;
+ samples = 2 * int(std::min(128.0f, ceilf(length * density * 0.5f))) + 1;
+ valid = true;
+ return true;
+ }
+
+ static RenderEffectMotionBlur* gen(va_list& args)
+ {
+ auto inst = new RenderEffectMotionBlur;
+ inst->distance = std::max(0.0f, float(va_arg(args, double)));
+ inst->angle = fmod((float)va_arg(args, double), 180.0f);
+ inst->quality = std::min(va_arg(args, int), 100);
+ inst->type = SceneEffect::MotionBlur;
+ return inst;
+ }
+};
+
struct RenderEffectDropShadow : RenderEffect
{
uint8_t color[4]; //rgba
@@ -499,6 +568,19 @@ struct RenderEffectDropShadow : RenderEffect
float sigma;
uint8_t quality; //0 ~ 100 (optional)
+ bool update(const Matrix& transform, Point& offset)
+ {
+ valid = (color[3] != 0);
+ if (!valid) return false;
+
+ // Transform the offset as a direction, without translation.
+ const auto radian = tvg::deg2rad(90.0f - angle);
+ const auto x = distance * cosf(radian);
+ const auto y = -distance * sinf(radian);
+ offset = {transform.e11 * x + transform.e12 * y, transform.e21 * x + transform.e22 * y};
+ return true;
+ }
+
static RenderEffectDropShadow* gen(va_list& args)
{
auto inst = new RenderEffectDropShadow;
@@ -596,8 +678,8 @@ public:
//main features
virtual ~RenderMethod() {}
virtual bool preUpdate() = 0;
- virtual RenderData prepare(const RenderShape& rshape, RenderData data, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flags, bool clipper) = 0;
- virtual RenderData prepare(RenderSurface* surface, RenderData data, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, FilterMethod filter, RenderUpdateFlag flags) = 0;
+ virtual RenderData prepare(const RenderShape& rshape, RenderData data, const Matrix& transform, const Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flags, bool clipper) = 0;
+ virtual RenderData prepare(RenderSurface* surface, RenderData data, const Matrix& transform, const Array<RenderData>& clips, uint8_t opacity, FilterMethod filter, RenderUpdateFlag flags) = 0;
virtual bool postUpdate() = 0;
virtual bool preRender() = 0;
virtual bool renderShape(RenderData data) = 0;
@@ -628,6 +710,8 @@ public:
//partial rendering
virtual void damage(RenderData rd, const RenderRegion& region) = 0;
virtual bool partial(bool disable) = 0;
+ virtual uint32_t dirtyRegions() const = 0;
+ virtual Result dirtyRegions(Region* regions, uint32_t cnt) const = 0;
};
static inline bool MASK_REGION_MERGING(MaskMethod method)
@@ -655,6 +739,8 @@ static inline bool MASK_REGION_MERGING(MaskMethod method)
static inline uint8_t CHANNEL_SIZE(ColorSpace cs)
{
switch(cs) {
+ case ColorSpace::XBGR8888:
+ case ColorSpace::XRGB8888:
case ColorSpace::ABGR8888:
case ColorSpace::ABGR8888S:
case ColorSpace::ARGB8888:
diff --git a/thirdparty/thorvg/src/renderer/tvgSaveModule.h b/thirdparty/thorvg/src/renderer/tvgSaveModule.h
index 69be4326c4c..126cabf8198 100644
--- a/thirdparty/thorvg/src/renderer/tvgSaveModule.h
+++ b/thirdparty/thorvg/src/renderer/tvgSaveModule.h
@@ -23,16 +23,14 @@
#ifndef _TVG_SAVE_MODULE_H_
#define _TVG_SAVE_MODULE_H_
-#include "tvgIteratorAccessor.h"
+#include "tvgCommon.h"
namespace tvg
{
-class SaveModule
+struct SaveModule
{
-public:
virtual ~SaveModule() {}
-
virtual bool save(Paint* paint, Paint* bg, const char* filename, uint32_t quality) = 0;
virtual bool save(Animation* animation, Paint* bg, const char* filename, uint32_t quality, uint32_t fps) = 0;
virtual bool close() = 0;
diff --git a/thirdparty/thorvg/src/renderer/tvgSaver.cpp b/thirdparty/thorvg/src/renderer/tvgSaver.cpp
index c930edc7ceb..242034dfc69 100644
--- a/thirdparty/thorvg/src/renderer/tvgSaver.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgSaver.cpp
@@ -23,6 +23,7 @@
#include <cstring>
#include "tvgCommon.h"
#include "tvgStr.h"
+#include "tvgMath.h"
#include "tvgSaveModule.h"
#ifdef THORVG_GIF_SAVER_SUPPORT
@@ -33,19 +34,22 @@
/* Internal Class Implementation */
/************************************************************************/
-struct Saver::Impl
+#define IMPL static_cast<SaverImpl*>(this)
+
+Saver::Saver() = default;
+
+struct SaverImpl : Saver
{
SaveModule* saveModule = nullptr;
Paint* bg = nullptr;
- ~Impl()
+ ~SaverImpl()
{
delete(saveModule);
if (bg) bg->unref();
}
};
-
static SaveModule* _find(FileType type)
{
switch(type) {
@@ -77,7 +81,6 @@ static SaveModule* _find(FileType type)
return nullptr;
}
-
static SaveModule* _find(const char* filename)
{
auto ext = fileext(filename);
@@ -85,35 +88,23 @@ static SaveModule* _find(const char* filename)
return nullptr;
}
-
/************************************************************************/
/* External Class Implementation */
/************************************************************************/
-Saver::Saver() : pImpl(new Impl())
-{
-}
-
-
-Saver::~Saver()
-{
- delete(pImpl);
-}
-
-
Result Saver::save(Paint* paint, const char* filename, uint32_t quality) noexcept
{
if (!paint) return Result::InvalidArguments;
//Already on saving another resource.
- if (pImpl->saveModule) {
+ if (IMPL->saveModule) {
Paint::rel(paint);
return Result::InsufficientCondition;
}
if (auto saveModule = _find(filename)) {
- if (saveModule->save(paint, pImpl->bg, filename, quality)) {
- pImpl->saveModule = saveModule;
+ if (saveModule->save(paint, IMPL->bg, filename, quality)) {
+ IMPL->saveModule = saveModule;
return Result::Success;
} else {
Paint::rel(paint);
@@ -125,19 +116,17 @@ Result Saver::save(Paint* paint, const char* filename, uint32_t quality) noexcep
return Result::NonSupport;
}
-
Result Saver::background(Paint* paint) noexcept
{
if (!paint) return Result::InvalidArguments;
- if (pImpl->bg) pImpl->bg->unref();
+ if (IMPL->bg) IMPL->bg->unref();
paint->ref();
- pImpl->bg = paint;
+ IMPL->bg = paint;
return Result::Success;
}
-
Result Saver::save(Animation* animation, const char* filename, uint32_t quality, uint32_t fps) noexcept
{
if (!animation) return Result::InvalidArguments;
@@ -151,14 +140,14 @@ Result Saver::save(Animation* animation, const char* filename, uint32_t quality,
}
//Already on saving another resource.
- if (pImpl->saveModule) {
+ if (IMPL->saveModule) {
if (remove) delete(animation);
return Result::InsufficientCondition;
}
if (auto saveModule = _find(filename)) {
- if (saveModule->save(animation, pImpl->bg, filename, quality, fps)) {
- pImpl->saveModule = saveModule;
+ if (saveModule->save(animation, IMPL->bg, filename, quality, fps)) {
+ IMPL->saveModule = saveModule;
return Result::Success;
} else {
if (remove) delete(animation);
@@ -170,19 +159,17 @@ Result Saver::save(Animation* animation, const char* filename, uint32_t quality,
return Result::NonSupport;
}
-
Result Saver::sync() noexcept
{
- if (!pImpl->saveModule) return Result::InsufficientCondition;
- pImpl->saveModule->close();
- delete(pImpl->saveModule);
- pImpl->saveModule = nullptr;
+ if (!IMPL->saveModule) return Result::InsufficientCondition;
+ IMPL->saveModule->close();
+ delete(IMPL->saveModule);
+ IMPL->saveModule = nullptr;
return Result::Success;
}
-
Saver* Saver::gen() noexcept
{
- return new Saver;
+ return new SaverImpl;
}
diff --git a/thirdparty/thorvg/src/renderer/tvgScene.h b/thirdparty/thorvg/src/renderer/tvgScene.h
index 1c9ba37d60a..ed3c389caf5 100644
--- a/thirdparty/thorvg/src/renderer/tvgScene.h
+++ b/thirdparty/thorvg/src/renderer/tvgScene.h
@@ -26,36 +26,7 @@
#include <algorithm>
#include "tvgMath.h"
#include "tvgPaint.h"
-
-
-struct SceneIterator : Iterator
-{
- list<Paint*>* paints;
- list<Paint*>::iterator itr;
-
- SceneIterator(list<Paint*>* p) : paints(p)
- {
- begin();
- }
-
- const Paint* next() override
- {
- if (itr == paints->end()) return nullptr;
- auto paint = *itr;
- ++itr;
- return paint;
- }
-
- uint32_t count() override
- {
- return paints->size();
- }
-
- void begin() override
- {
- itr = paints->begin();
- }
-};
+#include "tvgAccessor.h"
struct SceneImpl : Scene
{
@@ -144,7 +115,7 @@ struct SceneImpl : Scene
if (fixed) {
auto pt = fsize * transform;
- vport.intersect({{int32_t(round(transform.e13)), int32_t(round(transform.e23))}, {int32_t(round(pt.x)), int32_t(round(pt.y))}});
+ vport.intersect({int32_t(round(transform.e13)), int32_t(round(transform.e23)), int32_t(round(pt.x)), int32_t(round(pt.y))});
} else {
vdirty = true;
}
@@ -198,29 +169,28 @@ struct SceneImpl : Scene
vdirty = false;
//Merge regions
- RenderRegion pRegion = {{INT32_MAX, INT32_MAX}, {0, 0}};
+ RenderRegion pRegion = {INT32_MAX, INT32_MAX, 0, 0};
for (auto paint : paints) {
auto region = paint->pImpl->bounds();
- if (region.min.x < pRegion.min.x) pRegion.min.x = region.min.x;
- if (pRegion.max.x < region.max.x) pRegion.max.x = region.max.x;
- if (region.min.y < pRegion.min.y) pRegion.min.y = region.min.y;
- if (pRegion.max.y < region.max.y) pRegion.max.y = region.max.y;
+ if (region.xMin < pRegion.xMin) pRegion.xMin = region.xMin;
+ if (pRegion.xMax < region.xMax) pRegion.xMax = region.xMax;
+ if (region.yMin < pRegion.yMin) pRegion.yMin = region.yMin;
+ if (pRegion.yMax < region.yMax) pRegion.yMax = region.yMax;
}
//Extends the render region if post effects require
- RenderRegion eRegion{};
if (effects) {
ARRAY_FOREACH(p, *effects) {
auto effect = *p;
- if (effect->valid && impl.renderer->region(effect)) eRegion.add(effect->extend);
+ if (!effect->valid || !impl.renderer->region(effect)) continue;
+ // Each effect expands the output of the preceding effects.
+ pRegion.xMin += effect->extend.xMin;
+ pRegion.yMin += effect->extend.yMin;
+ pRegion.xMax += effect->extend.xMax;
+ pRegion.yMax += effect->extend.yMax;
}
}
- pRegion.min.x += eRegion.min.x;
- pRegion.min.y += eRegion.min.y;
- pRegion.max.x += eRegion.max.x;
- pRegion.max.y += eRegion.max.y;
-
vport = RenderRegion::intersect(vport, pRegion);
return vport;
}
@@ -260,14 +230,13 @@ struct SceneImpl : Scene
return ret;
}
-
- bool intersects(const RenderRegion& region)
+ bool intersects(const RenderRegion& region, bool visibleOnly)
{
if (!impl.renderer) return false;
if (this->bounds().intersected(region)) {
for (auto paint : paints) {
- if (PAINT(paint)->intersects(region)) return true;
+ if (PAINT(paint)->intersects(region, visibleOnly)) return true;
}
}
@@ -297,6 +266,10 @@ struct SceneImpl : Scene
ret = new RenderEffectGaussianBlur(*(RenderEffectGaussianBlur*)(*p));
break;
}
+ case SceneEffect::MotionBlur: {
+ ret = new RenderEffectMotionBlur(*(RenderEffectMotionBlur*)(*p));
+ break;
+ }
case SceneEffect::DropShadow: {
ret = new RenderEffectDropShadow(*(RenderEffectDropShadow*)(*p));
break;
@@ -383,14 +356,31 @@ struct SceneImpl : Scene
if (itr == paints.end()) return Result::InvalidArguments;
paints.insert(itr, target);
}
- timpl->parent = this;
- if (timpl->clipper) PAINT(timpl->clipper)->parent = this;
- if (timpl->maskData) PAINT(timpl->maskData->target)->parent = this;
+ timpl->attachTo(this);
return Result::Success;
}
- Iterator* iterator()
+ AccessorIterator* iterator()
{
+ struct SceneIterator : AccessorIterator
+ {
+ list<Paint*>* paints;
+ list<Paint*>::iterator itr;
+
+ SceneIterator(list<Paint*>* p) : paints(p)
+ {
+ itr = paints->begin();
+ }
+
+ const Paint* next() override
+ {
+ if (itr == paints->end()) return nullptr;
+ auto paint = *itr;
+ ++itr;
+ return paint;
+ }
+ };
+
return new SceneIterator(&paints);
}
@@ -437,6 +427,10 @@ struct SceneImpl : Scene
re = RenderEffectTritone::gen(args);
break;
}
+ case SceneEffect::MotionBlur: {
+ re = RenderEffectMotionBlur::gen(args);
+ break;
+ }
default: break;
}
diff --git a/thirdparty/thorvg/src/renderer/tvgShape.h b/thirdparty/thorvg/src/renderer/tvgShape.h
index be3009e16e7..d82ff89abd9 100644
--- a/thirdparty/thorvg/src/renderer/tvgShape.h
+++ b/thirdparty/thorvg/src/renderer/tvgShape.h
@@ -96,8 +96,7 @@ struct ShapeImpl : Shape
bool skip(RenderUpdateFlag flag)
{
- if (flag == RenderUpdateFlag::None) return true;
- return false;
+ return (flag == RenderUpdateFlag::None);
}
bool update(RenderMethod* renderer, const Matrix& transform, Array<RenderData>& clips, uint8_t opacity, RenderUpdateFlag flag, bool clipper)
@@ -129,7 +128,7 @@ struct ShapeImpl : Shape
}
//Keep this for legacy. loaders still depend on this logic, remove it if possible.
if (fallback) {
- BBox box = {{FLT_MAX, FLT_MAX}, {-FLT_MAX, -FLT_MAX}};
+ BBox box;
if (!rs.path.bounds(obb ? nullptr : &m, box)) return false;
if (rs.stroke) {
//Use geometric mean for feathering.
@@ -241,7 +240,7 @@ struct ShapeImpl : Shape
return Result::Success;
}
- bool intersects(const RenderRegion& region)
+ bool intersects(const RenderRegion& region, TVG_UNUSED bool visibleOnly)
{
if (!impl.rd || !impl.renderer) return false;
return impl.renderer->intersectsShape(impl.rd, region);
@@ -285,9 +284,9 @@ struct ShapeImpl : Shape
tvg::free(dash.pattern);
dash.pattern = nullptr;
}
+ dash.length = 0.0f;
if (cnt > 0) {
if (!dash.pattern) dash.pattern = tvg::malloc<float>(sizeof(float) * cnt);
- dash.length = 0.0f;
for (uint32_t i = 0; i < cnt; ++i) {
dash.pattern[i] = pattern[i] < 0.0f ? 0.0f : pattern[i];
dash.length += dash.pattern[i];
@@ -415,7 +414,7 @@ struct ShapeImpl : Shape
rs.fill = nullptr;
}
- Iterator* iterator()
+ AccessorIterator* iterator()
{
return nullptr;
}
diff --git a/thirdparty/thorvg/src/renderer/tvgText.cpp b/thirdparty/thorvg/src/renderer/tvgText.cpp
index f1007a0fae3..1ab22951c86 100644
--- a/thirdparty/thorvg/src/renderer/tvgText.cpp
+++ b/thirdparty/thorvg/src/renderer/tvgText.cpp
@@ -23,7 +23,6 @@
#include "tvgText.h"
-
Text::Text() = default;
@@ -47,47 +46,23 @@ Result Text::size(float size) noexcept
Result Text::load(const char* filename) noexcept
{
-#ifdef THORVG_FILE_IO_SUPPORT
- bool invalid; //invalid path
- auto loader = LoaderMgr::loader(filename, &invalid);
- if (loader) {
- if (loader->sharing > 0) --loader->sharing; //font loading doesn't mean sharing.
- return Result::Success;
- } else {
- if (invalid) return Result::InvalidArguments;
- else return Result::NonSupport;
- }
-#else
- TVGLOG("RENDERER", "FILE IO is disabled!");
- return Result::NonSupport;
-#endif
+ LoaderOps ops = {Type::Text, Ownership::Transfer};
+ auto ret = Result::InvalidArguments;
+ return LoaderMgr::loader(filename, ops, ret) ? Result::Success: ret;
}
Result Text::load(const char* name, const char* data, uint32_t size, const char* mimeType, bool copy) noexcept
{
- if (!name || (size == 0 && data)) return Result::InvalidArguments;
-
- //unload font
- if (!data) {
- if (LoaderMgr::retrieve(LoaderMgr::font(name))) return Result::Success;
- return Result::InsufficientCondition;
- }
-
- if (!LoaderMgr::loader(name, data, size, mimeType, copy)) return Result::NonSupport;
- return Result::Success;
+ return TextImpl::load(name, data, size, mimeType, copy ? Ownership::Copy : Ownership::Borrow);
}
Result Text::unload(const char* filename) noexcept
{
-#ifdef THORVG_FILE_IO_SUPPORT
+ if (!filename) return Result::InvalidArguments;
if (LoaderMgr::retrieve(filename)) return Result::Success;
return Result::InsufficientCondition;
-#else
- TVGLOG("RENDERER", "FILE IO is disabled!");
- return Result::NonSupport;
-#endif
}
@@ -161,10 +136,9 @@ Result Text::metrics(TextMetrics& metrics) const noexcept
return to<TextImpl>(this)->metrics(metrics);
}
-
-Result Text::metrics(const char* ch, GlyphMetrics& metrics) const noexcept
+Result Text::metrics(const char* ch, GlyphMetrics& metrics, const char** next) const noexcept
{
- return to<TextImpl>(this)->metrics(ch, metrics);
+ return to<TextImpl>(this)->metrics(ch, metrics, next);
}
diff --git a/thirdparty/thorvg/src/renderer/tvgText.h b/thirdparty/thorvg/src/renderer/tvgText.h
index ea1ab3abbad..54b985f6ff8 100644
--- a/thirdparty/thorvg/src/renderer/tvgText.h
+++ b/thirdparty/thorvg/src/renderer/tvgText.h
@@ -27,7 +27,7 @@
#include "tvgMath.h"
#include "tvgShape.h"
#include "tvgFill.h"
-#include "tvgLoader.h"
+#include "tvgLoaderMgr.h"
namespace tvg
{
@@ -133,17 +133,16 @@ struct TextImpl : Text
return Result::Success;
}
- Result metrics(const char* ch, GlyphMetrics& metrics)
+ Result metrics(const char* ch, GlyphMetrics& metrics, const char** next)
{
if (!loader || fm.fontSize <= 0.0f) return Result::InsufficientCondition;
- if (ch && loader->metrics(fm, ch, metrics)) return Result::Success;
+ if (ch && loader->metrics(fm, ch, metrics, next)) return Result::Success;
return Result::InvalidArguments;
}
bool skip(RenderUpdateFlag flag)
{
- if (flag == RenderUpdateFlag::None) return true;
- return false;
+ return (flag == RenderUpdateFlag::None);
}
void wrapping(TextWrap mode)
@@ -188,11 +187,13 @@ struct TextImpl : Text
if (fill->type() == Type::LinearGradient) {
LINEAR(fill)->p1 *= scale;
LINEAR(fill)->p2 *= scale;
- } else {
+ } else if (fill->type() == Type::RadialGradient) {
RADIAL(fill)->center *= scale;
RADIAL(fill)->r *= scale;
RADIAL(fill)->focal *= scale;
RADIAL(fill)->fr *= scale;
+ } else if (fill->type() == Type::ConicGradient) {
+ CONIC(fill)->center *= scale;
}
}
@@ -202,10 +203,10 @@ struct TextImpl : Text
return true;
}
- bool intersects(const RenderRegion& region)
+ bool intersects(const RenderRegion& region, TVG_UNUSED bool visibleOnly)
{
if (!load()) return false;
- return to<ShapeImpl>(shape)->intersects(region);
+ return to<ShapeImpl>(shape)->intersects(region, false);
}
bool bounds(Point* pt4, const Matrix& m, bool obb)
@@ -240,10 +241,25 @@ struct TextImpl : Text
return text;
}
- Iterator* iterator()
+ AccessorIterator* iterator()
{
return nullptr;
}
+
+ static Result load(const char* name, const char* data, uint32_t size, const char* mimeType, Ownership owner) noexcept
+ {
+ if (!name || (size == 0 && data)) return Result::InvalidArguments;
+
+ // unload font
+ if (!data) {
+ if (LoaderMgr::retrieve(LoaderMgr::font(name))) return Result::Success;
+ return Result::InsufficientCondition;
+ }
+
+ LoaderOps ops = {Type::Text, owner};
+ if (!LoaderMgr::loader(name, data, size, mimeType, ops)) return Result::NonSupport;
+ return Result::Success;
+ }
};
}
diff --git a/thirdparty/thorvg/update-thorvg.sh b/thirdparty/thorvg/update-thorvg.sh
index d32ddb1e7da..777e7a21726 100755
--- a/thirdparty/thorvg/update-thorvg.sh
+++ b/thirdparty/thorvg/update-thorvg.sh
@@ -1,6 +1,6 @@
#!/bin/bash -e
-VERSION=1.0.3
+VERSION=1.1.3
# Uncomment and set a git hash to use specific commit instead of tag.
#GIT_COMMIT=
@@ -40,7 +40,7 @@ cat << EOF > ../inc/config.h
#ifndef THORVG_CONFIG_H
#define THORVG_CONFIG_H
-#define THORVG_SW_RASTER_SUPPORT
+#define THORVG_CPU_ENGINE_SUPPORT
#define THORVG_SVG_LOADER_SUPPORT
#define THORVG_PNG_LOADER_SUPPORT
#ifndef WEB_ENABLED
@@ -62,9 +62,8 @@ mkdir ../src
cp -rv src/common ../src
cp -rv src/renderer ../src/
-# Only sw_engine is enabled.
-rm -rfv ../src/renderer/gl_engine
-rm -rfv ../src/renderer/wg_engine
+# Only cpu_engine is enabled.
+rm -rfv ../src/renderer/gpu_engine
# Enabled embedded loaders: raw, JPEG, PNG, WebP.
mkdir ../src/loaders