You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

254 lines
7.9KB

  1. #include <svg.hpp>
  2. #include <map>
  3. #include <math.hpp>
  4. #include <string.hpp>
  5. // #define DEBUG_ONLY(x) x
  6. #define DEBUG_ONLY(x)
  7. namespace rack {
  8. Svg::~Svg() {
  9. if (handle)
  10. nsvgDelete(handle);
  11. }
  12. void Svg::loadFile(const std::string& filename) {
  13. handle = nsvgParseFromFile(filename.c_str(), "px", SVG_DPI);
  14. if (!handle)
  15. throw Exception("Failed to load SVG %s", filename.c_str());
  16. INFO("Loaded SVG %s", filename.c_str());
  17. }
  18. void Svg::loadString(const std::string& str) {
  19. // nsvgParse modifies the input string
  20. std::string strCopy = str;
  21. handle = nsvgParse(&strCopy[0], "px", SVG_DPI);
  22. std::string strEllip = string::ellipsize(str, 40);
  23. if (!handle)
  24. throw Exception("Failed to load SVG \"%s\"", strEllip.c_str());
  25. INFO("Loaded SVG \"%s\"", strEllip.c_str());
  26. }
  27. void Svg::draw(NVGcontext* vg) {
  28. svgDraw(vg, handle);
  29. }
  30. static std::map<std::string, std::shared_ptr<Svg>> svgCache;
  31. std::shared_ptr<Svg> Svg::load(const std::string& filename) {
  32. const auto& pair = svgCache.find(filename);
  33. if (pair != svgCache.end())
  34. return pair->second;
  35. // Load svg
  36. std::shared_ptr<Svg> svg;
  37. try {
  38. svg = std::make_shared<Svg>();
  39. svg->loadFile(filename);
  40. }
  41. catch (Exception& e) {
  42. WARN("%s", e.what());
  43. svg = NULL;
  44. }
  45. svgCache[filename] = svg;
  46. return svg;
  47. }
  48. static NVGcolor getNVGColor(uint32_t color) {
  49. return nvgRGBA(
  50. (color >> 0) & 0xff,
  51. (color >> 8) & 0xff,
  52. (color >> 16) & 0xff,
  53. (color >> 24) & 0xff);
  54. }
  55. static NVGpaint getPaint(NVGcontext* vg, NSVGpaint* p) {
  56. assert(p->type == NSVG_PAINT_LINEAR_GRADIENT || p->type == NSVG_PAINT_RADIAL_GRADIENT);
  57. NSVGgradient* g = p->gradient;
  58. assert(g->nstops >= 1);
  59. NVGcolor icol = getNVGColor(g->stops[0].color);
  60. NVGcolor ocol = getNVGColor(g->stops[g->nstops - 1].color);
  61. float inverse[6];
  62. nvgTransformInverse(inverse, g->xform);
  63. DEBUG_ONLY(printf(" inverse: %f %f %f %f %f %f\n", inverse[0], inverse[1], inverse[2], inverse[3], inverse[4], inverse[5]);)
  64. math::Vec s, e;
  65. DEBUG_ONLY(printf(" sx: %f sy: %f ex: %f ey: %f\n", s.x, s.y, e.x, e.y);)
  66. // Is it always the case that the gradient should be transformed from (0, 0) to (0, 1)?
  67. nvgTransformPoint(&s.x, &s.y, inverse, 0, 0);
  68. nvgTransformPoint(&e.x, &e.y, inverse, 0, 1);
  69. DEBUG_ONLY(printf(" sx: %f sy: %f ex: %f ey: %f\n", s.x, s.y, e.x, e.y);)
  70. NVGpaint paint;
  71. if (p->type == NSVG_PAINT_LINEAR_GRADIENT)
  72. paint = nvgLinearGradient(vg, s.x, s.y, e.x, e.y, icol, ocol);
  73. else
  74. paint = nvgRadialGradient(vg, s.x, s.y, 0.0, 160, icol, ocol);
  75. return paint;
  76. }
  77. /** Returns the parameterized value of the line p2--p3 where it intersects with p0--p1 */
  78. static float getLineCrossing(math::Vec p0, math::Vec p1, math::Vec p2, math::Vec p3) {
  79. math::Vec b = p2.minus(p0);
  80. math::Vec d = p1.minus(p0);
  81. math::Vec e = p3.minus(p2);
  82. float m = d.x * e.y - d.y * e.x;
  83. // Check if lines are parallel, or if either pair of points are equal
  84. if (std::abs(m) < 1e-6)
  85. return NAN;
  86. return -(d.x * b.y - d.y * b.x) / m;
  87. }
  88. void svgDraw(NVGcontext* vg, NSVGimage* svg) {
  89. DEBUG_ONLY(printf("new image: %g x %g px\n", svg->width, svg->height);)
  90. int shapeIndex = 0;
  91. // Iterate shape linked list
  92. for (NSVGshape* shape = svg->shapes; shape; shape = shape->next, shapeIndex++) {
  93. DEBUG_ONLY(printf(" new shape: %d id \"%s\", fillrule %d, from (%f, %f) to (%f, %f)\n", shapeIndex, shape->id, shape->fillRule, shape->bounds[0], shape->bounds[1], shape->bounds[2], shape->bounds[3]);)
  94. // Visibility
  95. if (!(shape->flags & NSVG_FLAGS_VISIBLE))
  96. continue;
  97. nvgSave(vg);
  98. // Opacity
  99. if (shape->opacity < 1.0)
  100. nvgGlobalAlpha(vg, shape->opacity);
  101. // Build path
  102. nvgBeginPath(vg);
  103. // Iterate path linked list
  104. for (NSVGpath* path = shape->paths; path; path = path->next) {
  105. DEBUG_ONLY(printf(" new path: %d points, %s, from (%f, %f) to (%f, %f)\n", path->npts, path->closed ? "closed" : "open", path->bounds[0], path->bounds[1], path->bounds[2], path->bounds[3]);)
  106. nvgMoveTo(vg, path->pts[0], path->pts[1]);
  107. for (int i = 1; i < path->npts; i += 3) {
  108. float* p = &path->pts[2 * i];
  109. nvgBezierTo(vg, p[0], p[1], p[2], p[3], p[4], p[5]);
  110. // nvgLineTo(vg, p[4], p[5]);
  111. DEBUG_ONLY(printf(" bezier (%f, %f) to (%f, %f)\n", p[-2], p[-1], p[4], p[5]);)
  112. }
  113. // Close path
  114. if (path->closed)
  115. nvgClosePath(vg);
  116. // Compute whether this is a hole or a solid.
  117. // Assume that no paths are crossing (usually true for normal SVG graphics).
  118. // Also assume that the topology is the same if we use straight lines rather than Beziers (not always the case but usually true).
  119. // Using the even-odd fill rule, if we draw a line from a point on the path to a point outside the boundary (e.g. top left) and count the number of times it crosses another path, the parity of this count determines whether the path is a hole (odd) or solid (even).
  120. int crossings = 0;
  121. math::Vec p0 = math::Vec(path->pts[0], path->pts[1]);
  122. math::Vec p1 = math::Vec(path->bounds[0] - 1.0, path->bounds[1] - 1.0);
  123. // Iterate all other paths
  124. for (NSVGpath* path2 = shape->paths; path2; path2 = path2->next) {
  125. if (path2 == path)
  126. continue;
  127. // Iterate all lines on the path
  128. if (path2->npts < 4)
  129. continue;
  130. for (int i = 1; i < path2->npts + 3; i += 3) {
  131. float* p = &path2->pts[2 * i];
  132. // The previous point
  133. math::Vec p2 = math::Vec(p[-2], p[-1]);
  134. // The current point
  135. math::Vec p3 = (i < path2->npts) ? math::Vec(p[4], p[5]) : math::Vec(path2->pts[0], path2->pts[1]);
  136. float crossing = getLineCrossing(p0, p1, p2, p3);
  137. float crossing2 = getLineCrossing(p2, p3, p0, p1);
  138. if (0.0 <= crossing && crossing < 1.0 && 0.0 <= crossing2) {
  139. crossings++;
  140. }
  141. }
  142. }
  143. if (crossings % 2 == 0)
  144. nvgPathWinding(vg, NVG_SOLID);
  145. else
  146. nvgPathWinding(vg, NVG_HOLE);
  147. /*
  148. // Shoelace algorithm for computing the area, and thus the winding direction
  149. float area = 0.0;
  150. math::Vec p0 = math::Vec(path->pts[0], path->pts[1]);
  151. for (int i = 1; i < path->npts; i += 3) {
  152. float *p = &path->pts[2*i];
  153. math::Vec p1 = (i < path->npts) ? math::Vec(p[4], p[5]) : math::Vec(path->pts[0], path->pts[1]);
  154. area += 0.5 * (p1.x - p0.x) * (p1.y + p0.y);
  155. printf("%f %f, %f %f\n", p0.x, p0.y, p1.x, p1.y);
  156. p0 = p1;
  157. }
  158. printf("%f\n", area);
  159. if (area < 0.0)
  160. nvgPathWinding(vg, NVG_CCW);
  161. else
  162. nvgPathWinding(vg, NVG_CW);
  163. */
  164. }
  165. // Fill shape
  166. if (shape->fill.type) {
  167. switch (shape->fill.type) {
  168. case NSVG_PAINT_COLOR: {
  169. NVGcolor color = getNVGColor(shape->fill.color);
  170. nvgFillColor(vg, color);
  171. DEBUG_ONLY(printf(" fill color (%g, %g, %g, %g)\n", color.r, color.g, color.b, color.a);)
  172. } break;
  173. case NSVG_PAINT_LINEAR_GRADIENT:
  174. case NSVG_PAINT_RADIAL_GRADIENT: {
  175. NSVGgradient* g = shape->fill.gradient;
  176. (void)g;
  177. DEBUG_ONLY(printf(" gradient: type: %s xform: %f %f %f %f %f %f spread: %d fx: %f fy: %f nstops: %d\n", (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT ? "linear" : "radial"), g->xform[0], g->xform[1], g->xform[2], g->xform[3], g->xform[4], g->xform[5], g->spread, g->fx, g->fy, g->nstops);)
  178. for (int i = 0; i < g->nstops; i++) {
  179. DEBUG_ONLY(printf(" stop: #%08x\t%f\n", g->stops[i].color, g->stops[i].offset);)
  180. }
  181. nvgFillPaint(vg, getPaint(vg, &shape->fill));
  182. } break;
  183. }
  184. nvgFill(vg);
  185. }
  186. // Stroke shape
  187. if (shape->stroke.type) {
  188. nvgStrokeWidth(vg, shape->strokeWidth);
  189. // strokeDashOffset, strokeDashArray, strokeDashCount not yet supported
  190. nvgLineCap(vg, (NVGlineCap) shape->strokeLineCap);
  191. nvgLineJoin(vg, (int) shape->strokeLineJoin);
  192. switch (shape->stroke.type) {
  193. case NSVG_PAINT_COLOR: {
  194. NVGcolor color = getNVGColor(shape->stroke.color);
  195. nvgStrokeColor(vg, color);
  196. DEBUG_ONLY(printf(" stroke color (%g, %g, %g, %g)\n", color.r, color.g, color.b, color.a);)
  197. } break;
  198. case NSVG_PAINT_LINEAR_GRADIENT: {
  199. // NSVGgradient *g = shape->stroke.gradient;
  200. // printf(" lin grad: %f\t%f\n", g->fx, g->fy);
  201. } break;
  202. }
  203. nvgStroke(vg);
  204. }
  205. nvgRestore(vg);
  206. }
  207. DEBUG_ONLY(printf("\n");)
  208. }
  209. } // namespace rack