SVG parser improvements

This commit is contained in:
Viktor Chlumský 2017-06-05 15:09:56 +02:00
parent 8c352b6153
commit 746767a62b
4 changed files with 321 additions and 187 deletions

View File

@ -57,7 +57,7 @@ The input can be specified as one of:
- **-font \<filename.ttf\> \<character code\>** &ndash; to load a glyph from a font file. - **-font \<filename.ttf\> \<character code\>** &ndash; to load a glyph from a font file.
Character code can be expressed as either a decimal (63) or hexadecimal (0x3F) Unicode value, or an ASCII character Character code can be expressed as either a decimal (63) or hexadecimal (0x3F) Unicode value, or an ASCII character
in single quotes ('?'). in single quotes ('?').
- **-svg \<filename.svg\>** &ndash; to load an SVG file. Note that only the first vector path in the file will be used. - **-svg \<filename.svg\>** &ndash; to load an SVG file. Note that only the last vector path in the file will be used.
- **-shapedesc \<filename.txt\>**, -defineshape \<definition\>, -stdin &ndash; to load a text description of the shape - **-shapedesc \<filename.txt\>**, -defineshape \<definition\>, -stdin &ndash; to load a text description of the shape
from either a file, the next argument, or the standard input, respectively. Its syntax is documented further down. from either a file, the next argument, or the standard input, respectively. Its syntax is documented further down.

View File

