diff --git a/source/MRIOExtras/CMakeLists.txt b/source/MRIOExtras/CMakeLists.txt index f5cc823523bc..7b94c0977224 100644 --- a/source/MRIOExtras/CMakeLists.txt +++ b/source/MRIOExtras/CMakeLists.txt @@ -34,7 +34,12 @@ target_link_libraries(${PROJECT_NAME} ) IF(NOT MRIOEXTRAS_NO_XML) - target_link_libraries(${PROJECT_NAME} PRIVATE tinyxml2) + # FreeType rasterizes SVG + IF(EMSCRIPTEN) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -s USE_FREETYPE=1") + ENDIF() + find_package(Freetype REQUIRED) + target_link_libraries(${PROJECT_NAME} PRIVATE tinyxml2 Freetype::Freetype) ENDIF() IF(NOT MRIOEXTRAS_NO_CTM) diff --git a/source/MRIOExtras/MRIOExtrasConfig.cmake b/source/MRIOExtras/MRIOExtrasConfig.cmake index 6288fa1ba3d0..51ebef4a6038 100644 --- a/source/MRIOExtras/MRIOExtrasConfig.cmake +++ b/source/MRIOExtras/MRIOExtrasConfig.cmake @@ -5,6 +5,7 @@ if(EMSCRIPTEN) find_dependency(OpenCTM) find_dependency(draco) find_dependency(LAZPERF) + find_dependency(Freetype) endif() include("${CMAKE_CURRENT_LIST_DIR}/MRIOExtrasTargets.cmake") diff --git a/source/MRIOExtras/MRSvg.cpp b/source/MRIOExtras/MRSvg.cpp index a5aa39b084c3..ddf6b6edcea0 100644 --- a/source/MRIOExtras/MRSvg.cpp +++ b/source/MRIOExtras/MRSvg.cpp @@ -2,17 +2,32 @@ #ifndef MRIOEXTRAS_NO_XML #include "MRMesh/MRBezier.h" +#include "MRMesh/MRBox.h" +#include "MRMesh/MRContour.h" +#include "MRMesh/MRFinally.h" #include "MRMesh/MRIOFormatsRegistry.h" #include "MRMesh/MRIOParsing.h" #include "MRMesh/MRMatrix2.h" +#include "MRMesh/MRphmap.h" +#include "MRMesh/MRString.h" #include "MRMesh/MRStringConvert.h" +#include "MRMesh/MRVector4.h" #include #include +#include +#include FT_FREETYPE_H +#include FT_OUTLINE_H +#include FT_STROKER_H + #include +#include +#include +#include #include +#include #include @@ -165,7 +180,10 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) // https://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii auto r = cmd.radii; - if ( r == Vector2f{} ) + // an arc with identical endpoints is omitted, and an arc with a zero radius is a straight line + if ( p1 == p2 ) + return {}; + if ( r.x == 0.f || r.y == 0.f ) return { p2 }; if ( r.x < 0.f ) r.x *= -1.f; @@ -178,8 +196,8 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) // https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter const auto rp_ = Vector2f { r.x * p0_.y, r.y * p0_.x }; assert( rp_.lengthSq() != 0.f ); - const auto k1Sq = sqr( r.x * r.y ) / rp_.lengthSq() - 1; - assert( k1Sq >= 0.f ); + // slightly negative from rounding errors if the radius is half of the chord + const auto k1Sq = std::max( 0.f, sqr( r.x * r.y ) / rp_.lengthSq() - 1 ); const auto k1 = std::sqrt( k1Sq ) * ( cmd.largeArc != cmd.sweep ? +1.f : -1.f ); assert( std::isfinite( k1 ) ); const auto c_ = k1 * Vector2f { rp_.x / r.y, -rp_.y / r.x }; @@ -207,8 +225,9 @@ std::vector getPoints( Vector2f start, const EllipticalArc& cmd ) for ( auto& p : results ) p = ellXfInv( p ); } - assert( ( p1 - results.front() ).lengthSq() < 1e-6f ); - assert( ( p2 - results.back() ).lengthSq() < 1e-6f ); + // rounding errors grow with the magnitude of the center and the radii + assert( ( p1 - results.front() ).lengthSq() < 1e-6f + sqr( 1e-5f * ( c.length() + std::max( r.x, r.y ) ) ) ); + assert( ( p2 - results.back() ).lengthSq() < 1e-6f + sqr( 1e-5f * ( c.length() + std::max( r.x, r.y ) ) ) ); results.erase( results.begin() ); return results; } @@ -294,6 +313,34 @@ Expected parseTransform( std::string_view str ) return result; } +// parses a number with an optional px unit; other units would be ignored, which gives wrong values +Expected parseNumber( std::string_view str ) +{ + float result = 0.f; + auto it = str.begin(); + if ( !phrase_parse( it, str.end(), float_ >> -lit( "px" ), space, result ) || it != str.end() ) + return unexpected( "Failed to parse number " + std::string( str ) ); + return result; +} + +Expected> parseNumbers( std::string_view str ) +{ + std::vector results; + auto it = str.begin(); + if ( !phrase_parse( it, str.end(), ( float_ >> -lit( "px" ) ) % -lit( ',' ), space, results ) || it != str.end() ) + return unexpected( "Failed to parse numbers " + std::string( str ) ); + return results; +} + +// parses rgb(r, g, b) +Expected> parseRgb( std::string_view str ) +{ + std::vector results; + if ( !phrase_parse( str.begin(), str.end(), lit( "rgb" ) >> '(' >> ( uint_ % ',' ) >> ')', space, results ) || results.size() != 3 ) + return unexpected( "Failed to parse color " + std::string( str ) ); + return results; +} + Expected> parsePath( std::string_view str ) { #define _( ... ) ( [] ( auto& ctx ) { auto& cmd = _val( ctx ); [[maybe_unused]] auto& val = _attr( ctx ); __VA_ARGS__; } ) @@ -325,8 +372,9 @@ Expected> parsePath( std::string_view str ) constexpr auto qscurveto = rule{ "qscurveto" } = eps[_( cmd.shorthand = true )] >> point[_( cmd.end = val )]; + // a flag is a single character, so "11" is two flags constexpr auto arc = rule{ "arc" } - = point[_( cmd.radii = val )] >> float_[_( cmd.xAxisRot = val )] >> int_[_( cmd.largeArc = (bool)val )] >> int_[_( cmd.sweep = (bool)val )] >> point[_( cmd.end = val )]; + = point[_( cmd.radii = val )] >> float_[_( cmd.xAxisRot = val )] >> char_( '0', '1' )[_( cmd.largeArc = val == '1' )] >> char_( '0', '1' )[_( cmd.sweep = val == '1' )] >> point[_( cmd.end = val )]; #undef _ @@ -372,24 +420,346 @@ void close( Contour2f& contour ) contour.emplace_back( contour.front() ); } +// returns nullopt for none +Expected> parseColor( std::string_view str ) +{ + if ( str == "none" ) + return std::optional{}; + if ( str == "black" ) + return Color::black(); + if ( str == "white" ) + return Color::white(); + // #rgb or #rrggbb, whose at most 6 hex digits cannot overflow + unsigned v = 0; + const auto end = str.data() + str.size(); + if ( str.starts_with( '#' ) && ( str.size() == 4 || str.size() == 7 ) && std::from_chars( str.data() + 1, end, v, 16 ).ptr == end ) + return str.size() == 4 ? Color( int( v >> 8 ) * 17, int( ( v >> 4 ) & 0xF ) * 17, int( v & 0xF ) * 17 ) + : Color( int( v >> 16 ), int( ( v >> 8 ) & 0xFF ), int( v & 0xFF ) ); + if ( const auto rgb = parser::parseRgb( str ) ) + return Color( int( std::min( ( *rgb )[0], 255u ) ), int( std::min( ( *rgb )[1], 255u ) ), int( std::min( ( *rgb )[2], 255u ) ) ); + return unexpected( "Unsupported paint " + std::string( str ) ); +} + +// inherited presentation properties +struct Style +{ + std::optional fill = Color::black(); + float fillOpacity = 1.f; + bool evenOdd = false; + std::optional stroke; + float strokeOpacity = 1.f; + float strokeWidth = 1.f; + FT_Stroker_LineCap lineCap = FT_STROKER_LINECAP_BUTT; + FT_Stroker_LineJoin lineJoin = FT_STROKER_LINEJOIN_MITER_FIXED; + float miterLimit = 4.f; + // lengths of dashes and gaps, empty for a solid line + std::vector dashes; + float dashOffset = 0.f; + // the color property, and whether fill and stroke are currentColor, which is resolved with the color of the drawn element + Color color = Color::black(); + bool currentFill = false, currentStroke = false; + // display none, which is not inherited, but children of a hidden element are not drawn either + bool hidden = false; +}; + +// applies a presentation attribute or a style declaration; opacity is not inherited so it is returned separately +Expected applyProperty( Style& style, float& opacity, std::string_view name, std::string_view value ) +{ + value = trim( value ); + const auto color = [value] ( std::optional& target, bool& current ) + { + current = value == "currentColor"; + return current ? Expected{} : parseColor( value ).transform( [&target] ( std::optional c ) { target = c; } ); + }; + // ignoring them would give a wrong image + if ( ( ( name == "mask" || name == "filter" || name == "marker" || name.starts_with( "marker-" ) || name == "vector-effect" ) && value != "none" ) + || ( name == "mix-blend-mode" && value != "normal" ) || ( name == "paint-order" && value != "normal" && !value.starts_with( "fill" ) ) ) + return unexpected( "Unsupported SVG attribute " + std::string( name ) ); + if ( name == "fill" ) + return color( style.fill, style.currentFill ); + if ( name == "stroke" ) + return color( style.stroke, style.currentStroke ); + // currentColor keeps the inherited color + if ( name == "color" && value != "currentColor" ) + return parseColor( value ).transform( [&style] ( std::optional c ) { style.color = c.value_or( style.color ); } ); + const std::pair numbers[] = { { "opacity", &opacity }, { "fill-opacity", &style.fillOpacity }, { "stroke-opacity", &style.strokeOpacity }, + { "stroke-width", &style.strokeWidth }, { "stroke-miterlimit", &style.miterLimit }, { "stroke-dashoffset", &style.dashOffset } }; + for ( const auto& number : numbers ) + if ( name == number.first ) + return parser::parseNumber( value ).transform( [target = number.second] ( float v ) { *target = v; } ); + if ( name == "stroke-dasharray" ) + { + style.dashes.clear(); + if ( value == "none" ) + return {}; + const auto dashes = parser::parseNumbers( value ); + if ( !dashes || std::any_of( dashes->begin(), dashes->end(), [] ( float d ) { return !( d >= 0.f ); } ) ) + return unexpected( "Invalid stroke-dasharray " + std::string( value ) ); + // all zeros give a solid line, and a list of odd length is repeated + if ( std::accumulate( dashes->begin(), dashes->end(), 0.f ) > 0.f ) + { + style.dashes = *dashes; + if ( dashes->size() % 2 == 1 ) + style.dashes.insert( style.dashes.end(), dashes->begin(), dashes->end() ); + } + return {}; + } + if ( name == "fill-rule" ) + style.evenOdd = value == "evenodd"; + else if ( name == "stroke-linecap" ) + style.lineCap = value == "round" ? FT_STROKER_LINECAP_ROUND : value == "square" ? FT_STROKER_LINECAP_SQUARE : FT_STROKER_LINECAP_BUTT; + else if ( name == "stroke-linejoin" ) + style.lineJoin = value == "round" ? FT_STROKER_LINEJOIN_ROUND : value == "bevel" ? FT_STROKER_LINEJOIN_BEVEL : FT_STROKER_LINEJOIN_MITER_FIXED; + else if ( name == "display" ) + style.hidden = value == "none"; + return {}; +} + +Expected applyStyle( const tinyxml2::XMLElement* elem, Style& style, float& opacity ) +{ + for ( auto* attr = elem->FirstAttribute(); attr; attr = attr->Next() ) + if ( auto res = applyProperty( style, opacity, attr->Name(), attr->Value() ); !res ) + return res; + // style declarations take precedence over presentation attributes + Expected res; + if ( const char* declarations = elem->Attribute( "style" ) ) + split( declarations, ";", [&] ( std::string_view decl ) + { + if ( const auto colon = decl.find( ':' ); colon != decl.npos ) + res = applyProperty( style, opacity, trim( decl.substr( 0, colon ) ), decl.substr( colon + 1 ) ); + return !res; + } ); + return res; +} + +// premultiplied colors, rows go from bottom to top as in Image +struct Canvas +{ + Vector2i resolution; + std::vector pixels; + + explicit Canvas( const Vector2i& res ) : resolution( res ), pixels( size_t( res.x ) * res.y ) {} + + void blend( const Canvas& layer, float opacity ) + { + for ( size_t i = 0; i < pixels.size(); ++i ) + { + const auto s = layer.pixels[i] * opacity; + pixels[i] = s + pixels[i] * ( 1.f - s.w ); + } + } +}; + +Vector4f premultiplied( const Color& color, float opacity ) +{ + const auto c = Vector4f( color ); + const auto a = c.w * std::clamp( opacity, 0.f, 1.f ); + return { c.x * a, c.y * a, c.z * a, a }; +} + +Image toImage( const Canvas& canvas ) +{ + const auto byte = [] ( float v ) { return std::clamp( int( std::lround( v * 255.f ) ), 0, 255 ); }; + Image image; + image.resolution = canvas.resolution; + image.pixels.reserve( canvas.pixels.size() ); + for ( const auto& p : canvas.pixels ) + image.pixels.push_back( p.w > 0.f ? Color( byte( p.x / p.w ), byte( p.y / p.w ), byte( p.z / p.w ), byte( p.w ) ) : Color::transparent() ); + return image; +} + +// FreeType's limit of coordinates in pixels, 0x1000000 in 26.6 fixed-point format +constexpr float cMaxPixelCoord = 262144.f; + +// point in 26.6 fixed-point format +FT_Vector toFt( const Vector2f& p ) +{ + return { FT_Pos( std::lround( p.x * 64.f ) ), FT_Pos( std::lround( p.y * 64.f ) ) }; +} + +bool same( const FT_Vector& a, const FT_Vector& b ) +{ + return a.x == b.x && a.y == b.y; +} + +struct SpanPaint +{ + Canvas& canvas; + Vector4f color; +}; + +void blendSpans( int y, int count, const FT_Span* spans, void* user ) +{ + const auto& paint = *static_cast( user ); + auto* row = paint.canvas.pixels.data() + size_t( y ) * paint.canvas.resolution.x; + for ( int i = 0; i < count; ++i ) + { + const auto s = paint.color * ( float( spans[i].coverage ) / 255.f ); + for ( int x = spans[i].x; x < spans[i].x + spans[i].len; ++x ) + row[x] = s + row[x] * ( 1.f - s.w ); + } +} + +Expected render( FT_Library library, FT_Outline& outline, const Vector4f& color, Canvas& canvas ) +{ + SpanPaint paint{ canvas, color }; + FT_Raster_Params params{ .flags = FT_RASTER_FLAG_AA | FT_RASTER_FLAG_DIRECT | FT_RASTER_FLAG_CLIP, .gray_spans = blendSpans, .user = &paint, + .clip_box = { 0, 0, canvas.resolution.x, canvas.resolution.y } }; + // FreeType's rasterizer overflows 32-bit long on an edge of 32768 pixels or longer and never ends + FT_BBox box; + FT_Outline_Get_CBox( &outline, &box ); + if ( std::max( std::int64_t( box.xMax ) - box.xMin, std::int64_t( box.yMax ) - box.yMin ) >= 32768 * 64 ) + return unexpected( "SVG coordinates out of range" ); + if ( const auto error = FT_Outline_Render( library, &outline, ¶ms ) ) + return unexpected( "FreeType rendering error " + std::to_string( error ) ); + return {}; +} + +Expected fill( FT_Library library, const Contours2f& contours, bool evenOdd, const Vector4f& color, Canvas& canvas ) +{ + const auto numPoints = std::accumulate( contours.begin(), contours.end(), size_t( 0 ), [] ( size_t s, const Contour2f& c ) { return s + c.size(); } ); + // FreeType checks the limits of point and contour counts, whose types differ between its versions + FT_Outline outline; + if ( FT_Outline_New( library, FT_UInt( numPoints ), FT_Int( contours.size() ), &outline ) ) + return unexpected( "Too many points or contours in SVG shape" ); + MR_FINALLY { FT_Outline_Done( library, &outline ); }; + // zero tags of a new outline are off-curve points + std::memset( outline.tags, FT_CURVE_TAG_ON, numPoints ); + size_t n = 0; + for ( size_t i = 0; i < contours.size(); ++i ) + { + for ( const auto& p : contours[i] ) + outline.points[n++] = toFt( p ); + outline.contours[i] = std::remove_pointer_t( n - 1 ); + } + outline.flags |= evenOdd ? FT_OUTLINE_EVEN_ODD_FILL : FT_OUTLINE_NONE; + return render( library, outline, color, canvas ); +} + +// splits the contours into dashes by the pattern of dash and gap lengths, multiplied by scale; each contour starts the pattern at the offset +Contours2f dash( const Contours2f& contours, const std::vector& pattern, float offset, float scale ) +{ + // in double, so that adding short dashes to long distances makes progress + const auto length = [&] ( size_t i ) { return double( pattern[i] ) * scale; }; + const auto period = std::accumulate( pattern.begin(), pattern.end(), 0. ) * scale; + Contours2f res; + for ( const auto& contour : contours ) + { + size_t i = 0; + auto pos = std::fmod( double( offset ) * scale, period ); + if ( pos < 0 ) + pos += period; + // a zero-length dash at the offset is not skipped + for ( ; pos > length( i ) || ( pos == length( i ) && pos > 0 ); i = ( i + 1 ) % pattern.size() ) + pos -= length( i ); + // where the current dash or gap ends from the start of the current segment, dashes have even indices + auto end = length( i ) - pos; + const auto first = res.size(); + const bool startsWithDash = i % 2 == 0; + if ( startsWithDash ) + res.push_back( { contour.front() } ); + for ( size_t j = 1; j < contour.size(); ++j ) + { + const auto a = contour[j - 1], b = contour[j]; + const double segment = ( b - a ).length(); + // what ends at b is cut at the start of the next segment, so no dash starts at the end of the contour + for ( ; end < segment; end += length( i ) ) + { + const auto p = a + ( b - a ) * float( end / segment ); + if ( i % 2 == 0 ) + res.back().push_back( p ); + i = ( i + 1 ) % pattern.size(); + if ( i % 2 == 0 ) + res.push_back( { p } ); + } + end -= segment; + if ( i % 2 == 0 ) + res.back().push_back( b ); + } + // a dash through the start of a closed contour is one dash with a join there + if ( startsWithDash && i % 2 == 0 && res.size() > first + 1 && same( toFt( contour.front() ), toFt( contour.back() ) ) ) + { + res.back().insert( res.back().end(), res[first].begin() + 1, res[first].end() ); + res.erase( res.begin() + first ); + } + } + return res; +} + +// scale converts the stroke width and dash lengths to pixels +Expected stroke( FT_Library library, const Contours2f& contours, const Style& style, float scale, const Vector4f& color, Canvas& canvas ) +{ + const auto width = style.strokeWidth * scale; + if ( !( std::abs( width ) <= cMaxPixelCoord ) ) + return unexpected( "SVG coordinates out of range" ); + if ( !style.dashes.empty() ) + { + const auto length = std::accumulate( contours.begin(), contours.end(), 0., [] ( double s, const Contour2f& c ) { return s + calcLength( c ); } ); + // fails early if the dashes would exceed 65535 outline points, estimating 4 points for each of length / period * size / 2 dashes + if ( !( length / ( std::accumulate( style.dashes.begin(), style.dashes.end(), 0. ) * scale ) * double( style.dashes.size() / 2 * 4 ) <= 65535 ) ) + return unexpected( "Too many points or contours in SVG shape" ); + } + FT_Stroker stroker = nullptr; + if ( FT_Stroker_New( library, &stroker ) ) + return unexpected( "Cannot create FreeType stroker" ); + MR_FINALLY { FT_Stroker_Done( stroker ); }; + // the radius is in 26.6 and the miter limit, which SVG requires to be at least 1, is in 16.16 fixed-point format of 32 bits + FT_Stroker_Set( stroker, FT_Fixed( std::lround( width * 32.f ) ), style.lineCap, style.lineJoin, FT_Fixed( std::lround( std::clamp( style.miterLimit, 1.f, 32767.f ) * 65536.f ) ) ); + std::vector points; + const auto dashed = style.dashes.empty() ? Contours2f{} : dash( contours, style.dashes, style.dashOffset, scale ); + for ( const auto& contour : style.dashes.empty() ? contours : dashed ) + { + // FreeType stroker crashes on a subpath without a segment of nonzero length + points.clear(); + for ( const auto& p : contour ) + if ( const auto q = toFt( p ); points.empty() || !same( q, points.back() ) ) + points.push_back( q ); + // a closed contour repeats its first point in the end + const bool closed = points.size() > 2 && same( points.front(), points.back() ); + if ( closed ) + points.pop_back(); + if ( points.size() < 2 ) + { + // a zero-length subpath draws only its caps, nothing for butt caps + if ( style.lineCap == FT_STROKER_LINECAP_BUTT ) + continue; + points.push_back( { points[0].x + 1, points[0].y } ); + } + auto error = FT_Stroker_BeginSubPath( stroker, &points[0], !closed ); + for ( size_t i = 1; !error && i < points.size(); ++i ) + error = FT_Stroker_LineTo( stroker, &points[i] ); + if ( error || FT_Stroker_EndSubPath( stroker ) ) + return unexpected( "FreeType stroking error" ); + } + FT_UInt numPoints = 0, numContours = 0; + if ( FT_Stroker_GetCounts( stroker, &numPoints, &numContours ) ) + return unexpected( "FreeType stroking error" ); + FT_Outline outline; + if ( FT_Outline_New( library, numPoints, FT_Int( numContours ), &outline ) ) + return unexpected( "Too many points or contours in SVG shape" ); + MR_FINALLY { FT_Outline_Done( library, &outline ); }; + // export appends to the outline + outline.n_points = 0; + outline.n_contours = 0; + FT_Stroker_Export( stroker, &outline ); + return render( library, outline, color, canvas ); +} + class SvgLoader { public: explicit SvgLoader( const char* data, size_t size ) { - doc_.Parse( data, size ); + if ( doc_.Parse( data, size ) == XML_SUCCESS && doc_.RootElement() && doc_.RootElement()->Name() == std::string_view{ "svg" } ) + svg_ = doc_.RootElement(); } - explicit operator bool () const { return !doc_.Error(); } - std::string error() const { return doc_.ErrorStr(); } + explicit operator bool () const { return svg_ != nullptr; } + std::string error() const { return doc_.Error() ? doc_.ErrorStr() : "Not an SVG document"; } Expected parse() { - auto* svg = doc_.RootElement(); - if ( !svg || svg->Name() != std::string_view{ "svg" } ) - return unexpected( "Not an SVG document" ); - - if ( auto contours = parseChildren_( svg ) ) + if ( auto contours = parseChildren_( svg_ ) ) { Polyline2 result{ *contours }; // flip Y axis @@ -403,7 +773,168 @@ class SvgLoader } } + Expected rasterize( const Vector2i& resolution ) + { + // FT_Span.x is short in older FreeType versions + if ( !( resolution.x > 0 && resolution.y > 0 && resolution.x <= 32767 && resolution.y <= 32767 ) ) + return unexpected( "Invalid image resolution" ); + // collects the elements that use can draw; style sheets restyle the drawn elements, so ignoring them would give a wrong image + bool styleSheet = false; + const auto collect = [&] ( const auto& self, XMLElement* elem ) -> void + { + for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) + { + styleSheet = styleSheet || child->Name() == std::string_view{ "style" }; + if ( const char* id = child->Attribute( "id" ) ) + ids_.emplace( id, child ); + self( self, child ); + } + }; + collect( collect, svg_ ); + if ( styleSheet ) + return unexpected( "Unsupported SVG element style" ); + // the view box is always fitted uniformly in the center + if ( const char* aspect = svg_->Attribute( "preserveAspectRatio" ); aspect && trim( aspect ) != "xMidYMid" && trim( aspect ) != "xMidYMid meet" ) + return unexpected( "Unsupported SVG attribute preserveAspectRatio" ); + + Box2f viewBox; + if ( const char* attr = svg_->Attribute( "viewBox" ) ) + { + // min and size + const auto points = parser::parsePoints( attr ); + if ( !points || points->size() != 2 ) + return unexpected( "Invalid viewBox " + std::string( attr ) ); + viewBox = Box2f::fromMinAndSize( ( *points )[0], ( *points )[1] ); + } + else + { + const char* width = svg_->Attribute( "width" ); + const char* height = svg_->Attribute( "height" ); + if ( !width || !height ) + return unexpected( "SVG has neither viewBox nor width and height" ); + const auto w = parser::parseNumber( width ); + const auto h = parser::parseNumber( height ); + if ( !w || !h ) + return unexpected( !w ? w.error() : h.error() ); + viewBox = { Vector2f{}, Vector2f{ *w, *h } }; + } + const auto size = viewBox.size(); + if ( !( size.x > 0.f && size.y > 0.f ) ) + return unexpected( "Empty SVG view box" ); + + // fit the view box in the center keeping its aspect ratio; flip Y axis since image rows go from bottom to top + const auto scale = std::min( float( resolution.x ) / size.x, float( resolution.y ) / size.y ); + const auto xf = AffineXf2f::translation( Vector2f( resolution ) / 2.f ) * AffineXf2f::linear( Matrix2f::scale( scale, -scale ) ) + * AffineXf2f::translation( -viewBox.center() ); + + FT_Library library = nullptr; + if ( FT_Init_FreeType( &library ) ) + return unexpected( "Cannot initialize FreeType" ); + MR_FINALLY { FT_Done_FreeType( library ); }; + + Canvas canvas( resolution ); + return render_( library, svg_, xf, {}, canvas, 0 ).transform( [&] { return toImage( canvas ); } ); + } + private: + // draws the element with its children over the canvas + Expected render_( FT_Library library, XMLElement* elem, AffineXf2f xf, Style style, Canvas& canvas, int depth ) + { + // use nests elements deeper than XML does, which would overflow the stack, and can multiply them without bound + if ( depth >= 128 ) + return unexpected( "SVG nesting is too deep" ); + if ( ++numDrawn_ > 100000 ) + return unexpected( "SVG has too many elements to draw" ); + const std::string_view name = elem->Name(); + // use draws the element it references as its only child + const bool use = name == "use"; + const bool group = elem == svg_ || name == "g" || name == "a" || use; + // drawing them is not supported, and omitting them would give a wrong image; text without content draws nothing + const bool unsupported = !group && ( name == "image" || ( name == "text" && elem->FirstChild() ) || name == "svg" || name == "switch" || name == "foreignObject" ); + const bool shape = !group && !unsupported; + auto contours = shape ? parseElement_( elem ) : Expected{}; + if ( !contours ) + return unexpected( std::move( contours.error() ) ); + // omitting unknown elements and empty shapes + if ( shape && contours->empty() ) + return {}; + + const char* t = elem->Attribute( "transform" ); + const auto elemXf = t ? parser::parseTransform( t ) : AffineXf2f{}; + if ( !elemXf ) + return unexpected( std::move( elemXf.error() ) ); + xf = xf * *elemXf; + if ( use ) + xf = xf * AffineXf2f::translation( { elem->FloatAttribute( "x" ), elem->FloatAttribute( "y" ) } ); + float opacity = 1.f; + if ( auto res = applyStyle( elem, style, opacity ); !res || style.hidden ) + return res; + if ( unsupported ) + return unexpected( "Unsupported SVG element " + std::string( name ) ); + + // an element with opacity is drawn in a separate layer + opacity = std::clamp( opacity, 0.f, 1.f ); + std::optional layer; + Canvas& target = opacity < 1.f ? layer.emplace( canvas.resolution ) : canvas; + if ( use ) + { + const char* href = elem->Attribute( "href" ) ? elem->Attribute( "href" ) : elem->Attribute( "xlink:href" ); + if ( href && *href != '#' ) + return unexpected( "Unsupported SVG use reference " + std::string( href ) ); + // a reference to a missing element draws nothing, as in browsers + if ( const auto it = href ? ids_.find( href + 1 ) : ids_.end(); it != ids_.end() ) + { + // a symbol is drawn only by use, which is not supported for it + if ( it->second->Name() == std::string_view{ "symbol" } ) + return unexpected( "Unsupported SVG element symbol" ); + if ( std::find( useTargets_.begin(), useTargets_.end(), it->second ) != useTargets_.end() ) + return unexpected( "SVG use references form a cycle" ); + useTargets_.push_back( it->second ); + MR_FINALLY { useTargets_.pop_back(); }; + if ( auto res = render_( library, it->second, xf, style, target, depth + 1 ); !res ) + return res; + } + } + else if ( group ) + { + for ( auto* child = elem->FirstChildElement(); child; child = child->NextSiblingElement() ) + if ( auto res = render_( library, child, xf, style, target, depth + 1 ); !res ) + return res; + } + else + { + for ( auto& contour : *contours ) + for ( auto& p : contour ) + { + p = xf( p ); + // NaN fails the check too + if ( !( std::abs( p.x ) <= cMaxPixelCoord && std::abs( p.y ) <= cMaxPixelCoord ) ) + return unexpected( "SVG coordinates out of range" ); + } + if ( const auto color = style.currentFill ? style.color : style.fill ) + { + if ( auto res = fill( library, *contours, style.evenOdd, premultiplied( *color, style.fillOpacity ), target ); !res ) + return res; + } + if ( const auto color = style.currentStroke ? style.color : style.stroke ) + { + // pathLength rescales the dashes + if ( !style.dashes.empty() && elem->Attribute( "pathLength" ) ) + return unexpected( "Unsupported SVG attribute pathLength" ); + // the stroke is drawn with a round pen in pixels, which is right only if the transform keeps circles + const auto n = xf.A.x.lengthSq() + xf.A.y.lengthSq(); + if ( std::abs( xf.A.x.lengthSq() - xf.A.y.lengthSq() ) > 1e-4f * n || std::abs( dot( xf.A.x, xf.A.y ) ) > 1e-4f * n ) + return unexpected( "Unsupported SVG stroke under non-uniform scale or skew" ); + const auto pixelScale = std::sqrt( std::abs( xf.A.det() ) ); + if ( auto res = stroke( library, *contours, style, pixelScale, premultiplied( *color, style.strokeOpacity ), target ); !res ) + return res; + } + } + if ( layer ) + canvas.blend( *layer, opacity ); + return {}; + } + Expected parseChildren_( XMLElement* group ) const { Contours2f results; @@ -461,14 +992,19 @@ class SvgLoader Expected parsePath_( XMLElement* elem ) const { - const std::string_view d = elem->Attribute( "d" ); + // an empty path is valid and draws nothing + const char* d = elem->Attribute( "d" ); + if ( !d || trim( d ).empty() ) + return {}; const auto commands = parser::parsePath( d ); if ( !commands ) return unexpected( std::move( commands.error() ) ); Contours2f results; Vector2f pos{}; + // a smooth curve reflects the control point of the previous curve only if it is of the same kind std::optional nextCurveControlPoint{}; + bool cubicControlPoint = false; results.emplace_back(); for ( const auto& command : *commands ) { @@ -523,8 +1059,9 @@ class SvgLoader if ( results.back().empty() ) results.back().emplace_back( pos ); - if ( !nextCurveControlPoint ) + if ( !nextCurveControlPoint || !cubicControlPoint ) nextCurveControlPoint = pos; + cubicControlPoint = true; for ( auto p : Path::getPoints( pos, *nextCurveControlPoint, cmd ) ) results.back().emplace_back( p ); @@ -535,8 +1072,9 @@ class SvgLoader if ( results.back().empty() ) results.back().emplace_back( pos ); - if ( !nextCurveControlPoint ) + if ( !nextCurveControlPoint || cubicControlPoint ) nextCurveControlPoint = pos; + cubicControlPoint = false; for ( auto p : Path::getPoints( pos, *nextCurveControlPoint, cmd ) ) results.back().emplace_back( p ); @@ -611,17 +1149,17 @@ class SvgLoader Expected parsePolygon_( XMLElement* elem ) const { - const std::string pointsStr = elem->Attribute( "points" ); - auto points = parser::parsePoints( pointsStr ); - if ( !points ) - return unexpected( std::move( points.error() ) ); - close( *points ); - return { { std::move( *points ) } }; + auto res = parsePolyline_( elem ); + if ( res && !res->empty() ) + close( res->front() ); + return res; } Expected parsePolyline_( XMLElement* elem ) const { - const std::string pointsStr = elem->Attribute( "points" ); + const char* pointsStr = elem->Attribute( "points" ); + if ( !pointsStr || trim( pointsStr ).empty() ) + return {}; auto points = parser::parsePoints( pointsStr ); if ( !points ) return unexpected( std::move( points.error() ) ); @@ -638,13 +1176,14 @@ class SvgLoader auto ry = elem->FloatAttribute( "ry", 0.f ); if ( width == 0.f || height == 0.f ) return {}; + // like its equivalent path in SVG, which sets the dash pattern, the rect starts at ( x + rx, y ) and goes in +x direction if ( rx == 0.f && ry == 0.f ) { Contour2f rect { { x, y }, - { x, y + height }, - { x + width, y + height }, { x + width, y }, + { x + width, y + height }, + { x, y + height }, { x, y }, }; return { { std::move( rect ) } }; @@ -661,7 +1200,7 @@ class SvgLoader if ( height / 2.f < ry ) ry = height / 2.f; - Contour2f points; + Contour2f points{ Vector2f{ x + rx, y } }; for ( auto p : getEllipsePoints( { .cx = x + width - rx, .cy = y + ry, @@ -698,13 +1237,19 @@ class SvgLoader .a1 = -PI2_F, } ) ) points.emplace_back( p ); - close( points ); + // the last arc ends at the start up to rounding errors + points.back() = points.front(); return { { std::move( points ) } }; } } private: tinyxml2::XMLDocument doc_; + // the root element if it is svg, elements by their ids, the elements being drawn by use to detect cycles, and the number of drawn elements + XMLElement* svg_ = nullptr; + HashMap ids_; + std::vector useTargets_; + size_t numDrawn_ = 0; }; } // namespace @@ -742,4 +1287,29 @@ Expected fromSvg( const char* data, size_t size, const LinesLoadSetti MR_ADD_LINES_LOADER(IOFilter( "SVG (.svg)", "*.svg" ), fromSvg) } // namespace MR::LinesLoad + +namespace MR::ImageLoad +{ + +Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ) +{ + std::ifstream in( file, std::ifstream::binary ); + if ( !in ) + return unexpected( std::string( "Cannot open file for reading " ) + utf8string( file ) ); + + return addFileNameInError( readCharBuffer( in ).and_then( [&] ( Buffer&& buf ) + { + return fromSvg( buf.data(), buf.size(), resolution ); + } ), file ); +} + +Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ) +{ + LinesLoad::SvgLoader loader( data, size ); + if ( !loader ) + return unexpected( loader.error() ); + return loader.rasterize( resolution ); +} + +} // namespace MR::ImageLoad #endif diff --git a/source/MRIOExtras/MRSvg.h b/source/MRIOExtras/MRSvg.h index f7d3776f2369..0fb2ae4f8a4c 100644 --- a/source/MRIOExtras/MRSvg.h +++ b/source/MRIOExtras/MRSvg.h @@ -5,6 +5,7 @@ #include "exports.h" #include "MRMesh/MRExpected.h" +#include "MRMesh/MRImage.h" #include "MRMesh/MRLinesLoadSettings.h" #include @@ -18,4 +19,19 @@ MRIOEXTRAS_API Expected fromSvg( std::istream& in, const LinesLoadSet MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const LinesLoadSettings& settings = {} ); } // namespace MR::LinesLoad + +namespace MR::ImageLoad +{ + +/// rasterizes .SVG file into an image of given resolution (from 1 to 32767 in each dimension), the view box is fitted in the center keeping its aspect ratio; +/// meant for small images like icons, since curves are flattened into 32 segments each whatever the resolution; +/// draws the shapes loaded by LinesLoad::fromSvg with solid fill and stroke (color, currentColor, opacity, fill-rule, stroke width, caps, joins, miter limit, dashes), +/// group and element opacity, display none, use of elements in the document; other paints (gradients, patterns, named colors other than black and white), +/// drawn image, text with content, switch, foreignObject, nested svg elements, use of symbol, strokes under non-uniform scale or skew, units other than px, +/// style sheets, mask, filter give an error, as well as markers, vector-effect, mix-blend-mode, paint-order not starting with fill, pathLength of dashed strokes, preserveAspectRatio other than xMidYMid meet; +/// other elements and attributes (e.g. clip-path, visibility) are ignored +MRIOEXTRAS_API Expected fromSvg( const std::filesystem::path& file, const Vector2i& resolution ); +MRIOEXTRAS_API Expected fromSvg( const char* data, size_t size, const Vector2i& resolution ); + +} // namespace MR::ImageLoad #endif diff --git a/source/MRTest/MRSvgTests.cpp b/source/MRTest/MRSvgTests.cpp index 4d0a8097cec2..bd406aedaa80 100644 --- a/source/MRTest/MRSvgTests.cpp +++ b/source/MRTest/MRSvgTests.cpp @@ -4,12 +4,18 @@ #include #include +#include #include #include namespace MR { +static Expected rasterize( const std::string& svg, const Vector2i& res ) +{ + return ImageLoad::fromSvg( svg.data(), svg.size(), res ); +} + // a file with symbols outside of any single code page in its name must be opened on Windows as well TEST( MRIOExtras, SvgUnicodeFileName ) { @@ -17,16 +23,382 @@ TEST( MRIOExtras, SvgUnicodeFileName ) ASSERT_TRUE( bool( folder ) ); const auto path = folder / std::filesystem::path( u8"\u0442\u0435\u0441\u0442 \u6587\u4ef6 \u00e9.svg" ); std::ofstream( path, std::ofstream::binary ) - << R"()"; + << R"()"; const auto loaded = LinesLoad::fromSvg( path ); ASSERT_TRUE( loaded ) << loaded.error(); EXPECT_EQ( loaded->topology.numValidVerts(), 2 ); + const auto image = ImageLoad::fromSvg( path, { 10, 5 } ); + EXPECT_TRUE( image ) << image.error(); const auto absent = LinesLoad::fromSvg( folder / "absent.svg" ); ASSERT_FALSE( absent ); EXPECT_TRUE( absent.error().starts_with( "Cannot open file for reading" ) ) << absent.error(); } +// arcs with the radius almost exactly half of the chord, with identical endpoints, which are omitted, with a zero radius, which are straight lines, +// with flags without separators, and with large coordinates or radii, whose rounding errors grow with the magnitude +TEST( MRIOExtras, SvgArcs ) +{ + const std::pair paths[] = { + { "M2.37 3.29 A2.6 2.6 0 0 1 6.5 6.46", 33 }, + { "M0 0 L1 1 A1 1 0 0 1 1 1 L2 0", 3 }, + { "M0 0 A0 1 0 0 1 2 0", 2 }, + { "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z", 68 }, + { "M100000.3 100000.7 A5.3 4.1 20 0 1 100007.1 100006.2", 33 }, + { "M0 0 A100000 100000 0 0 1 1 0", 33 }, + }; + for ( const auto& [d, numVerts] : paths ) + { + const auto svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), numVerts ) << d; + for ( const auto& p : loaded->points ) + EXPECT_TRUE( std::isfinite( p.x ) && std::isfinite( p.y ) ) << d; + const auto image = rasterize( svg, { 24, 24 } ); + EXPECT_TRUE( image ) << d << ": " << image.error(); + } +} + +// a smooth curve reflects the control point of the previous curve only if it is of the same kind, otherwise its control point is the current point; +// arc flags are single characters, so they need no separators +TEST( MRIOExtras, SvgSmoothCurves ) +{ + const auto load = [] ( const std::string& d ) + { + const auto svg = R"()"; + return LinesLoad::fromSvg( svg.data(), svg.size() ); + }; + // smooth and equivalent full commands, compact and spaced arc flags + const std::pair paths[] = { + { "M0 0 Q5 10 10 0 S10 10 10 10", "M0 0 Q5 10 10 0 C10 0 10 10 10 10" }, + { "M0 0 C0 5 5 5 5 0 T10 0", "M0 0 C0 5 5 5 5 0 Q5 0 10 0" }, + { "M0 0 C0 5 5 5 5 0 S10 -5 10 0", "M0 0 C0 5 5 5 5 0 C5 -5 10 -5 10 0" }, + { "M0 0 Q5 10 10 0 T20 0", "M0 0 Q5 10 10 0 Q15 -10 20 0" }, + { "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z", "M9 12l2 2 4-4m6 2a9 9 0 1 1-18 0 9 9 0 0,1 18 0z" }, + }; + for ( const auto& [smooth, full] : paths ) + { + const auto loaded = load( smooth ); + ASSERT_TRUE( loaded ) << loaded.error(); + const auto expected = load( full ); + ASSERT_TRUE( expected ) << expected.error(); + EXPECT_TRUE( loaded->points == expected->points ) << smooth; + } +} + +// a rect starts at ( x + rx, y ) and goes in +x direction as its equivalent path in SVG, which sets its dash pattern +TEST( MRIOExtras, SvgRectDirection ) +{ + const std::pair rects[] = { { "0", 1.f }, { "2", 3.f } }; + for ( const auto& [rx, startX] : rects ) + { + const auto svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_TRUE( loaded->topology.isClosed() ) << rx; + EXPECT_EQ( loaded->topology.numValidVerts(), rx == "0" ? 4 : 132 ) << rx; + // Y axis is flipped + EXPECT_EQ( loaded->points[0_v], Vector3f( startX, -1.f, 0.f ) ) << rx; + EXPECT_EQ( loaded->points[1_v].y, -1.f ) << rx; + EXPECT_GT( loaded->points[1_v].x, startX ) << rx; + } + + const auto draw = [] ( const std::string& shape ) + { + return rasterize( R"(<)" + shape + R"( fill="none" stroke="#000" stroke-width="2" stroke-dasharray="3 2"/>)", { 24, 16 } ); + }; + const auto rect = draw( R"(rect x="1" y="1" width="10" height="6")" ); + ASSERT_TRUE( rect ) << rect.error(); + const auto path = draw( R"(path d="M1 1H11V7H1Z")" ); + ASSERT_TRUE( path ) << path.error(); + EXPECT_TRUE( rect->pixels == path->pixels ); + // a dash through the start of a closed path has a join there instead of two caps, so the outer corner is filled + EXPECT_EQ( ( *path )[Vector2i( 0, 15 )], Color::black() ); +} + +// shapes without their geometry attributes or with empty ones are empty +TEST( MRIOExtras, SvgMissingAttributes ) +{ + const std::string svg = R"()"; + const auto loaded = LinesLoad::fromSvg( svg.data(), svg.size() ); + ASSERT_TRUE( loaded ) << loaded.error(); + EXPECT_EQ( loaded->topology.numValidVerts(), 0 ); + const auto image = rasterize( svg, { 1, 1 } ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::transparent() ); +} + +TEST( MRIOExtras, SvgRasterize ) +{ + // red top-left quadrant, and blue horizontal line 1 wide at y = 3 + const auto image = rasterize( R"svg( + + +)svg", { 8, 8 } ); + ASSERT_TRUE( image ) << image.error(); + ASSERT_EQ( image->resolution, Vector2i( 8, 8 ) ); + // image rows go from bottom to top + EXPECT_EQ( ( *image )[Vector2i( 1, 6 )], Color( 255, 0, 0 ) ); + EXPECT_EQ( ( *image )[Vector2i( 6, 6 )], Color::transparent() ); + EXPECT_EQ( ( *image )[Vector2i( 5, 3 )], Color::transparent() ); + EXPECT_EQ( ( *image )[Vector2i( 5, 2 )], Color( 0, 0, 255 ) ); + EXPECT_EQ( ( *image )[Vector2i( 5, 1 )], Color( 0, 0, 255 ) ); + EXPECT_EQ( ( *image )[Vector2i( 5, 0 )], Color::transparent() ); + + // the stroke width is scaled by the group transform, so the line at y = 4 is 2 pixels wide + const auto scaled = rasterize( R"svg()svg", { 8, 8 } ); + ASSERT_TRUE( scaled ) << scaled.error(); + for ( int y = 2; y <= 5; ++y ) + EXPECT_EQ( ( *scaled )[Vector2i( 4, y )], y == 3 || y == 4 ? Color::black() : Color::transparent() ) << y; +} + +TEST( MRIOExtras, SvgRasterizeFillRuleOpacity ) +{ + const auto ring = [] ( const std::string& rule ) + { + return rasterize( R"()", { 4, 4 } ); + }; + const auto evenOdd = ring( "evenodd" ); + ASSERT_TRUE( evenOdd ) << evenOdd.error(); + EXPECT_EQ( ( *evenOdd )[Vector2i( 0, 0 )], Color::black() ); + EXPECT_EQ( ( *evenOdd )[Vector2i( 1, 1 )], Color::transparent() ); + const auto nonZero = ring( "nonzero" ); + ASSERT_TRUE( nonZero ) << nonZero.error(); + EXPECT_EQ( ( *nonZero )[Vector2i( 1, 1 )], Color::black() ); + + // group opacity applies to the group as a whole, so the overlap of its rectangles is not darker + const auto image = rasterize( R"()", { 2, 1 } ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color( 255, 255, 255, 128 ) ); + EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color( 255, 255, 255, 128 ) ); + + // element opacity applies to its fill and stroke together, so their overlap is not darker + const auto element = rasterize( R"()", { 8, 8 } ); + ASSERT_TRUE( element ) << element.error(); + EXPECT_EQ( ( *element )[Vector2i( 2, 4 )], Color( 255, 255, 255, 128 ) ); +} + +TEST( MRIOExtras, SvgRasterizeUse ) +{ + const auto draw = [] ( const std::string& shapes ) + { + return rasterize( R"()" + shapes + "", { 7, 1 } ); + }; + // use draws the referenced element moved by x, y and its transform, which inherits the style of use but keeps its own, also through a group or another use; + // opacity of use applies to the drawn element, the elements in defs are not drawn by themselves, and a reference to a missing element draws nothing + const auto image = draw( R"svg()svg" + R"svg()svg" + R"svg()svg" + R"svg()svg" ); + ASSERT_TRUE( image ) << image.error(); + const Color expected[] = { Color( 255, 0, 0 ), Color( 0, 0, 255 ), Color( 0, 255, 0 ), Color( 255, 0, 0 ), Color( 0, 0, 255 ), Color( 0, 0, 0, 128 ), Color::transparent() }; + for ( int x = 0; x < 7; ++x ) + EXPECT_EQ( ( *image )[Vector2i( x, 0 )], expected[x] ) << x; + + // use can nest elements deeper than XML does, so too deep nesting gives an error instead of overflowing the stack + const auto chain = [&] ( int length ) + { + std::string shapes = R"()"; + for ( int i = 1; i <= length; ++i ) + shapes += ""; + return draw( shapes + "" ); + }; + const auto deep = chain( 200 ); + ASSERT_FALSE( deep ); + EXPECT_EQ( deep.error(), "SVG nesting is too deep" ); + const auto shallow = chain( 50 ); + ASSERT_TRUE( shallow ) << shallow.error(); + EXPECT_EQ( ( *shallow )[Vector2i( 0, 0 )], Color::black() ); +} + +// a zero-length subpath draws only its caps, which are nothing for butt caps +TEST( MRIOExtras, SvgRasterizeDot ) +{ + const auto dot = [] ( const std::string& cap ) + { + return rasterize( R"()", { 8, 8 } ); + }; + const auto round = dot( "round" ); + ASSERT_TRUE( round ) << round.error(); + EXPECT_EQ( ( *round )[Vector2i( 3, 3 )], Color::black() ); + EXPECT_EQ( ( *round )[Vector2i( 0, 0 )], Color::transparent() ); + const auto square = dot( "square" ); + ASSERT_TRUE( square ) << square.error(); + EXPECT_EQ( ( *square )[Vector2i( 2, 2 )], Color::black() ); + const auto butt = dot( "butt" ); + ASSERT_TRUE( butt ) << butt.error(); + EXPECT_EQ( std::count( butt->pixels.begin(), butt->pixels.end(), Color::transparent() ), 64 ); +} + +// a stroked circle is closed, so it has a join and no notch between two caps at its seam on the right +TEST( MRIOExtras, SvgRasterizeCircleSeam ) +{ + const auto image = rasterize( R"()", { 64, 64 } ); + ASSERT_TRUE( image ) << image.error(); + // 8 pixels outward from the seam, and from the opposite point + EXPECT_EQ( ( *image )[Vector2i( 56, 31 )], ( *image )[Vector2i( 7, 31 )] ); + EXPECT_EQ( ( *image )[Vector2i( 7, 31 )], Color::black() ); +} + +// the view box is fitted uniformly in the center of a non-square image +TEST( MRIOExtras, SvgRasterizeAspectRatio ) +{ + const std::string svg = R"()"; + for ( const auto& res : { Vector2i( 4, 2 ), Vector2i( 2, 4 ) } ) + { + const auto image = rasterize( svg, res ); + ASSERT_TRUE( image ) << image.error(); + // columns or rows 0 and 3 are empty + for ( int y = 0; y < res.y; ++y ) + for ( int x = 0; x < res.x; ++x ) + EXPECT_EQ( ( *image )[Vector2i( x, y )], ( res.x > res.y ? x : y ) % 3 == 0 ? Color::transparent() : Color::black() ) << x << ' ' << y; + } +} + +// currentColor is the color property of the drawn element even if it is inherited or set after it +TEST( MRIOExtras, SvgRasterizeCurrentColor ) +{ + const auto image = rasterize( R"()" + R"()" + R"()", { 9, 3 } ); + ASSERT_TRUE( image ) << image.error(); + for ( int x : { 1, 4, 7 } ) + EXPECT_EQ( ( *image )[Vector2i( x, 1 )], Color( 255, 0, 0 ) ) << x; +} + +// elements and attributes that would be drawn wrong give errors +TEST( MRIOExtras, SvgRasterizeUnsupported ) +{ + const auto draw = [] ( const std::string& shapes ) + { + return rasterize( R"()" + shapes + "", { 2, 1 } ); + }; + const std::pair errors[] = { + { "", "Unsupported SVG element svg" }, + { "", "Unsupported SVG element switch" }, + { "", "Unsupported SVG element foreignObject" }, + { "a", "Unsupported SVG element text" }, + { "", "Unsupported SVG element style" }, + { R"svg()svg", "Unsupported paint url(#g)" }, + { R"svg()svg", "Unsupported SVG attribute mask" }, + { R"svg()svg", "Unsupported SVG attribute filter" }, + { R"()", "Invalid stroke-dasharray 1 -1" }, + { R"()", "Too many points or contours in SVG shape" }, + { R"()", "Unsupported SVG attribute pathLength" }, + { R"svg()svg", "Unsupported SVG attribute marker" }, + { R"svg()svg", "Unsupported SVG attribute marker-start" }, + { R"svg()svg", "Unsupported SVG attribute marker-mid" }, + { R"svg()svg", "Unsupported SVG attribute marker-end" }, + { R"()", "Unsupported SVG attribute vector-effect" }, + { R"()", "Unsupported SVG attribute mix-blend-mode" }, + { R"()", "Unsupported SVG attribute paint-order" }, + { R"svg()svg", "SVG use references form a cycle" }, + { R"svg()svg", "SVG use references form a cycle" }, + { R"svg()svg", "Unsupported SVG element symbol" }, + { R"svg()svg", "Unsupported SVG use reference other.svg#a" }, + { R"()", "SVG coordinates out of range" }, + { R"()", "SVG coordinates out of range" }, + { R"()", "SVG coordinates out of range" }, + // FreeType's rasterizer never ends on an edge of 32768 pixels or longer, as in this fill or the caps of this stroke + { R"()", "SVG coordinates out of range" }, + { R"()", "SVG coordinates out of range" }, + { R"svg()svg", "Unsupported SVG stroke under non-uniform scale or skew" }, + { R"svg()svg", "Unsupported SVG stroke under non-uniform scale or skew" }, + { R"()", "Failed to parse number 0.5mm" }, + { R"()", "Failed to parse number 50%" }, + { R"()", "Invalid stroke-dasharray 1px 2em" }, + }; + for ( const auto& [shapes, error] : errors ) + { + const auto image = draw( shapes ); + ASSERT_FALSE( image ) << shapes; + EXPECT_EQ( image.error(), error ); + } + + const auto unsupportedAspect = rasterize( R"()", { 2, 2 } ); + ASSERT_FALSE( unsupportedAspect ); + EXPECT_EQ( unsupportedAspect.error(), "Unsupported SVG attribute preserveAspectRatio" ); + + for ( const Vector2i& res : { Vector2i( 0, 1 ), Vector2i( -1, 10 ), Vector2i( 32768, 1 ) } ) + { + const auto invalid = rasterize( R"()", res ); + ASSERT_FALSE( invalid ) << res.x << " " << res.y; + EXPECT_EQ( invalid.error(), "Invalid image resolution" ); + } + + // use can multiply the drawn elements beyond any limit: here 10^6 empty groups + std::string fanOut = R"()"; + for ( int i = 1; i <= 6; ++i ) + { + fanOut += ""; + for ( int j = 0; j < 10; ++j ) + fanOut += ""; + fanOut += ""; + } + const auto tooMany = draw( fanOut + R"()" ); + ASSERT_FALSE( tooMany ); + EXPECT_EQ( tooMany.error(), "SVG has too many elements to draw" ); + + // a is a group, currentColor is black, default values and px are supported, hidden elements are not drawn even if they are unsupported; + // text without content and a symbol not drawn by use draw nothing; a fill is right under any transform + const auto image = draw( R"svg()" + R"(a)" + R"()" ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::black() ); + EXPECT_EQ( ( *image )[Vector2i( 1, 0 )], Color::transparent() ); +} + +TEST( MRIOExtras, SvgRasterizeDashes ) +{ + // a stroke through the only row of pixels, dash ends are on pixel borders; alpha of at least hi is '#', at most lo is '.', otherwise '?' + const auto row = [] ( const std::string& stroke, int lo = 0, int hi = 255 ) + { + const auto image = rasterize( R"svg(", { 10, 1 } ); + if ( !image ) + return image.error(); + std::string res; + for ( const auto& c : image->pixels ) + res += c.a >= hi ? '#' : c.a <= lo ? '.' : '?'; + return res; + }; + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="2")" ), "##..##...." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="2 2" stroke-dashoffset="1")" ), "#..##..#.." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="2,2" stroke-dashoffset="-1")" ), ".##..##..." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" style="stroke-dasharray: 1, 2, 3")" ), "#..###.#.." ); + EXPECT_EQ( row( R"(d="M0 0.5H8" stroke-dasharray="0 0")" ), "########.." ); + // a zero-length dash at the start is a dot of round caps, and no dash starts at the end of a path + EXPECT_EQ( row( R"(d="M0.5 .5H9.5" stroke-linecap="round" stroke-dasharray="0 3")", 15, 129 ), "#..#..#..." ); + EXPECT_EQ( row( R"(d="M1 .5H9" stroke-linecap="round" stroke-dasharray="2")", 15, 129 ), "?##??##?.." ); + + // the pattern goes on through the vertices of a polyline, and its lengths are transformed as the stroke width + const auto image = rasterize( R"svg()svg", { 16, 2 } ); + ASSERT_TRUE( image ) << image.error(); + for ( int x = 0; x < 16; ++x ) + EXPECT_EQ( ( *image )[Vector2i( x, 1 )].a, x % 4 < 2 ? 255 : 0 ) << x; +} + +// a miter limit beyond the range of FreeType's fixed-point format still gives miter joins +TEST( MRIOExtras, SvgRasterizeMiterLimit ) +{ + const auto image = rasterize( R"()", { 8, 8 } ); + ASSERT_TRUE( image ) << image.error(); + // the tip of the miter at the top-left corner + EXPECT_EQ( ( *image )[Vector2i( 0, 7 )], Color::black() ); +} + +// an icon as exported from Figma, whose clip path covers the whole icon +TEST( MRIOExtras, SvgRasterizeFigmaIcon ) +{ + const auto image = rasterize( R"svg()svg" + R"()", { 24, 24 } ); + ASSERT_TRUE( image ) << image.error(); + EXPECT_EQ( ( *image )[Vector2i( 12, 12 )], Color( 0x1C, 0x9C, 0x01 ) ); + EXPECT_EQ( ( *image )[Vector2i( 0, 0 )], Color::transparent() ); +} + } // namespace MR #endif