FileImporter.cs 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685
  1. using System;
  2. using System.Collections.Generic;
  3. //using System.Drawing;
  4. using System.Globalization;
  5. using System.Windows;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. namespace SketchAssistantWPF
  11. {
  12. public class FileImporter
  13. {
  14. /// <summary>
  15. /// scale factor for coordinates of svg file
  16. /// </summary>
  17. double scale;
  18. /// <summary>
  19. /// line pointer for the current svg document
  20. /// </summary>
  21. int i;
  22. /// <summary>
  23. /// array containing all characters interpreted as whitespaces which seperate words/tokens in the input file
  24. /// </summary>
  25. readonly char[] whitespaces = new char[] { ' ' , ',' };
  26. /// <summary>
  27. /// number of points to create along the outline of an ellipse, divisible by 4
  28. /// </summary>
  29. readonly int samplingRateEllipse = 12;
  30. /// <summary>
  31. /// number of points to create on a bezier curve, including start and end point (even number will result in "flat" bezier curves, uneven number in "pointed" ones)
  32. /// </summary>
  33. readonly int samplingRateBezier = 101;
  34. /// <summary>
  35. /// parses a drawing consisting of line objects, given as a file in the application specific .isad format
  36. /// </summary>
  37. /// <param name="fileName">the path of the input file</param>
  38. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  39. public Tuple<int, int, List<InternalLine>> ParseISADInputFile(String fileName)
  40. {
  41. return ParseISADInput(System.IO.File.ReadAllLines(fileName));
  42. }
  43. /// <summary>
  44. /// parses a drawing consisting of line objects, given as the content of a .isad file, seperated into lines
  45. /// </summary>
  46. /// <param name="allLines">an array holding all lines of the input file</param>
  47. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  48. private Tuple<int, int, List<InternalLine>> ParseISADInput(String[] allLines)
  49. {
  50. if (allLines.Length == 0)
  51. {
  52. throw new FileImporterException("file is empty", "", -1);
  53. }
  54. if (!"drawing".Equals(allLines[0]))
  55. {
  56. throw new FileImporterException("file is not an interactive sketch assistant drawing", ".isad files have to start with the 'drawing' token", 1);
  57. }
  58. if (!"enddrawing".Equals(allLines[allLines.Length - 1]))
  59. {
  60. throw new FileImporterException("unterminated drawing definition", ".isad files have to end with the 'enddrawing' token", allLines.Length);
  61. }
  62. Tuple<int, int> dimensions = ParseISADHeader(allLines);
  63. List<InternalLine> picture = ParseISADBody(allLines, dimensions.Item1, dimensions.Item2);
  64. return new Tuple<int, int, List<InternalLine>>(dimensions.Item1, dimensions.Item2, picture);
  65. }
  66. /// <summary>
  67. /// parses the first two lines of an input file in .isad format
  68. /// </summary>
  69. /// <param name="allLines">the input file as an array of lines</param>
  70. /// <returns>the width and height of the left canvas</returns>
  71. private Tuple<int, int> ParseISADHeader(String[] allLines)
  72. {
  73. int width;
  74. int height;
  75. if (!(allLines.Length > 1) || !Regex.Match(allLines[1], @"^\d+x?\d+$", RegexOptions.None).Success)
  76. {
  77. throw new FileImporterException("invalid or missing canvas size definition", "format: [width]x[heigth]", 2);
  78. }
  79. String[] size = allLines[1].Split('x');
  80. width = Convert.ToInt32(size[0]);
  81. height = Convert.ToInt32(size[1]);
  82. return new Tuple<int, int>(width, height);
  83. }
  84. /// <summary>
  85. /// parses all line entries of an input file in .isad format
  86. /// </summary>
  87. /// <param name="allLines">the input file as an array of lines</param>
  88. /// <returns>the parsed picture as a list of lines</returns>
  89. private List<InternalLine> ParseISADBody(String[] allLines, int width, int height)
  90. {
  91. String lineStartString = "line";
  92. String lineEndString = "endline";
  93. List<InternalLine> drawing = new List<InternalLine>();
  94. //number of the line currently being parsed, enumeration starting at 0, body starts at the third line, therefore lin number 2
  95. int i = 2;
  96. //parse 'line' token and complete line definition
  97. int lineStartPointer = i;
  98. //holds the line number of the next expected beginning of a line definition, or of the enddrawing token
  99. while (lineStartString.Equals(allLines[i]))
  100. {
  101. //start parsing next line
  102. i++;
  103. List<Point> newLine = new List<Point>();
  104. while (!lineEndString.Equals(allLines[i]))
  105. {
  106. if (i == allLines.Length)
  107. {
  108. throw new FileImporterException("unterminated line definition", null, (i + 1));
  109. }
  110. //parse single point definition
  111. if (!Regex.Match(allLines[i], @"^\d+;\d+$", RegexOptions.None).Success)
  112. {
  113. throw new FileImporterException("invalid Point definition: wrong format", "format: [xCoordinate];[yCoordinate]", (i + 1));
  114. }
  115. String[] coordinates = allLines[i].Split(';');
  116. //no errors possible, convertability to int already checked above
  117. int xCoordinate = Convert.ToInt32(coordinates[0]);
  118. int yCoordinate = Convert.ToInt32(coordinates[1]);
  119. if (xCoordinate < 0 || yCoordinate < 0 || xCoordinate > width - 1 || yCoordinate > height - 1)
  120. {
  121. throw new FileImporterException("invalid Point definition: point out of bounds", null, (i + 1));
  122. }
  123. newLine.Add(new Point(xCoordinate, yCoordinate));
  124. //start parsing next line
  125. i++;
  126. }
  127. //"parse" 'endline' token, syntax already checked at the beginning, and start parsing next line
  128. i++;
  129. //add line to drawing
  130. drawing.Add(new InternalLine(newLine));
  131. //update lineStartPointer to the presumable start of the next line
  132. lineStartPointer = i;
  133. }
  134. //check if end of body is reached after there are no more line definitions
  135. if (i != allLines.Length - 1)
  136. {
  137. throw new FileImporterException("missing or invalid line definition token", "line definitions start with the 'line' token", (i + 1));
  138. }
  139. //return parsed picture
  140. return drawing;
  141. }
  142. /// <summary>
  143. /// connection point for testing use only: calls ParseISADInput(String[] allLines) and directly passes the given argument (effectively bypassing the File Input functionality)
  144. /// </summary>
  145. /// <param name="allLines">an array holding all lines of the input file</param>
  146. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  147. public Tuple<int, int, List<InternalLine>> ParseISADInputForTesting(String[] allLines)
  148. {
  149. return ParseISADInput(allLines);
  150. }
  151. /// <summary>
  152. /// parses a svg drawing, given as a .svg file
  153. /// <para />several severe restrictions to the svg standard apply:
  154. /// <para /> - width and heigth values must be integers
  155. /// <para /> - the supported svg elements to be drawn must be placed on top level directly inside the 'svg' tag
  156. /// <para /> - except for the global 'svg' tag, no hierarchical elements (elements which contain other svg elements) may exist. in other words: after an opening element tag no other opening element tag may occur before the closing tag of this element.
  157. /// <para /> - lines in front of the (single) opening and after the (single) closing global svg tag will be ignored during parsing
  158. /// <para /> - unsupported svg elements on top level will be ignored during parsing
  159. /// <para /> - the input file must not contain empty lines
  160. /// <para /> - all input files have to be manually tested and approved for use with this program by a developer or otherwise entitled personnel, otherwise no guarantee about correct and error-free parsing will be given
  161. /// </summary>
  162. /// <param name="fileName">the path of the input file</param>
  163. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  164. public Tuple<int, int, List<InternalLine>> ParseSVGInputFile(String fileName, int windowWidth, int windowHeight)
  165. {
  166. return ParseSVGInput(System.IO.File.ReadAllLines(fileName), windowWidth, windowHeight);
  167. }
  168. /// <summary>
  169. /// parses a svg drawing, given as the content of a .svg file, seperated into lines
  170. /// </summary>
  171. /// <param name="allLines">an array holding all lines of the input file</param>
  172. /// <returns>the width and height of the left canvas and the parsed picture as a list of lines</returns>
  173. private Tuple<int, int, List<InternalLine>> ParseSVGInput(String[] allLines, double windowWidth, double windowHeight)
  174. {
  175. i = 0; //reset line pointer
  176. if (allLines.Length == 0) //check for empty file
  177. {
  178. throw new FileImporterException("file is empty", "", -1);
  179. }
  180. var sizedef = ParseSVGHeader(allLines); //parse svg file header and get internal coordinate range
  181. i++;
  182. int width; //width of the resulting picture in pixels
  183. int height; //height of the resulting picture in pixels
  184. if(windowWidth != 0 && windowHeight != 0)
  185. {
  186. if (windowWidth / windowHeight > sizedef.Item1 / sizedef.Item2) //height dominant, width has to be smaller than drawing window to preserve xy-scale
  187. {
  188. scale = windowHeight / sizedef.Item2;
  189. height = (int)Math.Round(windowHeight);
  190. width = (int) Math.Round(scale * sizedef.Item1);
  191. }
  192. else //width dominant, height has to be smaller than drawing window to preserve xy-scale
  193. {
  194. scale = windowWidth / sizedef.Item1;
  195. width = (int)Math.Round(windowWidth);
  196. height = (int)Math.Round(scale * sizedef.Item2);
  197. }
  198. }
  199. else
  200. {
  201. scale = 1;
  202. width = sizedef.Item1;
  203. height = sizedef.Item2;
  204. }
  205. for (int j=0; j < allLines.Length; j++)
  206. {
  207. allLines[j] = allLines[j].Trim(whitespaces);
  208. }
  209. List<InternalLine> picture = ParseSVGBody(allLines); //parse whole svg drawing into list of lines
  210. return new Tuple<int, int, List<InternalLine>>(width, height, picture);
  211. }
  212. /// <summary>
  213. /// parses the svg file header and returns the internal coordinate range of this drawing, and iterates i to point to the start of svg element definitions
  214. /// </summary>
  215. /// <param name="allLines">an array holding all lines of the input file</param>
  216. /// <returns>the internal coordinate range of this drawing</returns>
  217. private Tuple<int, int> ParseSVGHeader(String[] allLines)
  218. {
  219. while (!allLines[i].StartsWith("<svg")) //skip non-relevant metadata at start of svg file
  220. {
  221. i++;
  222. }
  223. String[] currentLine = allLines[i].Split(' ');
  224. int width= -1;
  225. int height= -1;
  226. for(int j= 0; j < currentLine.Length; j++)
  227. {
  228. if (currentLine[j].StartsWith("width"))
  229. {
  230. width = Convert.ToInt32(ParseSingleSVGAttribute(currentLine[j]));
  231. }
  232. else if (currentLine[j].StartsWith("height"))
  233. {
  234. height = Convert.ToInt32(ParseSingleSVGAttribute(currentLine[j]));
  235. }
  236. }
  237. if(width == -1)
  238. {
  239. throw new FileImporterException("missing width definition in SVG header", "the header should contain the \"width=...\" attribute", i+1);
  240. }
  241. if (height == -1)
  242. {
  243. throw new FileImporterException("missing height definition in SVG header", "the header should contain the \"height=...\" attribute", i + 1);
  244. }
  245. return new Tuple<int, int>(width, height);
  246. }
  247. /// <summary>
  248. /// parses all relevant svg element definitions and skips the ones not representable by the sketch assistant
  249. /// </summary>
  250. /// <param name="allLines">an array holding all lines of the input file</param>
  251. /// <returns>the parsed picture as a list of lines</returns>
  252. private List<InternalLine> ParseSVGBody(String[] allLines)
  253. {
  254. List<InternalLine> picture = new List<InternalLine>();
  255. while (!allLines[i].StartsWith("</svg"))
  256. {
  257. List<InternalLine> element = ParseSingleSVGElement(allLines);
  258. if (element != null)
  259. {
  260. picture.AddRange(element);
  261. }
  262. i++;
  263. if (i > allLines.Length - 1) throw new FileImporterException("unterminated input file: missing </svg> tag", "the file must not contain empty lines", i + 1);
  264. }
  265. return picture;
  266. }
  267. /// <summary>
  268. /// parses one toplevel svg element
  269. /// </summary>
  270. /// <param name="allLines">an array holding all lines of the input file</param>
  271. /// <returns>the parsed Element as a list of lines</returns>
  272. private List<InternalLine> ParseSingleSVGElement(string[] allLines)
  273. {
  274. String[] currentElement = GetCurrentElement(allLines);
  275. return ParseSingleLineSVGElement(currentElement);
  276. }
  277. /// <summary>
  278. /// parses a single toplevel svg element only taking one line
  279. /// </summary>
  280. /// <param name="allLines">an array holding all lines of the input file</param>
  281. /// <returns>the parsed element as a Line object, or null if the element is not supported</returns>
  282. private List<InternalLine> ParseSingleLineSVGElement(string[] currentElement)
  283. {
  284. List<Point> points= null;
  285. List<InternalLine> element = null;
  286. switch (currentElement[0])
  287. {
  288. case "<rect":
  289. points = ParseRect(currentElement);
  290. break;
  291. case "<circle":
  292. points = ParseCircle(currentElement);
  293. break;
  294. case "<ellipse":
  295. points = ParseEllipse(currentElement);
  296. break;
  297. case "<line":
  298. points = ParseLine(currentElement);
  299. break;
  300. case "<polyline":
  301. points = ParsePolyline(currentElement);
  302. break;
  303. case "<polygon":
  304. points = ParsePolygon(currentElement);
  305. break;
  306. case "<path":
  307. element = ParsePath(currentElement);
  308. break;
  309. default: //unsupported svg element
  310. return null; //simply ignore
  311. }
  312. if (element == null)
  313. {
  314. element = new List<InternalLine>();
  315. element.Add(new InternalLine(points));
  316. }
  317. return element;
  318. }
  319. /// <summary>
  320. /// parses a rectangle definition into a List of Points representing a single line around the rectangle (in clockwise direction), ignoring rounded corners
  321. /// </summary>
  322. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  323. /// <returns>the parsed element as a List of Points</returns>
  324. private List<Point> ParseRect(string[] currentElement)
  325. {
  326. double x = 0;
  327. double y = 0;
  328. double w = 0;
  329. double h = 0;
  330. double rx = 0;
  331. double ry = 0;
  332. for(int j= 0; j < currentElement.Length; j++)
  333. {
  334. if (currentElement[j].StartsWith("x="))
  335. {
  336. x = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  337. }
  338. else if (currentElement[j].StartsWith("y="))
  339. {
  340. y = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  341. }
  342. else if (currentElement[j].StartsWith("width="))
  343. {
  344. w = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  345. }
  346. else if (currentElement[j].StartsWith("height="))
  347. {
  348. h = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  349. }
  350. else if (currentElement[j].StartsWith("rx="))
  351. {
  352. rx = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  353. }
  354. else if (currentElement[j].StartsWith("ry="))
  355. {
  356. ry = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  357. }
  358. }
  359. List<Point> rect = new List<Point>();
  360. rect.Add(ScaleAndCreatePoint(x, y));
  361. rect.Add(ScaleAndCreatePoint(x + w, y));
  362. rect.Add(ScaleAndCreatePoint(x + w, y + h));
  363. rect.Add(ScaleAndCreatePoint(x, y + h));
  364. rect.Add(ScaleAndCreatePoint(x, y));
  365. return rect;
  366. }
  367. /// <summary>
  368. /// parses a circle definition into a List of Points
  369. /// </summary>
  370. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  371. /// <returns>the parsed element as a List of Points</returns>
  372. private List<Point> ParseCircle(string[] currentElement)
  373. {
  374. double x = 0;
  375. double y = 0;
  376. double r = 0;
  377. for (int j = 0; j < currentElement.Length; j++)
  378. {
  379. if (currentElement[j].StartsWith("cx="))
  380. {
  381. x = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  382. }
  383. else if (currentElement[j].StartsWith("cy="))
  384. {
  385. y = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  386. }
  387. else if (currentElement[j].StartsWith("r="))
  388. {
  389. r = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  390. }
  391. }
  392. return SampleEllipse(x, y, r, r);
  393. }
  394. /// <summary>
  395. /// parses a ellipse definition into a List of Points
  396. /// </summary>
  397. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  398. /// <returns>the parsed element as a List of Points</returns>
  399. private List<Point> ParseEllipse(string[] currentElement)
  400. {
  401. double x = 0;
  402. double y = 0;
  403. double rx = 0;
  404. double ry = 0;
  405. for (int j = 0; j < currentElement.Length; j++)
  406. {
  407. if (currentElement[j].StartsWith("cx="))
  408. {
  409. x = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  410. }
  411. else if (currentElement[j].StartsWith("cy="))
  412. {
  413. y = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  414. }
  415. else if (currentElement[j].StartsWith("rx="))
  416. {
  417. rx = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  418. }
  419. else if (currentElement[j].StartsWith("ry="))
  420. {
  421. ry = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  422. }
  423. }
  424. return SampleEllipse(x, y, rx, ry);
  425. }
  426. /// <summary>
  427. /// parses a line definition into a List of two Points
  428. /// </summary>
  429. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  430. /// <returns>the parsed element as a List of Points</returns>
  431. private List<Point> ParseLine(string[] currentElement)
  432. {
  433. double x1 = 0;
  434. double y1 = 0;
  435. double x2 = 0;
  436. double y2 = 0;
  437. for (int j = 0; j < currentElement.Length; j++)
  438. {
  439. if (currentElement[j].StartsWith("x1="))
  440. {
  441. x1 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  442. }
  443. else if (currentElement[j].StartsWith("y1="))
  444. {
  445. y1 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  446. }
  447. else if (currentElement[j].StartsWith("x2="))
  448. {
  449. x2 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  450. }
  451. else if (currentElement[j].StartsWith("y2="))
  452. {
  453. y2 = Convert.ToDouble(ParseSingleSVGAttribute(currentElement[j]), CultureInfo.InvariantCulture);
  454. }
  455. }
  456. List<Point> line = new List<Point>();
  457. line.Add(ScaleAndCreatePoint(x1, y1));
  458. line.Add(ScaleAndCreatePoint(x2, y2));
  459. return line;
  460. }
  461. /// <summary>
  462. /// parses a polyline definition into a List of Points
  463. /// </summary>
  464. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  465. /// <returns>the parsed element as a List of Points</returns>
  466. private List<Point> ParsePolyline(string[] currentElement)
  467. {
  468. String[] points = null;
  469. for (int j = 0; j < currentElement.Length; j++)
  470. {
  471. if (currentElement[j].StartsWith("points="))
  472. {
  473. List<String> pointDefs = new List<string>();
  474. pointDefs.Add(currentElement[j].Substring(8)); //parse first point coordinates by removing 'points="'
  475. j++;
  476. while (!currentElement[j].EndsWith("\""))
  477. {
  478. pointDefs.Add(currentElement[j]); //parse intermediate point coordinates
  479. j++;
  480. }
  481. pointDefs.Add(currentElement[j].Trim('"')); //parse last point coordinates by removing '"'
  482. points = pointDefs.ToArray();
  483. }
  484. }
  485. List<Point> polyline = new List<Point>();
  486. for (int k = 0; k < points.Length - 1; k += 2)
  487. {
  488. polyline.Add(ScaleAndCreatePoint(Convert.ToDouble(points[k], CultureInfo.InvariantCulture), Convert.ToDouble(points[k + 1], CultureInfo.InvariantCulture)));
  489. }
  490. return polyline;
  491. }
  492. /// <summary>
  493. /// parses a polygon definition into a List of Points
  494. /// </summary>
  495. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  496. /// <returns>the parsed element as a List of Points</returns>
  497. private List<Point> ParsePolygon(string[] currentElement)
  498. {
  499. String[] points = null;
  500. for (int j = 0; j < currentElement.Length; j++)
  501. {
  502. if (currentElement[j].StartsWith("points="))
  503. {
  504. List<String> pointDefs = new List<string>();
  505. pointDefs.Add(currentElement[j].Substring(8)); //parse first point coordinates by removing 'points="'
  506. j++;
  507. while (!currentElement[j].EndsWith("\""))
  508. {
  509. pointDefs.Add(currentElement[j]); //parse intermediate point coordinates
  510. j++;
  511. }
  512. pointDefs.Add(currentElement[j].Trim('"')); //parse last point coordinates by removing '"'
  513. points = pointDefs.ToArray();
  514. }
  515. }
  516. List<Point> polygon = new List<Point>();
  517. for (int k = 0; k < points.Length - 1; k+=2)
  518. {
  519. polygon.Add(ScaleAndCreatePoint(Convert.ToDouble(points[k], CultureInfo.InvariantCulture), Convert.ToDouble(points[k+1], CultureInfo.InvariantCulture)));
  520. }
  521. polygon.Add(ScaleAndCreatePoint(Convert.ToDouble(points[0], CultureInfo.InvariantCulture), Convert.ToDouble(points[1], CultureInfo.InvariantCulture))); //close polygon
  522. return polygon;
  523. }
  524. /// <summary>
  525. /// parses a path definition into a List of Points
  526. /// </summary>
  527. /// <param name="currentElement">the definition of the element as whitespace seperated String[]</param>
  528. /// <returns>the parsed element as a List of Points</returns>
  529. private List<InternalLine> ParsePath(string[] currentElement)
  530. {
  531. List<String> pathElements = new List<string>();
  532. for (int j = 0; j < currentElement.Length; j++)
  533. {
  534. if (currentElement[j].StartsWith("d="))
  535. {
  536. pathElements.Add(currentElement[j].Substring(3)); //parse first path element by removing 'd="'
  537. j++;
  538. while (!currentElement[j].EndsWith("\""))
  539. {
  540. pathElements.Add(currentElement[j]); //parse intermediate path element
  541. j++;
  542. }
  543. pathElements.Add(currentElement[j].Trim('"')); //parse last path element by removing '"'
  544. }
  545. }
  546. NormalizePathDeclaration(pathElements); //expand path data to always explicitly have the command descriptor in front of the appropriate number of arguments and to seperate command descriptors, coordinates and other tokens always into seperate list elements (equivalent to seperation with spaces in the input file, but svg allows also for comma as a seperator, and for omitting seperators where possible without losing information (refer to svg grammer) to reduce file size
  547. List<InternalLine> element = new List<InternalLine>();
  548. List<Point> currentLine = new List<Point>();
  549. double lastBezierControlPointX= 0;
  550. double lastBezierControlPointY= 0;
  551. double lastPositionX;
  552. double lastPositionY;
  553. double initialPositionX= -1;
  554. double initialPositionY= -1;
  555. bool newSubpath = true;
  556. Tuple<List<Point>, double, double> valuesArc; //list of points, new values for: lastPositionX, lastPositionY
  557. Tuple<List<Point>, double, double, double, double> valuesBezierCurve; //list of points, new values for: lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY
  558. var valuesSinglePoint = Parse_M_L(pathElements); //new point, new values for: lastPositionX, lastPositionY
  559. currentLine = new List<Point>();
  560. currentLine.Add(valuesSinglePoint.Item1);
  561. lastPositionX = valuesSinglePoint.Item2;
  562. lastPositionY = valuesSinglePoint.Item3;
  563. String currentToken;
  564. while (!(pathElements.Count == 0)){
  565. if (newSubpath)
  566. {
  567. initialPositionX = lastPositionX; //update buffers for coordinates of first point of active subpath
  568. initialPositionY = lastPositionY;
  569. newSubpath = false;
  570. }
  571. currentToken = pathElements.First();
  572. if (currentToken.Equals("M"))
  573. {
  574. element.Add(new InternalLine(currentLine)); //save current line
  575. valuesSinglePoint = Parse_M_L(pathElements);
  576. currentLine = new List<Point>(); //create new empty line
  577. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  578. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  579. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  580. }
  581. else if (currentToken.Equals("m"))
  582. {
  583. element.Add(new InternalLine(currentLine)); //save current line
  584. valuesSinglePoint = Parse_m_l(pathElements, lastPositionX, lastPositionY);
  585. currentLine = new List<Point>(); //create new empty line
  586. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  587. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  588. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  589. }
  590. else if (currentToken.Equals("Z") || currentToken.Equals("z"))
  591. {
  592. valuesSinglePoint = Parse_Z(pathElements, initialPositionX, initialPositionY); //method call only used for uniform program structure... only real effect of method is to consume one token
  593. newSubpath = true;
  594. currentLine.Add(valuesSinglePoint.Item1); //add point to old line
  595. element.Add(new InternalLine(currentLine)); //save current line
  596. currentLine = new List<Point>(); //create new empty line
  597. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  598. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  599. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  600. }
  601. else if (currentToken.Equals("L"))
  602. {
  603. valuesSinglePoint = Parse_M_L(pathElements);
  604. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  605. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  606. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  607. }
  608. else if (currentToken.Equals("l"))
  609. {
  610. valuesSinglePoint = Parse_m_l(pathElements, lastPositionX, lastPositionY);
  611. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  612. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  613. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  614. }
  615. else if (currentToken.Equals("H"))
  616. {
  617. valuesSinglePoint = Parse_H(pathElements, lastPositionY);
  618. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  619. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  620. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  621. }
  622. else if (currentToken.Equals("h"))
  623. {
  624. valuesSinglePoint = Parse_h(pathElements, lastPositionX, lastPositionY);
  625. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  626. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  627. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  628. }
  629. else if (currentToken.Equals("V"))
  630. {
  631. valuesSinglePoint = Parse_V(pathElements, lastPositionX);
  632. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  633. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  634. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  635. }
  636. else if (currentToken.Equals("v"))
  637. {
  638. valuesSinglePoint = Parse_v(pathElements, lastPositionX, lastPositionY);
  639. currentLine.Add(valuesSinglePoint.Item1); //add point to new line
  640. lastPositionX = valuesSinglePoint.Item2; //save last point coordinates
  641. lastPositionY = valuesSinglePoint.Item3; //save last point coordinates
  642. }
  643. else if (currentToken.Equals("C"))
  644. {
  645. valuesBezierCurve = Parse_C(pathElements, lastPositionX, lastPositionY);
  646. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  647. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  648. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  649. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  650. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  651. }
  652. else if (currentToken.Equals("c"))
  653. {
  654. valuesBezierCurve = Parse_C(pathElements, lastPositionX, lastPositionY);
  655. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  656. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  657. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  658. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  659. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  660. }
  661. else if (currentToken.Equals("S"))
  662. {
  663. valuesBezierCurve = Parse_S(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  664. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  665. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  666. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  667. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  668. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  669. }
  670. else if (currentToken.Equals("s"))
  671. {
  672. valuesBezierCurve = Parse_s(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  673. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  674. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  675. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  676. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  677. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  678. }
  679. else if (currentToken.Equals("Q"))
  680. {
  681. valuesBezierCurve = Parse_Q(pathElements, lastPositionX, lastPositionY);
  682. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  683. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  684. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  685. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  686. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  687. }
  688. else if (currentToken.Equals("q"))
  689. {
  690. valuesBezierCurve = Parse_q(pathElements, lastPositionX, lastPositionY);
  691. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  692. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  693. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  694. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  695. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  696. }
  697. else if (currentToken.Equals("T"))
  698. {
  699. valuesBezierCurve = Parse_T(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  700. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  701. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  702. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  703. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  704. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  705. }
  706. else if (currentToken.Equals("t"))
  707. {
  708. valuesBezierCurve = Parse_t(pathElements, lastPositionX, lastPositionY, lastBezierControlPointX, lastBezierControlPointY);
  709. currentLine.AddRange(valuesBezierCurve.Item1); //add point to new line
  710. lastPositionX = valuesBezierCurve.Item2; //save last point coordinates
  711. lastPositionY = valuesBezierCurve.Item3; //save last point coordinates
  712. lastBezierControlPointX = valuesBezierCurve.Item4; //save last bezier control point coordinates
  713. lastBezierControlPointY = valuesBezierCurve.Item5; //save last bezier control point coordinates
  714. }
  715. else if (currentToken.Equals("A"))
  716. {
  717. valuesArc = Parse_A(pathElements, lastPositionX, lastPositionY);
  718. currentLine.AddRange(valuesArc.Item1); //add points to new line
  719. lastPositionX = valuesArc.Item2; //save last point coordinates
  720. lastPositionY = valuesArc.Item3; //save last point coordinates
  721. }
  722. else if (currentToken.Equals("a"))
  723. {
  724. valuesArc = Parse_a(pathElements, lastPositionX, lastPositionY);
  725. currentLine.AddRange(valuesArc.Item1); //add points to new line
  726. lastPositionX = valuesArc.Item2; //save last point coordinates
  727. lastPositionY = valuesArc.Item3; //save last point coordinates
  728. }
  729. else
  730. {
  731. throw new FileImporterException("invalid path argument or path data formatting: read argument " + pathElements.First(), "valid path arguments are: {M,Z,L,H,V,C,S,Q,T,A} in upper and lower case", i + 1);
  732. }
  733. }
  734. if (currentLine.Count > 1)
  735. {
  736. element.Add(new InternalLine(currentLine)); //save current line
  737. }
  738. return element;
  739. }
  740. /// <summary>
  741. /// normalizes the declaration of the data field of a path declaration by splitting coordinates still connected by a semicolon and command descriptors which are directly attached to the following coordinate into seperate tokens, also repeats omitted command descriptor tokens when the same command is repeated multiple times
  742. /// </summary>
  743. /// <param name="pathElements">the list of tokens to normalize, by splitting up existing tokens and adding new command descriptor tokens</param>
  744. private void NormalizePathDeclaration(List<string> pathElements)
  745. {
  746. Char lastCommand = 'M';
  747. int argumentCounter = 0;
  748. for( int j= 0; j < pathElements.Count; j++)
  749. {
  750. String currentElement = pathElements.ElementAt(j);
  751. if (currentElement.Length != 1)
  752. {
  753. if (((currentElement.First() >= 'A' && currentElement.First() <= 'Z') || (currentElement.First() >= 'a' && currentElement.First() <= 'z')) && currentElement.First() != 'e') //seperate a single command descriptor / letter
  754. {
  755. pathElements.RemoveAt(j);
  756. pathElements.Insert(j, currentElement.First() + ""); //insert letter as seperate element
  757. pathElements.Insert(j + 1, currentElement.Substring(1)); //insert rest of String at next position so it will be processed again
  758. lastCommand = currentElement.First();
  759. argumentCounter = 0;
  760. }
  761. else if ((currentElement.First() >= '0' && currentElement.First() <= '9') || currentElement.First() == '-' || currentElement.First() == '+' || currentElement.First() != 'e') //seperate a single coordinate / number
  762. {
  763. bool repeatCommandDescriptor = false;
  764. switch (lastCommand){ //check for reaching of next command with omitted command descriptor
  765. case 'M':
  766. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  767. break;
  768. case 'm':
  769. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  770. break;
  771. case 'L':
  772. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  773. break;
  774. case 'l':
  775. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  776. break;
  777. case 'V':
  778. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  779. break;
  780. case 'v':
  781. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  782. break;
  783. case 'H':
  784. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  785. break;
  786. case 'h':
  787. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  788. break;
  789. case 'C':
  790. if (argumentCounter >= 6) repeatCommandDescriptor = true;
  791. break;
  792. case 'c':
  793. if (argumentCounter >= 6) repeatCommandDescriptor = true;
  794. break;
  795. case 'S':
  796. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  797. break;
  798. case 's':
  799. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  800. break;
  801. case 'Q':
  802. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  803. break;
  804. case 'q':
  805. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  806. break;
  807. case 'T':
  808. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  809. break;
  810. case 't':
  811. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  812. break;
  813. case 'A':
  814. if (argumentCounter >= 7) repeatCommandDescriptor = true;
  815. break;
  816. case 'a':
  817. if (argumentCounter >= 7) repeatCommandDescriptor = true;
  818. break;
  819. }
  820. if (repeatCommandDescriptor)
  821. {
  822. pathElements.Insert(j, lastCommand + ""); //repeat command descriptor
  823. j++; //skip command descriptor (was put into active position in the list
  824. argumentCounter = 0; //reset argument counter
  825. }
  826. bool decimalPointEncountered = false;
  827. for (int k = 1; k < currentElement.Length; k++)
  828. {
  829. if (!decimalPointEncountered && currentElement.ElementAt(k) == '.') //allow up to one decimal point in numbers
  830. {
  831. decimalPointEncountered = true;
  832. }
  833. else if (!((currentElement.ElementAt(k) >= '0' && currentElement.ElementAt(k) <= '9') || currentElement.First() == '-' || currentElement.First() == '+' || currentElement.First() != 'e'))
  834. {
  835. pathElements.RemoveAt(j);
  836. pathElements.Insert(j, currentElement.Substring(0, k - 1)); //insert number as seperate element
  837. pathElements.Insert(j + 1, currentElement.Substring(k)); //insert rest of String at next position so it will be processed again
  838. break;
  839. }
  840. }
  841. argumentCounter++;
  842. }
  843. else //parse non-space seperators and skip other unsupported characters (the only other valid ones per svg standard would be weird tokens looking like format descriptors (e.g. '#xC'), these are unsopported and will likely cause an error or other inconsitencies during parsing)
  844. {
  845. for (int k = 1; k < currentElement.Length; k++)
  846. {
  847. if (((currentElement.ElementAt(k) >= '0' && currentElement.ElementAt(k) <= '9')) || currentElement.ElementAt(k) == '-' || currentElement.ElementAt(k) == '+' || (currentElement.ElementAt(k) >= 'A' && currentElement.ElementAt(k) <= 'Z') || (currentElement.ElementAt(k) >= 'a' && currentElement.ElementAt(k) <= 'z'))
  848. {
  849. pathElements.RemoveAt(j);
  850. pathElements.Insert(j + 1, currentElement.Substring(k)); //insert rest of String at next position so it will be processed again
  851. break;
  852. }
  853. }
  854. }
  855. }
  856. else
  857. {
  858. if ((currentElement.First() >= 'A' && currentElement.First() <= 'Z') || (currentElement.First() >= 'a' && currentElement.First() <= 'z')) //update lastCommand buffer when reading single letter
  859. {
  860. lastCommand = currentElement.First();
  861. argumentCounter = 0;
  862. }
  863. else if(!(currentElement.First() >= '0' && currentElement.First() <= '9')) //not a number
  864. {
  865. pathElements.RemoveAt(j); //remove element
  866. j--; //decrement index pointer so next element will not be skipped (indices of all folowing elements just decreased by 1)
  867. }
  868. else //a single digit number
  869. {
  870. bool repeatCommandDescriptor = false;
  871. switch (lastCommand)
  872. { //check for reaching of next command with omitted command descriptor
  873. case 'M':
  874. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  875. break;
  876. case 'm':
  877. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  878. break;
  879. case 'L':
  880. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  881. break;
  882. case 'l':
  883. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  884. break;
  885. case 'V':
  886. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  887. break;
  888. case 'v':
  889. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  890. break;
  891. case 'H':
  892. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  893. break;
  894. case 'h':
  895. if (argumentCounter >= 1) repeatCommandDescriptor = true;
  896. break;
  897. case 'C':
  898. if (argumentCounter >= 6) repeatCommandDescriptor = true;
  899. break;
  900. case 'c':
  901. if (argumentCounter >= 6) repeatCommandDescriptor = true;
  902. break;
  903. case 'S':
  904. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  905. break;
  906. case 's':
  907. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  908. break;
  909. case 'Q':
  910. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  911. break;
  912. case 'q':
  913. if (argumentCounter >= 4) repeatCommandDescriptor = true;
  914. break;
  915. case 'T':
  916. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  917. break;
  918. case 't':
  919. if (argumentCounter >= 2) repeatCommandDescriptor = true;
  920. break;
  921. case 'A':
  922. if (argumentCounter >= 7) repeatCommandDescriptor = true;
  923. break;
  924. case 'a':
  925. if (argumentCounter >= 7) repeatCommandDescriptor = true;
  926. break;
  927. }
  928. if (repeatCommandDescriptor)
  929. {
  930. pathElements.Insert(j, lastCommand + ""); //repeat command descriptor
  931. j++; //skip command descriptor (was put into active position in the list
  932. argumentCounter = 0; //reset argument counter
  933. }
  934. argumentCounter++;
  935. }
  936. }
  937. }
  938. }
  939. /// <summary>
  940. /// parses a "closeloop" path element
  941. /// </summary>
  942. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  943. /// <param name="initialPositionX">absolute x coordinate of the last initial point of this subpath</param>
  944. /// <param name="initialPositionY">absolute y coordinate of the last initial point of this subpath</param>
  945. /// <returns></returns>
  946. private Tuple<Point, double, double> Parse_Z(List<string> pathElements, double initialPositionX, double initialPositionY)
  947. {
  948. pathElements.RemoveAt(0); //remove element descriptor token
  949. return new Tuple<Point, double, double>(ScaleAndCreatePoint(initialPositionX, initialPositionY), initialPositionX, initialPositionY);
  950. }
  951. /// <summary>
  952. /// parses a "moveto", "close loop" or "lineto" path element with absolute coordinates
  953. /// </summary>
  954. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  955. /// <returns>the point at the end of the move, close loop or line action and its exact, unscaled coordinates</returns>
  956. private Tuple<Point, double, double> Parse_M_L(List<string> pathElements)
  957. {
  958. pathElements.RemoveAt(0); //remove element descriptor token
  959. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x coordinate
  960. pathElements.RemoveAt(0); //remove x coordinate token
  961. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y coordinate
  962. pathElements.RemoveAt(0); //remove y coordinate token
  963. return new Tuple<Point, double, double>(ScaleAndCreatePoint(x, y), x, y);
  964. }
  965. /// <summary>
  966. /// parses a "moveto", "close loop" or "lineto" path element with relative coordinates
  967. /// </summary>
  968. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  969. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  970. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  971. /// <returns>the point at the end of the move, close loop or line action and its exact, unscaled coordinates</returns>
  972. private Tuple<Point, double, double> Parse_m_l(List<string> pathElements, double lastPositionX, double lastPositionY)
  973. {
  974. pathElements.RemoveAt(0); //remove element descriptor token
  975. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative x coordinate
  976. pathElements.RemoveAt(0); //remove x coordinate token
  977. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative y coordinate
  978. pathElements.RemoveAt(0); //remove y coordinate token
  979. x = lastPositionX + x; //compute absolute x coordinate
  980. y = lastPositionY + y; //compute absolute y coordinate
  981. return new Tuple<Point, double, double>(ScaleAndCreatePoint(x, y), x, y);
  982. }
  983. /// <summary>
  984. /// parses a "horizontal lineto" path element with absolute coordinates
  985. /// </summary>
  986. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  987. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  988. /// <returns>the point at the end of the horizontal line action and its exact, unscaled coordinates</returns>
  989. private Tuple<Point, double, double> Parse_H(List<string> pathElements, double lastPositionY)
  990. {
  991. pathElements.RemoveAt(0); //remove element descriptor token
  992. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x coordinate
  993. pathElements.RemoveAt(0); //remove x coordinate token
  994. return new Tuple<Point, double, double>(ScaleAndCreatePoint(x, lastPositionY), x, lastPositionY);
  995. }
  996. /// <summary>
  997. /// parses a "horizontal lineto" path element with relative coordinates
  998. /// </summary>
  999. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1000. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1001. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1002. /// <returns>the point at the end of the horizontal line action and its exact, unscaled coordinates</returns>
  1003. private Tuple<Point, double, double> Parse_h(List<string> pathElements, double lastPositionX, double lastPositionY)
  1004. {
  1005. pathElements.RemoveAt(0); //remove element descriptor token
  1006. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative x coordinate
  1007. pathElements.RemoveAt(0); //remove x coordinate token
  1008. x = lastPositionX + x; //compute absolute x coordinate
  1009. return new Tuple<Point, double, double>(ScaleAndCreatePoint(x, lastPositionY), x, lastPositionY);
  1010. }
  1011. /// <summary>
  1012. /// parses a "vertical lineto" path element with absolute coordinates
  1013. /// </summary>
  1014. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1015. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1016. /// <returns>the point at the end of the vertical line action and its exact, unscaled coordinates</returns>
  1017. private Tuple<Point, double, double> Parse_V(List<string> pathElements, double lastPositionX)
  1018. {
  1019. pathElements.RemoveAt(0); //remove element descriptor token
  1020. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y coordinate
  1021. pathElements.RemoveAt(0); //remove y coordinate token
  1022. return new Tuple<Point, double, double>(ScaleAndCreatePoint(lastPositionX, y), lastPositionX, y);
  1023. }
  1024. /// <summary>
  1025. /// parses a "vertical lineto" path element with relative coordinates
  1026. /// </summary>
  1027. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1028. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1029. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1030. /// <returns>the point at the end of the vertical line action and its exact, unscaled coordinates</returns>
  1031. private Tuple<Point, double, double> Parse_v(List<string> pathElements, double lastPositionX, double lastPositionY)
  1032. {
  1033. pathElements.RemoveAt(0); //remove element descriptor token
  1034. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse relative y coordinate
  1035. pathElements.RemoveAt(0); //remove y coordinate token
  1036. y = lastPositionY + y; //compute absolute y coordinate
  1037. return new Tuple<Point, double, double>(ScaleAndCreatePoint(lastPositionX, y), lastPositionX, y);
  1038. }
  1039. /// <summary>
  1040. /// parses a "cubic bezier curve" path element with absolute coordinates
  1041. /// </summary>
  1042. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1043. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1044. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1045. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  1046. private Tuple<List<Point>, double, double, double, double> Parse_C(List<string> pathElements, double lastPositionX, double lastPositionY)
  1047. {
  1048. pathElements.RemoveAt(0); //remove element descriptor token
  1049. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point x coordinate
  1050. pathElements.RemoveAt(0); //remove x coordinate token
  1051. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point y coordinate
  1052. pathElements.RemoveAt(0); //remove y coordinate token
  1053. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1054. pathElements.RemoveAt(0); //remove x coordinate token
  1055. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1056. pathElements.RemoveAt(0); //remove y coordinate token
  1057. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1058. pathElements.RemoveAt(0); //remove x coordinate token
  1059. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1060. pathElements.RemoveAt(0); //remove y coordinate token
  1061. return new Tuple<List<Point>, double, double, double, double>(SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1062. }
  1063. /// <summary>
  1064. /// parses a "cubic bezier curve" path element with relative coordinates
  1065. /// </summary>
  1066. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1067. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1068. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1069. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  1070. private Tuple<List<Point>, double, double, double, double> Parse_c(List<string> pathElements, double lastPositionX, double lastPositionY)
  1071. {
  1072. pathElements.RemoveAt(0); //remove element descriptor token
  1073. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point x coordinate
  1074. pathElements.RemoveAt(0); //remove x coordinate token
  1075. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse first control point y coordinate
  1076. pathElements.RemoveAt(0); //remove y coordinate token
  1077. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1078. pathElements.RemoveAt(0); //remove x coordinate token
  1079. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1080. pathElements.RemoveAt(0); //remove y coordinate token
  1081. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1082. pathElements.RemoveAt(0); //remove x coordinate token
  1083. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1084. pathElements.RemoveAt(0); //remove y coordinate token
  1085. x1 = lastPositionX + x1; //compute absolute x coordinate
  1086. y1 = lastPositionY + y1; //compute absolute y coordinate
  1087. x2 = lastPositionX + x2; //compute absolute x coordinate
  1088. y2 = lastPositionY + y2; //compute absolute y coordinate
  1089. x = lastPositionX + x; //compute absolute x coordinate
  1090. y = lastPositionY + y; //compute absolute y coordinate
  1091. return new Tuple<List<Point>, double, double, double, double>(SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1092. }
  1093. /// <summary>
  1094. /// parses a "cubic bezier curve shorthand" path element with absolute coordinates
  1095. /// </summary>
  1096. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1097. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1098. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1099. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1100. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1101. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  1102. private Tuple<List<Point>, double, double, double, double> Parse_S(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1103. {
  1104. pathElements.RemoveAt(0); //remove element descriptor token
  1105. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1106. pathElements.RemoveAt(0); //remove x coordinate token
  1107. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1108. pathElements.RemoveAt(0); //remove y coordinate token
  1109. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1110. pathElements.RemoveAt(0); //remove x coordinate token
  1111. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1112. pathElements.RemoveAt(0); //remove y coordinate token
  1113. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1114. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1115. return new Tuple<List<Point>, double, double, double, double>(SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1116. }
  1117. /// <summary>
  1118. /// parses a "cubic bezier curve shorthand" path element with relative coordinates
  1119. /// </summary>
  1120. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1121. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1122. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1123. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1124. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1125. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the second bezier control point</returns>
  1126. private Tuple<List<Point>, double, double, double, double> Parse_s(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1127. {
  1128. pathElements.RemoveAt(0); //remove element descriptor token
  1129. double x2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point x coordinate
  1130. pathElements.RemoveAt(0); //remove x coordinate token
  1131. double y2 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse second control point y coordinate
  1132. pathElements.RemoveAt(0); //remove y coordinate token
  1133. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1134. pathElements.RemoveAt(0); //remove x coordinate token
  1135. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1136. pathElements.RemoveAt(0); //remove y coordinate token
  1137. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1138. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1139. x2 = lastPositionX + x2; //compute absolute x coordinate
  1140. y2 = lastPositionY + y2; //compute absolute y coordinate
  1141. x = lastPositionX + x; //compute absolute x coordinate
  1142. y = lastPositionY + y; //compute absolute y coordinate
  1143. return new Tuple<List<Point>, double, double, double, double>(SampleCubicBezier(lastPositionX, lastPositionY, x1, y1, x2, y2, x, y), x, y, x2, y2);
  1144. }
  1145. /// <summary>
  1146. /// parses a "quadratic bezier curve" path element with absolute coordinates
  1147. /// </summary>
  1148. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1149. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1150. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1151. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1152. private Tuple<List<Point>, double, double, double, double> Parse_Q(List<string> pathElements, double lastPositionX, double lastPositionY)
  1153. {
  1154. pathElements.RemoveAt(0); //remove element descriptor token
  1155. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point x coordinate
  1156. pathElements.RemoveAt(0); //remove x coordinate token
  1157. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point y coordinate
  1158. pathElements.RemoveAt(0); //remove y coordinate token
  1159. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1160. pathElements.RemoveAt(0); //remove x coordinate token
  1161. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1162. pathElements.RemoveAt(0); //remove y coordinate token
  1163. return new Tuple<List<Point>, double, double, double, double>(SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1164. }
  1165. /// <summary>
  1166. /// parses a "quadratic bezier curve" path element with relative coordinates
  1167. /// </summary>
  1168. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1169. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1170. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1171. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1172. private Tuple<List<Point>, double, double, double, double> Parse_q(List<string> pathElements, double lastPositionX, double lastPositionY)
  1173. {
  1174. pathElements.RemoveAt(0); //remove element descriptor token
  1175. double x1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point x coordinate
  1176. pathElements.RemoveAt(0); //remove x coordinate token
  1177. double y1 = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse control point y coordinate
  1178. pathElements.RemoveAt(0); //remove y coordinate token
  1179. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1180. pathElements.RemoveAt(0); //remove x coordinate token
  1181. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1182. pathElements.RemoveAt(0); //remove y coordinate token
  1183. x1 = lastPositionX + x1; //compute absolute x coordinate
  1184. y1 = lastPositionY + y1; //compute absolute y coordinate
  1185. x = lastPositionX + x; //compute absolute x coordinate
  1186. y = lastPositionY + y; //compute absolute y coordinate
  1187. return new Tuple<List<Point>, double, double, double, double>(SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1188. }
  1189. /// <summary>
  1190. /// parses a "quadratic bezier curve shorthand" path element with absolute coordinates
  1191. /// </summary>
  1192. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1193. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1194. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1195. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1196. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1197. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1198. private Tuple<List<Point>, double, double, double, double> Parse_T(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1199. {
  1200. pathElements.RemoveAt(0); //remove element descriptor token
  1201. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1202. pathElements.RemoveAt(0); //remove x coordinate token
  1203. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1204. pathElements.RemoveAt(0); //remove y coordinate token
  1205. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1206. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1207. return new Tuple<List<Point>, double, double, double, double>(SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1208. }
  1209. /// <summary>
  1210. /// parses a "quadratic bezier curve shorthand" path element with relative coordinates
  1211. /// </summary>
  1212. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1213. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1214. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1215. /// <param name="lastBezierControlPointX">absolute x coordinate of the last bezier control point of the previous bezier curve</param>
  1216. /// <param name="lastBezierControlPointY">absolute y coordinate of the last bezier control point of the previous bezier curve</param>
  1217. /// <returns>a List of Points containing all sampled points on the bezier curve, aswell as the unscaled x and y coordinates of the last point of the curve and of the bezier control point</returns>
  1218. private Tuple<List<Point>, double, double, double, double> Parse_t(List<string> pathElements, double lastPositionX, double lastPositionY, double lastBezierControlPointX, double lastBezierControlPointY)
  1219. {
  1220. pathElements.RemoveAt(0); //remove element descriptor token
  1221. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1222. pathElements.RemoveAt(0); //remove x coordinate token
  1223. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1224. pathElements.RemoveAt(0); //remove y coordinate token
  1225. x = lastPositionX + x; //compute absolute x coordinate
  1226. y = lastPositionY + y; //compute absolute y coordinate
  1227. double x1 = lastPositionX + (lastPositionX - lastBezierControlPointX); //mirror last bezier control point at bezier start point to get first new bezier control point
  1228. double y1 = lastPositionY + (lastPositionY - lastBezierControlPointY); //mirror last bezier control point at bezier start point to get first new bezier control point
  1229. return new Tuple<List<Point>, double, double, double, double>(SampleQuadraticBezier(lastPositionX, lastPositionY, x1, y1, x, y), x, y, x1, y1);
  1230. }
  1231. /// <summary>
  1232. /// parses a "elliptical arc" path element with absolute coordinates
  1233. /// </summary>
  1234. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1235. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1236. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1237. /// <returns>a List of Points containing all sampled points on the elliptic arc, aswell as the unscaled x and y coordinates of the last point of the arc<returns>
  1238. private Tuple<List<Point>, double, double> Parse_A(List<string> pathElements, double lastPositionX, double lastPositionY)
  1239. {
  1240. pathElements.RemoveAt(0); //remove element descriptor token
  1241. double rx = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x radius
  1242. pathElements.RemoveAt(0); //remove x radius token
  1243. double ry = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y radius
  1244. pathElements.RemoveAt(0); //remove y radius token
  1245. double thetha = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse rotation
  1246. pathElements.RemoveAt(0); //remove rotation token
  1247. bool largeArcFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse large arc flag
  1248. pathElements.RemoveAt(0); //remove large arc flag token
  1249. bool sweepFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse sweep flag
  1250. pathElements.RemoveAt(0); //remove sweep flag token
  1251. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1252. pathElements.RemoveAt(0); //remove x coordinate token
  1253. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1254. pathElements.RemoveAt(0); //remove y coordinate token
  1255. x = x - lastPositionX; //compute relative x coordinate
  1256. y = y - lastPositionY; //compute relative y coordinate
  1257. return new Tuple<List<Point>, double, double>(SampleArc(lastPositionX, lastPositionY, rx, ry, x, y, thetha, largeArcFlag, sweepFlag), x, y);
  1258. }
  1259. /// <summary>
  1260. /// parses a "elliptical arc" path element with relative coordinates
  1261. /// </summary>
  1262. /// <param name="pathElements">a list of all not yet parsed path element tokens and values in correct order, starting with the element to be parsed</param>
  1263. /// <param name="lastPositionX">absolute x coordinate of the last active point</param>
  1264. /// <param name="lastPositionY">absolute y coordinate of the last active point</param>
  1265. /// <returns>a List of Points containing all sampled points on the elliptic arc, aswell as the unscaled x and y coordinates of the last point of the arc</returns>
  1266. private Tuple<List<Point>, double, double> Parse_a(List<string> pathElements, double lastPositionX, double lastPositionY)
  1267. {
  1268. pathElements.RemoveAt(0); //remove element descriptor token
  1269. double rx = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse x radius
  1270. pathElements.RemoveAt(0); //remove x radius token
  1271. double ry = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse y radius
  1272. pathElements.RemoveAt(0); //remove y radius token
  1273. double thetha = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse rotation
  1274. pathElements.RemoveAt(0); //remove rotation token
  1275. bool largeArcFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse large arc flag
  1276. pathElements.RemoveAt(0); //remove large arc flag token
  1277. bool sweepFlag = Convert.ToInt16(pathElements.First()) == 1 ? true : false; //parse sweep flag
  1278. pathElements.RemoveAt(0); //remove sweep flag token
  1279. double x = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point x coordinate
  1280. pathElements.RemoveAt(0); //remove x coordinate token
  1281. double y = Convert.ToDouble(pathElements.First(), CultureInfo.InvariantCulture); //parse target point y coordinate
  1282. pathElements.RemoveAt(0); //remove y coordinate token
  1283. return new Tuple<List<Point>, double, double>(SampleArc(lastPositionX, lastPositionY, rx, ry, x, y, thetha, largeArcFlag, sweepFlag), x, y);
  1284. }
  1285. /// <summary>
  1286. /// samples an arc of an ellipse into a list of points
  1287. /// </summary>
  1288. /// <param name="lastPositionX">x coordinate of last point</param>
  1289. /// <param name="lastPositionY">y coordinate of last point</param>
  1290. /// <param name="rx">x radius of the ellipse</param>
  1291. /// <param name="ry">y radius of the ellipse</param>
  1292. /// <param name="nextPositionXRelative">x coordinate of next point</param>
  1293. /// <param name="nextPositionYRelative">y coordinate of next point</param>
  1294. /// <param name="thetha">rotation of the ellipse around the x axis</param>
  1295. /// <param name="largeArcFlag">flag determining if the large or the small arc is to be drawn</param>
  1296. /// <param name="sweepFlag">flag determining in which direction the arc is to be drawn (false = ccw, true = cw)</param>
  1297. /// <returns></returns>
  1298. private List<Point> SampleArc(double lastPositionX, double lastPositionY, double rx, double ry, double nextPositionXRelative, double nextPositionYRelative, double thetha, bool largeArcFlag, bool sweepFlag)
  1299. {
  1300. double cos = Math.Cos(thetha / 180 * Math.PI);
  1301. double sin = Math.Sin(thetha / 180 * Math.PI);
  1302. double targetXTransformed = cos * nextPositionXRelative - sin * nextPositionYRelative; //rotate target point counterclockwise around the start point by [thetha] degrees, thereby practically rotating an intermediate coordinate system, which has its origin in the start point, clockwise by the same amount
  1303. double targetYTransformed = sin * nextPositionXRelative + cos * nextPositionYRelative;
  1304. var values = SampleEllipticArcBiasedNoRotation(rx, ry, targetXTransformed, targetYTransformed, largeArcFlag, sweepFlag);
  1305. List<Point> result = new List<Point>();
  1306. for (int j = 0; j < values.Item1.Length; j++)
  1307. {
  1308. double xCoordinateRelative = cos * values.Item1[j] + sin * values.Item2[j]; //rotate backwards so intermediate coordinate system and "real" coordinate system have the same rotation again
  1309. double yCoordinateRelative = cos * values.Item2[j] - sin * values.Item1[j];
  1310. double xCoordinateAbsolute = lastPositionX + xCoordinateRelative; //translate relative to absolute coordinates (intermediate coordinate system is now again aligned with the "real" one (the virtual pane on which all vectorgraphic elements are placed) (note that this "real" coordinate system is still not the same as the one actually representing pixels for drawing, as it still has to be scaled appropriately (done inside the ScaleAndCreatePoint method)))
  1311. double yCoordinateAbsolute = lastPositionY + yCoordinateRelative;
  1312. result.Add(ScaleAndCreatePoint(xCoordinateAbsolute, yCoordinateAbsolute));
  1313. }
  1314. return result;
  1315. }
  1316. /// <summary>
  1317. /// samples an elliptical arc with given radii through coordinate origin and endpoint with specified properties
  1318. /// </summary>
  1319. /// <param name="rx">x radius</param>
  1320. /// <param name="ry">y radius</param>
  1321. /// <param name="targetXTransformed">x coordinate of next point</param>
  1322. /// <param name="targetYTransformed">y coordinate of next point</param>
  1323. /// <param name="largeArcFlag">flag determining if the large or the small arc is to be drawn</param>
  1324. /// <param name="sweepFlag">flag determining in which direction the arc is to be drawn (false = ccw, true = cw)</param>
  1325. /// <returns></returns>
  1326. private Tuple<double[], double[]> SampleEllipticArcBiasedNoRotation(double rx, double ry, double targetXTransformed, double targetYTransformed, bool largeArcFlag, bool sweepFlag)
  1327. {
  1328. double xStretchFactor = rx / ry; //get rx to ry ratio
  1329. var values = SampleCircleArcBiasedNoRotation(ry, targetXTransformed / xStretchFactor, targetYTransformed, largeArcFlag, sweepFlag); //get a circular arc with radius ry
  1330. for (int j = 0; j < values.Item1.Length; j++)
  1331. {
  1332. values.Item1[j] = values.Item1[j] * xStretchFactor; //correct x coordinates to get an elliptical arc from a circular one
  1333. }
  1334. return values;
  1335. }
  1336. /// <summary>
  1337. /// samples a circular arc with given radius through coordinate origin and endpoint with specified properties
  1338. /// </summary>
  1339. /// <param name="r">radius</param>
  1340. /// <param name="nextPositionXRelative">x coordinate of next point</param>
  1341. /// <param name="nextPositionYRelative">y coordinate of next point</param>
  1342. /// <param name="largeArcFlag">flag determining if the large or the small arc is to be drawn</param>
  1343. /// <param name="sweepFlag">flag determining in which direction the arc is to be drawn (false = ccw, true = cw)</param>
  1344. /// <returns></returns>
  1345. private Tuple<double[], double[]> SampleCircleArcBiasedNoRotation(double r, double nextPositionXRelative, double nextPositionYRelative, bool largeArcFlag, bool sweepFlag)
  1346. {
  1347. // code for center computation adapted from https://stackoverflow.com/a/36211852
  1348. double radsq = r * r;
  1349. double q = Math.Sqrt(((nextPositionXRelative) * (nextPositionXRelative)) + ((nextPositionYRelative) * (nextPositionYRelative))); //Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
  1350. double x3 = (nextPositionXRelative) / 2; //(x1 + x2) / 2;
  1351. double y3 = (nextPositionYRelative) / 2; //(y1 + y2) / 2;
  1352. bool xPlusFlag; //flags needed to select center point "left" of the line between origin and the endpoint (will be used to select correct one ("left" or "right" one) later together with flags passed as arguments
  1353. bool yPlusFlag;
  1354. if (nextPositionXRelative > 0)
  1355. {
  1356. yPlusFlag = true; //left point lies above line
  1357. }
  1358. else
  1359. {
  1360. yPlusFlag = false; //left point lies below line
  1361. }
  1362. if (nextPositionYRelative > 0)
  1363. {
  1364. xPlusFlag = false; //left point lies left of line
  1365. }
  1366. else
  1367. {
  1368. xPlusFlag = true; //left point lies right of line
  1369. }
  1370. if(sweepFlag != largeArcFlag) //need "right" center point, not "left" one (refer to svg specification, sweepFlag means going around the circle in "clockwise" direction, largeArcFlag means tracing the larger of the two possible arcs in the selected direction)
  1371. {
  1372. xPlusFlag = !xPlusFlag;
  1373. yPlusFlag = !yPlusFlag;
  1374. }
  1375. double xC; // coordinates of center point of circle
  1376. double yC;
  1377. if(xPlusFlag) xC = x3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionYRelative) / q); //x3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((y1 - y2) / q);
  1378. else xC = x3 - Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionYRelative) / q);
  1379. if (yPlusFlag) yC = y3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionXRelative) / q); //y3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((x2-x1) / q);
  1380. else yC = y3 - Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((nextPositionXRelative) / q);
  1381. var values = SampleCircleArcBiasedAroundCenter(-xC, -yC, nextPositionXRelative - xC, nextPositionYRelative - yC, r, largeArcFlag, sweepFlag);
  1382. for (int j = 0; j < values.Item1.Length; j++)
  1383. {
  1384. values.Item1[j] = values.Item1[j] + xC; //correct center point coordinate bias
  1385. values.Item2[j] = values.Item2[j] + yC;
  1386. }
  1387. return values;
  1388. }
  1389. /// <summary>
  1390. /// samples a circular arc with given radius around the center from the startpoint to the endpoint in the specified direction
  1391. /// </summary>
  1392. /// <param name="xStartPoint">x coordinate of the start point</param>
  1393. /// <param name="yStartPoint">y coordinate of the start point</param>
  1394. /// <param name="xFinalPoint">x coordinate of the final point</param>
  1395. /// <param name="yFinalPoint">y coordinate of the final point</param>
  1396. /// <param name="r">radius</param>
  1397. /// <param name="clockwise">direction</param>
  1398. /// <returns></returns>
  1399. private Tuple<double[], double[]> SampleCircleArcBiasedAroundCenter(double xStartPoint, double yStartPoint, double xFinalPoint, double yFinalPoint, double r, bool largeArcFlag, bool clockwise)
  1400. {
  1401. double phiEnd = Math.Atan2(yFinalPoint, xFinalPoint); // angles between points and origin and the positive x Axis
  1402. double phiStart = Math.Atan2(yStartPoint, xStartPoint);
  1403. double angle = ((double)2 * Math.PI) / (double)samplingRateEllipse; //compute angle increment (equal to the one used for ellipses)
  1404. double angleDifference = Math.Abs(phiStart - phiEnd);
  1405. if (angleDifference > 2 * Math.PI || angleDifference < 0) throw new Exception("angleDifference out of range: " + angleDifference); //TODO remove
  1406. if (largeArcFlag) // get larger angleDifference
  1407. {
  1408. if (angleDifference < Math.PI) angleDifference = ((double)2 * Math.PI) - angleDifference; // was smaller angleDifference
  1409. }
  1410. else // get smaller angleDifference
  1411. {
  1412. if(angleDifference > Math.PI) angleDifference = ((double)2 * Math.PI) - angleDifference; // was larger angleDifference
  1413. }
  1414. int numberOfPoints = (int) Math.Ceiling(angleDifference / angle); //compute number of points to sample
  1415. double[] xValues = new double[numberOfPoints];
  1416. double[] yValues = new double[numberOfPoints];
  1417. double phiCurrent = phiStart;
  1418. for (int j = 0; j < numberOfPoints-1; j++) //compute intermediate points
  1419. {
  1420. if (clockwise) phiCurrent -= angle; //get new angle
  1421. else phiCurrent += angle;
  1422. yValues[j] = Math.Sin(phiCurrent) * r; //angles are relative to positive x Axis!
  1423. xValues[j] = Math.Cos(phiCurrent) * r;
  1424. }
  1425. xValues[numberOfPoints - 1] = xFinalPoint; //(last segment always has an angle of less than or exactly 'angle')
  1426. yValues[numberOfPoints - 1] = yFinalPoint;
  1427. return new Tuple<double[], double[]>(xValues, yValues);
  1428. }
  1429. /// <summary>
  1430. /// samples a cubic bezier curve with a static number of steps (samplingRateBezier)
  1431. /// </summary>
  1432. /// <param name="lastPositionX">x coordinate of last point</param>
  1433. /// <param name="lastPositionY">y coordinate of last point</param>
  1434. /// <param name="controlPoint1X">x coordinate of control point 1</param>
  1435. /// <param name="controlPoint1Y">y coordinate of control point 1</param>
  1436. /// <param name="controlPoint2X">x coordinate of control point 2</param>
  1437. /// <param name="controlPoint2Y">y coordinate of control point 2</param>
  1438. /// <param name="nextPositionX">x coordinate of next point</param>
  1439. /// <param name="nextPositionY">y coordinate of next point</param>
  1440. /// <returns>a List of Points containing all sampled points</returns>
  1441. private List<Point> SampleCubicBezier(double lastPositionX, double lastPositionY, double controlPoint1X, double controlPoint1Y, double controlPoint2X, double controlPoint2Y, double nextPositionX, double nextPositionY)
  1442. {
  1443. var line1 = CreateDiscreteLine(lastPositionX, lastPositionY, controlPoint1X, controlPoint1Y);
  1444. var line2 = CreateDiscreteLine(controlPoint1X, controlPoint1Y, controlPoint2X, controlPoint2Y);
  1445. var line3 = CreateDiscreteLine(controlPoint2X, controlPoint2Y, nextPositionX, nextPositionY);
  1446. var quadraticBezier1 = ComputeBezierStep(line1.Item1, line1.Item2, line2.Item1, line2.Item2);
  1447. var quadraticBezier2 = ComputeBezierStep(line2.Item1, line2.Item2, line3.Item1, line3.Item2);
  1448. var values = ComputeBezierStep(quadraticBezier1.Item1, quadraticBezier1.Item2, quadraticBezier2.Item1, quadraticBezier2.Item2);
  1449. List<Point> result = new List<Point>();
  1450. for (int j = 0; j < samplingRateBezier; j++)
  1451. {
  1452. result.Add(ScaleAndCreatePoint(values.Item1[j], values.Item2[j]));
  1453. }
  1454. return result;
  1455. }
  1456. /// <summary>
  1457. /// samples a quadratic bezier curve with a static number of steps (samplingRateBezier)
  1458. /// </summary>
  1459. /// <param name="lastPositionX">x coordinate of last point</param>
  1460. /// <param name="lastPositionY">y coordinate of last point</param>
  1461. /// <param name="controlPointX">x coordinate of control point</param>
  1462. /// <param name="controlPointY">y coordinate of control point</param>
  1463. /// <param name="nextPositionX">x coordinate of next point</param>
  1464. /// <param name="nextPositionY">y coordinate of next point</param>
  1465. /// <returns>a List of Points containing all sampled points</returns>
  1466. private List<Point> SampleQuadraticBezier(double lastPositionX, double lastPositionY, double controlPointX, double controlPointY, double nextPositionX, double nextPositionY)
  1467. {
  1468. var line1 = CreateDiscreteLine(lastPositionX, lastPositionY, controlPointX, controlPointY);
  1469. var line2 = CreateDiscreteLine(controlPointX, controlPointY, nextPositionX, nextPositionY);
  1470. var values = ComputeBezierStep(line1.Item1, line1.Item2, line2.Item1, line2.Item2);
  1471. List<Point> result = new List<Point>();
  1472. for (int j = 0; j < samplingRateBezier; j++)
  1473. {
  1474. result.Add(ScaleAndCreatePoint(values.Item1[j], values.Item2[j]));
  1475. }
  1476. return result;
  1477. }
  1478. /// <summary>
  1479. /// create a discrete line with [samplingRateBezier] points (including start and end point) between two points
  1480. /// </summary>
  1481. /// <param name="point1X">coordinate of point 1</param>
  1482. /// <param name="point1Y">y coordinate of point 1</param>
  1483. /// <param name="point2X">x coordinate of point 2</param>
  1484. /// <param name="point2Y">y coordinate of point 2</param>
  1485. /// <returns>the discrete line as arrays of x and y coordinates</returns>
  1486. private Tuple<double[], double[]> CreateDiscreteLine(double point1X, double point1Y, double point2X, double point2Y)
  1487. {
  1488. double[] resultX = new double[samplingRateBezier];
  1489. double[] resultY = new double[samplingRateBezier];
  1490. for (int j = 0; j < samplingRateBezier; j++)
  1491. {
  1492. var pointResult = LinearInterpolationForBezier(point1X, point1Y, point2X, point2Y, j);
  1493. resultX[j] = pointResult.Item1;
  1494. resultY[j] = pointResult.Item2;
  1495. }
  1496. return new Tuple<double[], double[]>(resultX, resultY);
  1497. }
  1498. /// <summary>
  1499. /// computes the discrete bezier curve between two given dicrete lines/curves
  1500. /// </summary>
  1501. /// <param name="line1X">x coordinates of all points in line 1</param>
  1502. /// <param name="line1Y">y coordinates of all points in line 1</param>
  1503. /// <param name="line2X">x coordinates of all points in line 2</param>
  1504. /// <param name="line2Y">y coordinates of all points in line 2</param>
  1505. /// <returns>the discrete bezier curve</returns>
  1506. private Tuple<double[], double[]> ComputeBezierStep(double[] line1X, double[] line1Y, double[] line2X, double[] line2Y)
  1507. {
  1508. double[] resultX = new double[samplingRateBezier];
  1509. double[] resultY = new double[samplingRateBezier];
  1510. for (int j = 0; j < samplingRateBezier; j++)
  1511. {
  1512. var pointResult = LinearInterpolationForBezier(line1X[j], line1Y[j], line2X[j], line2Y[j], j);
  1513. resultX[j] = pointResult.Item1;
  1514. resultY[j] = pointResult.Item2;
  1515. }
  1516. return new Tuple<double[], double[]>(resultX, resultY);
  1517. }
  1518. /// <summary>
  1519. /// creates the linearly interpolated point at j/(samplingRateBezier - 1) between point 1 and point 2
  1520. /// </summary>
  1521. /// <param name="point1X">x coordinate of point 1</param>
  1522. /// <param name="point1Y">y coordinate of point 1</param>
  1523. /// <param name="point2X">x coordinate of point 2</param>
  1524. /// <param name="point2Y">y coordinate of point 2</param>
  1525. /// <param name="j">number of point to be interpolated, at a total number of [samplingRateBezier] points</param>
  1526. /// <returns>the linearly interpolated point</returns>
  1527. private Tuple<double, double> LinearInterpolationForBezier(double point1X, double point1Y, double point2X, double point2Y, int j)
  1528. {
  1529. double factor = ((double)1 / (double)(samplingRateBezier - 1)) * (double)j; //factor for linear interpolation
  1530. double x = point1X + ((point2X - point1X) * factor);
  1531. double y = point1Y + ((point2Y - point1Y) * factor);
  1532. return new Tuple<double, double>(x, y);
  1533. }
  1534. /// <summary>
  1535. /// parses a hierarchical svg element and all its sub-elements
  1536. /// </summary>
  1537. /// <param name="currentElement">the definition of the top level element as whitespace seperated String[]</param>
  1538. /// <param name="allLines">an array holding all lines of the input file</param>
  1539. /// <returns>the parsed element as a Line object, or null if the element is not supported</returns>
  1540. private List<InternalLine> ParseMultiLineSVGElement(string[] currentElement, string[] allLines)
  1541. {
  1542. throw new NotImplementedException();
  1543. }
  1544. /// <summary>
  1545. /// removes the name of the attribute aswell as the '="' at the beginning and the '"' or '">' at the end of an attribute definition
  1546. /// </summary>
  1547. /// <param name="definition">the definition from the svg file</param>
  1548. /// <returns>the value of the attribute, as String (the part of definition contained between '"'s)</returns>
  1549. private String ParseSingleSVGAttribute(String definition)
  1550. {
  1551. return definition.Split('"')[1];
  1552. }
  1553. /// <summary>
  1554. /// fetches a single svg element definition that may extend ovr several lines of the input file, iterates i to point to the last line of the element definition
  1555. /// </summary>
  1556. /// <param name="allLines">an array holding all lines of the input file</param>
  1557. /// <returns>the definition of the current svg element, as String[] split by whitespaces</returns>
  1558. private String[] GetCurrentElement(String[] allLines)
  1559. {
  1560. List<String> currentElementTemp = allLines[i].Split(whitespaces).ToList();
  1561. while (!currentElementTemp.Last().EndsWith(">"))
  1562. {
  1563. i++;
  1564. currentElementTemp.AddRange(allLines[i].Split(whitespaces).ToList());
  1565. }
  1566. return currentElementTemp.ToArray();
  1567. }
  1568. /// <summary>
  1569. /// applies the scale factor to the coordinates and creates a new Point
  1570. /// </summary>
  1571. /// <param name="x">unscaled x coordinate</param>
  1572. /// <param name="y">unscaled y coordinate</param>
  1573. /// <returns>new Point with scaled coordinates</returns>
  1574. private Point ScaleAndCreatePoint(double x, double y)
  1575. {
  1576. return new Point((int)Math.Round(x * scale), (int)Math.Round(y * scale));
  1577. }
  1578. /// <summary>
  1579. /// creates a representation of an ellipse as a List of Points by sampling the outline of the ellipse
  1580. /// </summary>
  1581. /// <param name="x">x coordinate of the center of the ellipse</param>
  1582. /// <param name="y">y coordinate of the center of the ellipse</param>
  1583. /// <param name="rx">x radius of the ellipse</param>
  1584. /// <param name="ry">y radius of the ellipse</param>
  1585. /// <returns>the parsed element as a List of Points</returns>
  1586. private List<Point> SampleEllipse(double x, double y, double rx, double ry)
  1587. {
  1588. List<Point> ellipse = new List<Point>();
  1589. double angle = ((double)2 * Math.PI) / (double)samplingRateEllipse;
  1590. double yScale = ry / rx;
  1591. double[] xValues = new double[samplingRateEllipse / 4];
  1592. double[] yValues = new double[samplingRateEllipse / 4];
  1593. for (int j = 0; j < samplingRateEllipse / 4; j++) //compute offset values of points for one quadrant
  1594. {
  1595. xValues[j] = Math.Sin((double)j * angle) * rx;
  1596. yValues[j] = Math.Cos((double)j * angle) * rx;
  1597. }
  1598. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for first quadrant
  1599. {
  1600. int xCoord = Convert.ToInt32(Math.Round(x + xValues[j]));
  1601. int yCoord = Convert.ToInt32(Math.Round(y - yValues[j] * yScale));
  1602. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1603. }
  1604. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for second quadrant
  1605. {
  1606. int xCoord = Convert.ToInt32(Math.Round(x + yValues[j]));
  1607. int yCoord = Convert.ToInt32(Math.Round(y + xValues[j] * yScale));
  1608. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1609. }
  1610. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for third quadrant
  1611. {
  1612. int xCoord = Convert.ToInt32(Math.Round(x - xValues[j]));
  1613. int yCoord = Convert.ToInt32(Math.Round(y + yValues[j] * yScale));
  1614. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1615. }
  1616. for (int j = 0; j < samplingRateEllipse / 4; j++) //create actual points for fourth quadrant
  1617. {
  1618. int xCoord = Convert.ToInt32(Math.Round(x - yValues[j]));
  1619. int yCoord = Convert.ToInt32(Math.Round(y - xValues[j] * yScale));
  1620. ellipse.Add(ScaleAndCreatePoint(xCoord, yCoord));
  1621. }
  1622. ellipse.Add(ScaleAndCreatePoint(Convert.ToInt32(Math.Round(x + 0)), Convert.ToInt32(Math.Round(y - rx * yScale)))); //close ellipse
  1623. return ellipse;
  1624. }
  1625. }
  1626. }