@ -1,183 +1,316 @@
#include "import-svg.h" #define _USE_MATH_DEFINES
#include "import-svg.h"
#include <cstdio>
#include <tinyxml2.h> #include <cstdio>
#include <tinyxml2.h>
#ifdef _WIN32 #include "../core/arithmetics.hpp"
#pragma warning(disable:4996)
#endif #ifdef _WIN32
#pragma warning(disable:4996)
namespace msdfgen { #endif
#define REQUIRE(cond) { if (!(cond)) return false; } #define ARC_SEGMENTS_PER_PI 2
#define ENDPOINT_SNAP_RANGE_PROPORTION (1/16384.)
static bool readNodeType(char &output, const char *&pathDef) {
int shift; namespace msdfgen {
char nodeType;
if (sscanf(pathDef, " %c%n", &nodeType, &shift) == 1 && nodeType != '+' && nodeType != '-' && nodeType != '.' && nodeType != ',' && (nodeType < '0' || nodeType > '9')) { #if defined(_DEBUG) || !NDEBUG
pathDef += shift; #define REQUIRE(cond) { if (!(cond)) { fprintf(stderr, "SVG Parse Error (%s:%d): " #cond "\n", __FILE__, __LINE__); return false; } }
output = nodeType; #else
return true; #define REQUIRE(cond) { if (!(cond)) return false; }
} #endif
return false;
} static bool readNodeType(char &output, const char *&pathDef) {
int shift;
static bool readCoord(Point2 &output, const char *&pathDef) { char nodeType;
int shift; if (sscanf(pathDef, " %c%n", &nodeType, &shift) == 1 && nodeType != '+' && nodeType != '-' && nodeType != '.' && nodeType != ',' && (nodeType < '0' || nodeType > '9')) {
double x, y; pathDef += shift;
if (sscanf(pathDef, "%lf%lf%n", &x, &y, &shift) == 2) { output = nodeType;
output.x = x; return true;
output.y = y; }
pathDef += shift; return false;
return true; }
}
if (sscanf(pathDef, "%lf,%lf%n", &x, &y, &shift) == 2) { static bool readCoord(Point2 &output, const char *&pathDef) {
output.x = x; int shift;
output.y = y; double x, y;
pathDef += shift; if (sscanf(pathDef, " %lf%lf%n", &x, &y, &shift) == 2 || sscanf(pathDef, " %lf , %lf%n", &x, &y, &shift) == 2) {
return true; output.x = x;
} output.y = y;
return false; pathDef += shift;
} return true;
}
static bool readDouble(double &output, const char *&pathDef) { return false;
int shift; }
double v;
if (sscanf(pathDef, "%lf%n", &v, &shift) == 1) { static bool readDouble(double &output, const char *&pathDef) {
pathDef += shift; int shift;
output = v; double v;
return true; if (sscanf(pathDef, " %lf%n", &v, &shift) == 1) {
} pathDef += shift;
return false; output = v;
} return true;
}
static void consumeOptionalComma(const char *&pathDef) { return false;
while (*pathDef == ' ') }
++pathDef;
if (*pathDef == ',') static bool readBool(bool &output, const char *&pathDef) {
++pathDef; int shift;
} int v;
if (sscanf(pathDef, " %d%n", &v, &shift) == 1) {
static bool buildFromPath(Shape &shape, const char *pathDef) { pathDef += shift;
char nodeType; output = v != 0;
Point2 prevNode(0, 0); return true;
while (readNodeType(nodeType, pathDef)) { }
Contour &contour = shape.addContour(); return false;
bool contourStart = true; }
Point2 startPoint; static void consumeWhitespace(const char *&pathDef) {
Point2 controlPoint[2]; while (*pathDef == ' ' || *pathDef == '\t' || *pathDef == '\r' || *pathDef == '\n')
Point2 node; ++pathDef;
}
while (true) {
switch (nodeType) { static void consumeOptionalComma(const char *&pathDef) {
case 'M': case 'm': consumeWhitespace(pathDef);
REQUIRE(contourStart); if (*pathDef == ',')
REQUIRE(readCoord(node, pathDef)); ++pathDef;
if (nodeType == 'm') }
node += prevNode;
startPoint = node; static double arcAngle(Vector2 u, Vector2 v) {
--nodeType; // to 'L' or 'l' return nonZeroSign(crossProduct(u, v))*acos(clamp(dotProduct(u, v)/(u.length()*v.length()), -1., +1.));
break; }
case 'Z': case 'z':
if (prevNode != startPoint) static Vector2 rotateVector(Vector2 v, Vector2 direction) {
contour.addEdge(new LinearSegment(prevNode, startPoint)); return Vector2(direction.x*v.x-direction.y*v.y, direction.y*v.x+direction.x*v.y);
prevNode = startPoint; }
goto NEXT_CONTOUR;
case 'L': case 'l': static void addArcApproximate(Contour &contour, Point2 startPoint, Point2 endPoint, Vector2 radius, double rotation, bool largeArc, bool sweep) {
REQUIRE(readCoord(node, pathDef)); if (endPoint == startPoint)
if (nodeType == 'l') return;
node += prevNode; if (radius.x == 0 || radius.y == 0)
contour.addEdge(new LinearSegment(prevNode, node)); return contour.addEdge(new LinearSegment(startPoint, endPoint));
break;
case 'H': case 'h': radius.x = fabs(radius.x);
REQUIRE(readDouble(node.x, pathDef)); radius.y = fabs(radius.y);
if (nodeType == 'h') Vector2 axis(cos(rotation), sin(rotation));
node.x += prevNode.x;
contour.addEdge(new LinearSegment(prevNode, node)); Vector2 rm = rotateVector(.5*(startPoint-endPoint), Vector2(axis.x, -axis.y));
break; Vector2 rm2 = rm*rm;
case 'V': case 'v': Vector2 radius2 = radius*radius;
REQUIRE(readDouble(node.y, pathDef)); double radiusGap = rm2.x/radius2.x+rm2.y/radius2.y;
if (nodeType == 'v') if (radiusGap > 1) {
node.y += prevNode.y; radius *= sqrt(radiusGap);
contour.addEdge(new LinearSegment(prevNode, node)); radius2 = radius*radius;
break; }
case 'Q': case 'q': double dq = (radius2.x*rm2.y+radius2.y*rm2.x);
REQUIRE(readCoord(controlPoint[0], pathDef)); double pq = radius2.x*radius2.y/dq-1;
consumeOptionalComma(pathDef); double q = (largeArc == sweep ? -1 : +1)*sqrt(max(pq, 0.));
REQUIRE(readCoord(node, pathDef)); Vector2 rc(q*radius.x*rm.y/radius.y, -q*radius.y*rm.x/radius.x);
if (nodeType == 'q') { Point2 center = .5*(startPoint+endPoint)+rotateVector(rc, axis);
controlPoint[0] += prevNode;
node += prevNode; double angleStart = arcAngle(Vector2(1, 0), (rm-rc)/radius);
} double angleExtent = arcAngle((rm-rc)/radius, (-rm-rc)/radius);
contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node)); if (!sweep && angleExtent > 0)
break; angleExtent -= 2*M_PI;
// TODO T, t else if (sweep && angleExtent < 0)
case 'C': case 'c': angleExtent += 2*M_PI;
REQUIRE(readCoord(controlPoint[0], pathDef));
consumeOptionalComma(pathDef); int segments = (int) ceil(ARC_SEGMENTS_PER_PI/M_PI*fabs(angleExtent));
REQUIRE(readCoord(controlPoint[1], pathDef)); double angleIncrement = angleExtent/segments;
consumeOptionalComma(pathDef); double cl = 4/3.*sin(.5*angleIncrement)/(1+cos(.5*angleIncrement));
REQUIRE(readCoord(node, pathDef));
if (nodeType == 'c') { Point2 prevNode = startPoint;
controlPoint[0] += prevNode; double angle = angleStart;
controlPoint[1] += prevNode; for (int i = 0; i < segments; ++i) {
node += prevNode; Point2 controlPoint[2];
} Vector2 d(cos(angle), sin(angle));
contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node)); controlPoint[0] = center+rotateVector(Vector2(d.x-cl*d.y, d.y+cl*d.x)*radius, axis);
break; angle += angleIncrement;
case 'S': case 's': d.set(cos(angle), sin(angle));
controlPoint[0] = node+node-controlPoint[1]; controlPoint[1] = center+rotateVector(Vector2(d.x+cl*d.y, d.y-cl*d.x)*radius, axis);
REQUIRE(readCoord(controlPoint[1], pathDef)); Point2 node = i == segments-1 ? endPoint : center+rotateVector(d*radius, axis);
consumeOptionalComma(pathDef); contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
REQUIRE(readCoord(node, pathDef)); prevNode = node;
if (nodeType == 's') { }
controlPoint[1] += prevNode; }
node += prevNode;
} static bool buildFromPath(Shape &shape, const char *pathDef, double size) {
contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node)); char nodeType;
break; Point2 prevNode(0, 0);
// TODO A, a bool nodeTypePreread = false;
default: while (nodeTypePreread || readNodeType(nodeType, pathDef)) {
REQUIRE(false); nodeTypePreread = false;
} Contour &contour = shape.addContour();
contourStart &= nodeType == 'M' || nodeType == 'm'; bool contourStart = true;
prevNode = node;
readNodeType(nodeType, pathDef); Point2 startPoint;
} Point2 controlPoint[2];
NEXT_CONTOUR:; Point2 node;
}
return true; while (*pathDef) {
} switch (nodeType) {
case 'M': case 'm':
bool loadSvgShape(Shape &output, const char *filename, Vector2 *dimensions) { if (!contourStart) {
tinyxml2::XMLDocument doc; nodeTypePreread = true;
if (doc.LoadFile(filename)) goto NEXT_CONTOUR;
return false; }
tinyxml2::XMLElement *root = doc.FirstChildElement("svg"); REQUIRE(readCoord(node, pathDef));
if (!root) if (nodeType == 'm')
return false; node += prevNode;
startPoint = node;
tinyxml2::XMLElement *path = root->FirstChildElement("path"); --nodeType; // to 'L' or 'l'
if (!path) { break;
tinyxml2::XMLElement *g = root->FirstChildElement("g"); case 'Z': case 'z':
if (g) REQUIRE(!contourStart);
path = g->FirstChildElement("path"); goto NEXT_CONTOUR;
} case 'L': case 'l':
if (!path) REQUIRE(readCoord(node, pathDef));
return false; if (nodeType == 'l')
const char *pd = path->Attribute("d"); node += prevNode;
if (!pd) contour.addEdge(new LinearSegment(prevNode, node));
return false; break;
case 'H': case 'h':
output.contours.clear(); REQUIRE(readDouble(node.x, pathDef));
output.inverseYAxis = true; if (nodeType == 'h')
if (dimensions) { node.x += prevNode.x;
dimensions->x = root->DoubleAttribute("width"); contour.addEdge(new LinearSegment(prevNode, node));
dimensions->y = root->DoubleAttribute("height"); break;
} case 'V': case 'v':
return buildFromPath(output, pd); REQUIRE(readDouble(node.y, pathDef));
} if (nodeType == 'v')
node.y += prevNode.y;
} contour.addEdge(new LinearSegment(prevNode, node));
break;
case 'Q': case 'q':
REQUIRE(readCoord(controlPoint[0], pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readCoord(node, pathDef));
if (nodeType == 'q') {
controlPoint[0] += prevNode;
node += prevNode;
}
contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
break;
case 'T': case 't':
controlPoint[0] = node+node-controlPoint[0];
REQUIRE(readCoord(node, pathDef));
if (nodeType == 't')
node += prevNode;
contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
break;
case 'C': case 'c':
REQUIRE(readCoord(controlPoint[0], pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readCoord(controlPoint[1], pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readCoord(node, pathDef));
if (nodeType == 'c') {
controlPoint[0] += prevNode;
controlPoint[1] += prevNode;
node += prevNode;
}
contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
break;
case 'S': case 's':
controlPoint[0] = node+node-controlPoint[1];
REQUIRE(readCoord(controlPoint[1], pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readCoord(node, pathDef));
if (nodeType == 's') {
controlPoint[1] += prevNode;
node += prevNode;
}
contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
break;
case 'A': case 'a':
{
Vector2 radius;
double angle;
bool largeArg;
bool sweep;
REQUIRE(readCoord(radius, pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readDouble(angle, pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readBool(largeArg, pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readBool(sweep, pathDef));
consumeOptionalComma(pathDef);
REQUIRE(readCoord(node, pathDef));
if (nodeType == 'a')
node += prevNode;
angle *= M_PI/180.0;
addArcApproximate(contour, prevNode, node, radius, angle, largeArg, sweep);
}
break;
default:
REQUIRE(!"Unknown node type");
}
contourStart &= nodeType == 'M' || nodeType == 'm';
prevNode = node;
readNodeType(nodeType, pathDef);
consumeWhitespace(pathDef);
}
NEXT_CONTOUR:
// Fix contour if it isn't properly closed
if (!contour.edges.empty() && prevNode != startPoint) {
if ((contour.edges[contour.edges.size()-1]->point(1)-contour.edges[0]->point(0)).length() < ENDPOINT_SNAP_RANGE_PROPORTION*size)
contour.edges[contour.edges.size()-1]->moveEndPoint(contour.edges[0]->point(0));
else
contour.addEdge(new LinearSegment(prevNode, startPoint));
}
prevNode = startPoint;
}
return true;
}
bool loadSvgShape(Shape &output, const char *filename, int pathIndex, Vector2 *dimensions) {
tinyxml2::XMLDocument doc;
if (doc.LoadFile(filename))
return false;
tinyxml2::XMLElement *root = doc.FirstChildElement("svg");
if (!root)
return false;
tinyxml2::XMLElement *path = NULL;
if (pathIndex > 0) {
path = root->FirstChildElement("path");
if (!path) {
tinyxml2::XMLElement *g = root->FirstChildElement("g");
if (g)
path = g->FirstChildElement("path");
}
while (path && --pathIndex > 0)
path = path->NextSiblingElement("path");
} else {
path = root->LastChildElement("path");
if (!path) {
tinyxml2::XMLElement *g = root->LastChildElement("g");
if (g)
path = g->LastChildElement("path");
}
while (path && ++pathIndex < 0)
path = path->PreviousSiblingElement("path");
}
if (!path)
return false;
const char *pd = path->Attribute("d");
if (!pd)
return false;
output.contours.clear();
output.inverseYAxis = true;
Vector2 dims(root->DoubleAttribute("width"), root->DoubleAttribute("height"));
if (!dims) {
double left, top;
const char *viewBox = root->Attribute("viewBox");
if (viewBox)
sscanf(viewBox, "%lf %lf %lf %lf", &left, &top, &dims.x, &dims.y);
}
if (dimensions)
*dimensions = dims;
return buildFromPath(output, pd, dims.length());
}
}

View File

@ -7,6 +7,6 @@
namespace msdfgen { namespace msdfgen {
/// Reads the first path found in the specified SVG file and stores it as a Shape in output. /// Reads the first path found in the specified SVG file and stores it as a Shape in output.
bool loadSvgShape(Shape &output, const char *filename, Vector2 *dimensions = NULL); bool loadSvgShape(Shape &output, const char *filename, int pathIndex = 0, Vector2 *dimensions = NULL);
} }

View File

@ -281,7 +281,7 @@ static const char *helpText =
" -stdin\n" " -stdin\n"
"\tReads text shape description from the standard input.\n" "\tReads text shape description from the standard input.\n"
" -svg <filename.svg>\n" " -svg <filename.svg>\n"
"\tLoads the first vector path encountered in the specified SVG file.\n" "\tLoads the last vector path found in the specified SVG file.\n"
"\n" "\n"
"OPTIONS\n" "OPTIONS\n"
" -angle <angle>\n" " -angle <angle>\n"
@ -359,6 +359,7 @@ int main(int argc, const char * const *argv) {
const char *testRenderMulti = NULL; const char *testRenderMulti = NULL;
bool outputSpecified = false; bool outputSpecified = false;
int unicode = 0; int unicode = 0;
int svgPathIndex = 0;
int width = 64, height = 64; int width = 64, height = 64;
int testWidth = 0, testHeight = 0; int testWidth = 0, testHeight = 0;
@ -618,7 +619,7 @@ int main(int argc, const char * const *argv) {
Shape shape; Shape shape;
switch (inputType) { switch (inputType) {
case SVG: { case SVG: {
if (!loadSvgShape(shape, input, &svgDims)) if (!loadSvgShape(shape, input, svgPathIndex, &svgDims))
ABORT("Failed to load shape from SVG file."); ABORT("Failed to load shape from SVG file.");
break; break;
} }