Skip to content

Commit

Permalink
Endpoint for drawing full SVG docs
Browse files Browse the repository at this point in the history
  • Loading branch information
andybak committed Apr 21, 2024
1 parent 28cfff8 commit 6e57852
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions Assets/Scripts/API/ApiMethods.DrawStrokes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using Newtonsoft.Json;
using UnityEngine;

Expand Down Expand Up @@ -161,8 +163,66 @@ public static void OpenTypeText(string text, string fontPath)
DrawStrokes.DrawNestedTrList(paths, tr, colors);
}

private static bool IsFullSvgDocument(string input)
{
using (XmlReader reader = XmlReader.Create(new StringReader(input)))
{
try
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("svg", StringComparison.OrdinalIgnoreCase))
{
return true; // Found the <svg> element
}
// Break early if not the expected start elements to avoid parsing entire document
if (reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("xml", StringComparison.OrdinalIgnoreCase))
{
break;
}
}
}
catch (XmlException)
{
// Handle case where input is not well-formed XML
return false;
}
}
return false; // No <svg> element found at the beginning of the document
}


[ApiEndpoint(
"draw.svg",
"Draws an entire SVG document"
)]
public static void Svg(string svg)
{
// SVG paths are usually scaled rather large so scale down 100x
float scale = 100f;
var tr = TrTransform.TRS(ApiManager.Instance.BrushPosition, Quaternion.identity, 1f / scale);
List<List<TrTransform>> paths;
List<Color> colors;

if (!IsFullSvgDocument(svg))
{
// For backwards compatibility, also support SVG path strings
SvgPath(svg);
return;
}

(paths, colors) = DrawStrokes.SvgDocumentToNestedPaths(svg);
DrawStrokes.DrawNestedTrList(
paths,
tr,
colors: colors,
brushScale: scale,
smoothing: ApiManager.Instance.PathSmoothing
);
}

[ApiEndpoint(
"draw.svg.path",
"Draws the path supplied as an SVG Path string at the current brush position",
"M 184,199 116,170 53,209.6 60,136.2 4.3,88"
)]
Expand Down

0 comments on commit 6e57852

Please sign in to comment.