SVGLoader.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930
  1. import {
  2. Box2,
  3. BufferGeometry,
  4. FileLoader,
  5. Float32BufferAttribute,
  6. Loader,
  7. Matrix3,
  8. Path,
  9. Shape,
  10. ShapePath,
  11. ShapeUtils,
  12. Vector2,
  13. Vector3
  14. } from 'three';
  15. class SVGLoader extends Loader {
  16. constructor( manager ) {
  17. super( manager );
  18. // Default dots per inch
  19. this.defaultDPI = 90;
  20. // Accepted units: 'mm', 'cm', 'in', 'pt', 'pc', 'px'
  21. this.defaultUnit = 'px';
  22. }
  23. load( url, onLoad, onProgress, onError ) {
  24. const scope = this;
  25. const loader = new FileLoader( scope.manager );
  26. loader.setPath( scope.path );
  27. loader.setRequestHeader( scope.requestHeader );
  28. loader.setWithCredentials( scope.withCredentials );
  29. loader.load( url, function ( text ) {
  30. try {
  31. onLoad( scope.parse( text ) );
  32. } catch ( e ) {
  33. if ( onError ) {
  34. onError( e );
  35. } else {
  36. console.error( e );
  37. }
  38. scope.manager.itemError( url );
  39. }
  40. }, onProgress, onError );
  41. }
  42. parse( text ) {
  43. const scope = this;
  44. function parseNode( node, style ) {
  45. if ( node.nodeType !== 1 ) return;
  46. const transform = getNodeTransform( node );
  47. let traverseChildNodes = true;
  48. let path = null;
  49. switch ( node.nodeName ) {
  50. case 'svg':
  51. break;
  52. case 'style':
  53. parseCSSStylesheet( node );
  54. break;
  55. case 'g':
  56. style = parseStyle( node, style );
  57. break;
  58. case 'path':
  59. style = parseStyle( node, style );
  60. if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node );
  61. break;
  62. case 'rect':
  63. style = parseStyle( node, style );
  64. path = parseRectNode( node );
  65. break;
  66. case 'polygon':
  67. style = parseStyle( node, style );
  68. path = parsePolygonNode( node );
  69. break;
  70. case 'polyline':
  71. style = parseStyle( node, style );
  72. path = parsePolylineNode( node );
  73. break;
  74. case 'circle':
  75. style = parseStyle( node, style );
  76. path = parseCircleNode( node );
  77. break;
  78. case 'ellipse':
  79. style = parseStyle( node, style );
  80. path = parseEllipseNode( node );
  81. break;
  82. case 'line':
  83. style = parseStyle( node, style );
  84. path = parseLineNode( node );
  85. break;
  86. case 'defs':
  87. traverseChildNodes = false;
  88. break;
  89. case 'use':
  90. style = parseStyle( node, style );
  91. const usedNodeId = node.href.baseVal.substring( 1 );
  92. const usedNode = node.viewportElement.getElementById( usedNodeId );
  93. if ( usedNode ) {
  94. parseNode( usedNode, style );
  95. } else {
  96. console.warn( 'SVGLoader: \'use node\' references non-existent node id: ' + usedNodeId );
  97. }
  98. break;
  99. default:
  100. // console.log( node );
  101. }
  102. if ( path ) {
  103. if ( style.fill !== undefined && style.fill !== 'none' ) {
  104. path.color.setStyle( style.fill );
  105. }
  106. transformPath( path, currentTransform );
  107. paths.push( path );
  108. path.userData = { node: node, style: style };
  109. }
  110. if ( traverseChildNodes ) {
  111. const nodes = node.childNodes;
  112. for ( let i = 0; i < nodes.length; i ++ ) {
  113. parseNode( nodes[ i ], style );
  114. }
  115. }
  116. if ( transform ) {
  117. transformStack.pop();
  118. if ( transformStack.length > 0 ) {
  119. currentTransform.copy( transformStack[ transformStack.length - 1 ] );
  120. } else {
  121. currentTransform.identity();
  122. }
  123. }
  124. }
  125. function parsePathNode( node ) {
  126. const path = new ShapePath();
  127. const point = new Vector2();
  128. const control = new Vector2();
  129. const firstPoint = new Vector2();
  130. let isFirstPoint = true;
  131. let doSetFirstPoint = false;
  132. const d = node.getAttribute( 'd' );
  133. // console.log( d );
  134. const commands = d.match( /[a-df-z][^a-df-z]*/ig );
  135. for ( let i = 0, l = commands.length; i < l; i ++ ) {
  136. const command = commands[ i ];
  137. const type = command.charAt( 0 );
  138. const data = command.substr( 1 ).trim();
  139. if ( isFirstPoint === true ) {
  140. doSetFirstPoint = true;
  141. isFirstPoint = false;
  142. }
  143. let numbers;
  144. switch ( type ) {
  145. case 'M':
  146. numbers = parseFloats( data );
  147. for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
  148. point.x = numbers[ j + 0 ];
  149. point.y = numbers[ j + 1 ];
  150. control.x = point.x;
  151. control.y = point.y;
  152. if ( j === 0 ) {
  153. path.moveTo( point.x, point.y );
  154. } else {
  155. path.lineTo( point.x, point.y );
  156. }
  157. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  158. }
  159. break;
  160. case 'H':
  161. numbers = parseFloats( data );
  162. for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
  163. point.x = numbers[ j ];
  164. control.x = point.x;
  165. control.y = point.y;
  166. path.lineTo( point.x, point.y );
  167. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  168. }
  169. break;
  170. case 'V':
  171. numbers = parseFloats( data );
  172. for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
  173. point.y = numbers[ j ];
  174. control.x = point.x;
  175. control.y = point.y;
  176. path.lineTo( point.x, point.y );
  177. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  178. }
  179. break;
  180. case 'L':
  181. numbers = parseFloats( data );
  182. for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
  183. point.x = numbers[ j + 0 ];
  184. point.y = numbers[ j + 1 ];
  185. control.x = point.x;
  186. control.y = point.y;
  187. path.lineTo( point.x, point.y );
  188. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  189. }
  190. break;
  191. case 'C':
  192. numbers = parseFloats( data );
  193. for ( let j = 0, jl = numbers.length; j < jl; j += 6 ) {
  194. path.bezierCurveTo(
  195. numbers[ j + 0 ],
  196. numbers[ j + 1 ],
  197. numbers[ j + 2 ],
  198. numbers[ j + 3 ],
  199. numbers[ j + 4 ],
  200. numbers[ j + 5 ]
  201. );
  202. control.x = numbers[ j + 2 ];
  203. control.y = numbers[ j + 3 ];
  204. point.x = numbers[ j + 4 ];
  205. point.y = numbers[ j + 5 ];
  206. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  207. }
  208. break;
  209. case 'S':
  210. numbers = parseFloats( data );
  211. for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
  212. path.bezierCurveTo(
  213. getReflection( point.x, control.x ),
  214. getReflection( point.y, control.y ),
  215. numbers[ j + 0 ],
  216. numbers[ j + 1 ],
  217. numbers[ j + 2 ],
  218. numbers[ j + 3 ]
  219. );
  220. control.x = numbers[ j + 0 ];
  221. control.y = numbers[ j + 1 ];
  222. point.x = numbers[ j + 2 ];
  223. point.y = numbers[ j + 3 ];
  224. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  225. }
  226. break;
  227. case 'Q':
  228. numbers = parseFloats( data );
  229. for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
  230. path.quadraticCurveTo(
  231. numbers[ j + 0 ],
  232. numbers[ j + 1 ],
  233. numbers[ j + 2 ],
  234. numbers[ j + 3 ]
  235. );
  236. control.x = numbers[ j + 0 ];
  237. control.y = numbers[ j + 1 ];
  238. point.x = numbers[ j + 2 ];
  239. point.y = numbers[ j + 3 ];
  240. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  241. }
  242. break;
  243. case 'T':
  244. numbers = parseFloats( data );
  245. for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
  246. const rx = getReflection( point.x, control.x );
  247. const ry = getReflection( point.y, control.y );
  248. path.quadraticCurveTo(
  249. rx,
  250. ry,
  251. numbers[ j + 0 ],
  252. numbers[ j + 1 ]
  253. );
  254. control.x = rx;
  255. control.y = ry;
  256. point.x = numbers[ j + 0 ];
  257. point.y = numbers[ j + 1 ];
  258. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  259. }
  260. break;
  261. case 'A':
  262. numbers = parseFloats( data, [ 3, 4 ], 7 );
  263. for ( let j = 0, jl = numbers.length; j < jl; j += 7 ) {
  264. // skip command if start point == end point
  265. if ( numbers[ j + 5 ] == point.x && numbers[ j + 6 ] == point.y ) continue;
  266. const start = point.clone();
  267. point.x = numbers[ j + 5 ];
  268. point.y = numbers[ j + 6 ];
  269. control.x = point.x;
  270. control.y = point.y;
  271. parseArcCommand(
  272. path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
  273. );
  274. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  275. }
  276. break;
  277. case 'm':
  278. numbers = parseFloats( data );
  279. for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
  280. point.x += numbers[ j + 0 ];
  281. point.y += numbers[ j + 1 ];
  282. control.x = point.x;
  283. control.y = point.y;
  284. if ( j === 0 ) {
  285. path.moveTo( point.x, point.y );
  286. } else {
  287. path.lineTo( point.x, point.y );
  288. }
  289. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  290. }
  291. break;
  292. case 'h':
  293. numbers = parseFloats( data );
  294. for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
  295. point.x += numbers[ j ];
  296. control.x = point.x;
  297. control.y = point.y;
  298. path.lineTo( point.x, point.y );
  299. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  300. }
  301. break;
  302. case 'v':
  303. numbers = parseFloats( data );
  304. for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
  305. point.y += numbers[ j ];
  306. control.x = point.x;
  307. control.y = point.y;
  308. path.lineTo( point.x, point.y );
  309. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  310. }
  311. break;
  312. case 'l':
  313. numbers = parseFloats( data );
  314. for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
  315. point.x += numbers[ j + 0 ];
  316. point.y += numbers[ j + 1 ];
  317. control.x = point.x;
  318. control.y = point.y;
  319. path.lineTo( point.x, point.y );
  320. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  321. }
  322. break;
  323. case 'c':
  324. numbers = parseFloats( data );
  325. for ( let j = 0, jl = numbers.length; j < jl; j += 6 ) {
  326. path.bezierCurveTo(
  327. point.x + numbers[ j + 0 ],
  328. point.y + numbers[ j + 1 ],
  329. point.x + numbers[ j + 2 ],
  330. point.y + numbers[ j + 3 ],
  331. point.x + numbers[ j + 4 ],
  332. point.y + numbers[ j + 5 ]
  333. );
  334. control.x = point.x + numbers[ j + 2 ];
  335. control.y = point.y + numbers[ j + 3 ];
  336. point.x += numbers[ j + 4 ];
  337. point.y += numbers[ j + 5 ];
  338. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  339. }
  340. break;
  341. case 's':
  342. numbers = parseFloats( data );
  343. for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
  344. path.bezierCurveTo(
  345. getReflection( point.x, control.x ),
  346. getReflection( point.y, control.y ),
  347. point.x + numbers[ j + 0 ],
  348. point.y + numbers[ j + 1 ],
  349. point.x + numbers[ j + 2 ],
  350. point.y + numbers[ j + 3 ]
  351. );
  352. control.x = point.x + numbers[ j + 0 ];
  353. control.y = point.y + numbers[ j + 1 ];
  354. point.x += numbers[ j + 2 ];
  355. point.y += numbers[ j + 3 ];
  356. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  357. }
  358. break;
  359. case 'q':
  360. numbers = parseFloats( data );
  361. for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
  362. path.quadraticCurveTo(
  363. point.x + numbers[ j + 0 ],
  364. point.y + numbers[ j + 1 ],
  365. point.x + numbers[ j + 2 ],
  366. point.y + numbers[ j + 3 ]
  367. );
  368. control.x = point.x + numbers[ j + 0 ];
  369. control.y = point.y + numbers[ j + 1 ];
  370. point.x += numbers[ j + 2 ];
  371. point.y += numbers[ j + 3 ];
  372. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  373. }
  374. break;
  375. case 't':
  376. numbers = parseFloats( data );
  377. for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
  378. const rx = getReflection( point.x, control.x );
  379. const ry = getReflection( point.y, control.y );
  380. path.quadraticCurveTo(
  381. rx,
  382. ry,
  383. point.x + numbers[ j + 0 ],
  384. point.y + numbers[ j + 1 ]
  385. );
  386. control.x = rx;
  387. control.y = ry;
  388. point.x = point.x + numbers[ j + 0 ];
  389. point.y = point.y + numbers[ j + 1 ];
  390. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  391. }
  392. break;
  393. case 'a':
  394. numbers = parseFloats( data, [ 3, 4 ], 7 );
  395. for ( let j = 0, jl = numbers.length; j < jl; j += 7 ) {
  396. // skip command if no displacement
  397. if ( numbers[ j + 5 ] == 0 && numbers[ j + 6 ] == 0 ) continue;
  398. const start = point.clone();
  399. point.x += numbers[ j + 5 ];
  400. point.y += numbers[ j + 6 ];
  401. control.x = point.x;
  402. control.y = point.y;
  403. parseArcCommand(
  404. path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
  405. );
  406. if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
  407. }
  408. break;
  409. case 'Z':
  410. case 'z':
  411. path.currentPath.autoClose = true;
  412. if ( path.currentPath.curves.length > 0 ) {
  413. // Reset point to beginning of Path
  414. point.copy( firstPoint );
  415. path.currentPath.currentPoint.copy( point );
  416. isFirstPoint = true;
  417. }
  418. break;
  419. default:
  420. console.warn( command );
  421. }
  422. // console.log( type, parseFloats( data ), parseFloats( data ).length )
  423. doSetFirstPoint = false;
  424. }
  425. return path;
  426. }
  427. function parseCSSStylesheet( node ) {
  428. if ( ! node.sheet || ! node.sheet.cssRules || ! node.sheet.cssRules.length ) return;
  429. for ( let i = 0; i < node.sheet.cssRules.length; i ++ ) {
  430. const stylesheet = node.sheet.cssRules[ i ];
  431. if ( stylesheet.type !== 1 ) continue;
  432. const selectorList = stylesheet.selectorText
  433. .split( /,/gm )
  434. .filter( Boolean )
  435. .map( i => i.trim() );
  436. for ( let j = 0; j < selectorList.length; j ++ ) {
  437. stylesheets[ selectorList[ j ] ] = Object.assign(
  438. stylesheets[ selectorList[ j ] ] || {},
  439. stylesheet.style
  440. );
  441. }
  442. }
  443. }
  444. /**
  445. * https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
  446. * https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion
  447. * From
  448. * rx ry x-axis-rotation large-arc-flag sweep-flag x y
  449. * To
  450. * aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation
  451. */
  452. function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) {
  453. if ( rx == 0 || ry == 0 ) {
  454. // draw a line if either of the radii == 0
  455. path.lineTo( end.x, end.y );
  456. return;
  457. }
  458. x_axis_rotation = x_axis_rotation * Math.PI / 180;
  459. // Ensure radii are positive
  460. rx = Math.abs( rx );
  461. ry = Math.abs( ry );
  462. // Compute (x1', y1')
  463. const dx2 = ( start.x - end.x ) / 2.0;
  464. const dy2 = ( start.y - end.y ) / 2.0;
  465. const x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2;
  466. const y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2;
  467. // Compute (cx', cy')
  468. let rxs = rx * rx;
  469. let rys = ry * ry;
  470. const x1ps = x1p * x1p;
  471. const y1ps = y1p * y1p;
  472. // Ensure radii are large enough
  473. const cr = x1ps / rxs + y1ps / rys;
  474. if ( cr > 1 ) {
  475. // scale up rx,ry equally so cr == 1
  476. const s = Math.sqrt( cr );
  477. rx = s * rx;
  478. ry = s * ry;
  479. rxs = rx * rx;
  480. rys = ry * ry;
  481. }
  482. const dq = ( rxs * y1ps + rys * x1ps );
  483. const pq = ( rxs * rys - dq ) / dq;
  484. let q = Math.sqrt( Math.max( 0, pq ) );
  485. if ( large_arc_flag === sweep_flag ) q = - q;
  486. const cxp = q * rx * y1p / ry;
  487. const cyp = - q * ry * x1p / rx;
  488. // Step 3: Compute (cx, cy) from (cx', cy')
  489. const cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;
  490. const cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;
  491. // Step 4: Compute θ1 and Δθ
  492. const theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );
  493. const delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );
  494. path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation );
  495. }
  496. function svgAngle( ux, uy, vx, vy ) {
  497. const dot = ux * vx + uy * vy;
  498. const len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy );
  499. let ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear
  500. if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang;
  501. return ang;
  502. }
  503. /*
  504. * According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute
  505. * rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough
  506. */
  507. function parseRectNode( node ) {
  508. const x = parseFloatWithUnits( node.getAttribute( 'x' ) || 0 );
  509. const y = parseFloatWithUnits( node.getAttribute( 'y' ) || 0 );
  510. const rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || node.getAttribute( 'ry' ) || 0 );
  511. const ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || node.getAttribute( 'rx' ) || 0 );
  512. const w = parseFloatWithUnits( node.getAttribute( 'width' ) );
  513. const h = parseFloatWithUnits( node.getAttribute( 'height' ) );
  514. // Ellipse arc to Bezier approximation Coefficient (Inversed). See:
  515. // https://spencermortensen.com/articles/bezier-circle/
  516. const bci = 1 - 0.551915024494;
  517. const path = new ShapePath();
  518. // top left
  519. path.moveTo( x + rx, y );
  520. // top right
  521. path.lineTo( x + w - rx, y );
  522. if ( rx !== 0 || ry !== 0 ) {
  523. path.bezierCurveTo(
  524. x + w - rx * bci,
  525. y,
  526. x + w,
  527. y + ry * bci,
  528. x + w,
  529. y + ry
  530. );
  531. }
  532. // bottom right
  533. path.lineTo( x + w, y + h - ry );
  534. if ( rx !== 0 || ry !== 0 ) {
  535. path.bezierCurveTo(
  536. x + w,
  537. y + h - ry * bci,
  538. x + w - rx * bci,
  539. y + h,
  540. x + w - rx,
  541. y + h
  542. );
  543. }
  544. // bottom left
  545. path.lineTo( x + rx, y + h );
  546. if ( rx !== 0 || ry !== 0 ) {
  547. path.bezierCurveTo(
  548. x + rx * bci,
  549. y + h,
  550. x,
  551. y + h - ry * bci,
  552. x,
  553. y + h - ry
  554. );
  555. }
  556. // back to top left
  557. path.lineTo( x, y + ry );
  558. if ( rx !== 0 || ry !== 0 ) {
  559. path.bezierCurveTo( x, y + ry * bci, x + rx * bci, y, x + rx, y );
  560. }
  561. return path;
  562. }
  563. function parsePolygonNode( node ) {
  564. function iterator( match, a, b ) {
  565. const x = parseFloatWithUnits( a );
  566. const y = parseFloatWithUnits( b );
  567. if ( index === 0 ) {
  568. path.moveTo( x, y );
  569. } else {
  570. path.lineTo( x, y );
  571. }
  572. index ++;
  573. }
  574. const regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
  575. const path = new ShapePath();
  576. let index = 0;
  577. node.getAttribute( 'points' ).replace( regex, iterator );
  578. path.currentPath.autoClose = true;
  579. return path;
  580. }
  581. function parsePolylineNode( node ) {
  582. function iterator( match, a, b ) {
  583. const x = parseFloatWithUnits( a );
  584. const y = parseFloatWithUnits( b );
  585. if ( index === 0 ) {
  586. path.moveTo( x, y );
  587. } else {
  588. path.lineTo( x, y );
  589. }
  590. index ++;
  591. }
  592. const regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g;
  593. const path = new ShapePath();
  594. let index = 0;
  595. node.getAttribute( 'points' ).replace( regex, iterator );
  596. path.currentPath.autoClose = false;
  597. return path;
  598. }
  599. function parseCircleNode( node ) {
  600. const x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
  601. const y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
  602. const r = parseFloatWithUnits( node.getAttribute( 'r' ) || 0 );
  603. const subpath = new Path();
  604. subpath.absarc( x, y, r, 0, Math.PI * 2 );
  605. const path = new ShapePath();
  606. path.subPaths.push( subpath );
  607. return path;
  608. }
  609. function parseEllipseNode( node ) {
  610. const x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
  611. const y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
  612. const rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 );
  613. const ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 );
  614. const subpath = new Path();
  615. subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2 );
  616. const path = new ShapePath();
  617. path.subPaths.push( subpath );
  618. return path;
  619. }
  620. function parseLineNode( node ) {
  621. const x1 = parseFloatWithUnits( node.getAttribute( 'x1' ) || 0 );
  622. const y1 = parseFloatWithUnits( node.getAttribute( 'y1' ) || 0 );
  623. const x2 = parseFloatWithUnits( node.getAttribute( 'x2' ) || 0 );
  624. const y2 = parseFloatWithUnits( node.getAttribute( 'y2' ) || 0 );
  625. const path = new ShapePath();
  626. path.moveTo( x1, y1 );
  627. path.lineTo( x2, y2 );
  628. path.currentPath.autoClose = false;
  629. return path;
  630. }
  631. //
  632. function parseStyle( node, style ) {
  633. style = Object.assign( {}, style ); // clone style
  634. let stylesheetStyles = {};
  635. if ( node.hasAttribute( 'class' ) ) {
  636. const classSelectors = node.getAttribute( 'class' )
  637. .split( /\s/ )
  638. .filter( Boolean )
  639. .map( i => i.trim() );
  640. for ( let i = 0; i < classSelectors.length; i ++ ) {
  641. stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '.' + classSelectors[ i ] ] );
  642. }
  643. }
  644. if ( node.hasAttribute( 'id' ) ) {
  645. stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '#' + node.getAttribute( 'id' ) ] );
  646. }
  647. function addStyle( svgName, jsName, adjustFunction ) {
  648. if ( adjustFunction === undefined ) adjustFunction = function copy( v ) {
  649. if ( v.startsWith( 'url' ) ) console.warn( 'SVGLoader: url access in attributes is not implemented.' );
  650. return v;
  651. };
  652. if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) );
  653. if ( stylesheetStyles[ svgName ] ) style[ jsName ] = adjustFunction( stylesheetStyles[ svgName ] );
  654. if ( node.style && node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] );
  655. }
  656. function clamp( v ) {
  657. return Math.max( 0, Math.min( 1, parseFloatWithUnits( v ) ) );
  658. }
  659. function positive( v ) {
  660. return Math.max( 0, parseFloatWithUnits( v ) );
  661. }
  662. addStyle( 'fill', 'fill' );
  663. addStyle( 'fill-opacity', 'fillOpacity', clamp );
  664. addStyle( 'opacity', 'opacity', clamp );
  665. addStyle( 'stroke', 'stroke' );
  666. addStyle( 'stroke-opacity', 'strokeOpacity', clamp );
  667. addStyle( 'stroke-width', 'strokeWidth', positive );
  668. addStyle( 'stroke-linejoin', 'strokeLineJoin' );
  669. addStyle( 'stroke-linecap', 'strokeLineCap' );
  670. addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive );
  671. addStyle( 'visibility', 'visibility' );
  672. return style;
  673. }
  674. // http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
  675. function getReflection( a, b ) {
  676. return a - ( b - a );
  677. }
  678. // from https://github.com/ppvg/svg-numbers (MIT License)
  679. function parseFloats( input, flags, stride ) {
  680. if ( typeof input !== 'string' ) {
  681. throw new TypeError( 'Invalid input: ' + typeof input );
  682. }
  683. // Character groups
  684. const RE = {
  685. SEPARATOR: /[ \t\r\n\,.\-+]/,
  686. WHITESPACE: /[ \t\r\n]/,
  687. DIGIT: /[\d]/,
  688. SIGN: /[-+]/,
  689. POINT: /\./,
  690. COMMA: /,/,
  691. EXP: /e/i,
  692. FLAGS: /[01]/
  693. };
  694. // States
  695. const SEP = 0;
  696. const INT = 1;
  697. const FLOAT = 2;
  698. const EXP = 3;
  699. let state = SEP;
  700. let seenComma = true;
  701. let number = '', exponent = '';
  702. const result = [];
  703. function throwSyntaxError( current, i, partial ) {
  704. const error = new SyntaxError( 'Unexpected character "' + current + '" at index ' + i + '.' );
  705. error.partial = partial;
  706. throw error;
  707. }
  708. function newNumber() {
  709. if ( number !== '' ) {
  710. if ( exponent === '' ) result.push( Number( number ) );
  711. else result.push( Number( number ) * Math.pow( 10, Number( exponent ) ) );
  712. }
  713. number = '';
  714. exponent = '';
  715. }
  716. let current;
  717. const length = input.length;
  718. for ( let i = 0; i < length; i ++ ) {
  719. current = input[ i ];
  720. // check for flags
  721. if ( Array.isArray( flags ) && flags.includes( result.length % stride ) && RE.FLAGS.test( current ) ) {
  722. state = INT;
  723. number = current;
  724. newNumber();
  725. continue;
  726. }
  727. // parse until next number
  728. if ( state === SEP ) {
  729. // eat whitespace
  730. if ( RE.WHITESPACE.test( current ) ) {
  731. continue;
  732. }
  733. // start new number
  734. if ( RE.DIGIT.test( current ) || RE.SIGN.test( current ) ) {
  735. state = INT;
  736. number = current;
  737. continue;
  738. }
  739. if ( RE.POINT.test( current ) ) {
  740. state = FLOAT;
  741. number = current;
  742. continue;
  743. }
  744. // throw on double commas (e.g. "1, , 2")
  745. if ( RE.COMMA.test( current ) ) {
  746. if ( seenComma ) {
  747. throwSyntaxError( current, i, result );
  748. }
  749. seenComma = true;
  750. }
  751. }
  752. // parse integer part
  753. if ( state === INT ) {
  754. if ( RE.DIGIT.test( current ) ) {
  755. number += current;
  756. continue;
  757. }
  758. if ( RE.POINT.test( current ) ) {
  759. number += current;
  760. state = FLOAT;
  761. continue;
  762. }
  763. if ( RE.EXP.test( current ) ) {
  764. state = EXP;
  765. continue;
  766. }
  767. // throw on double signs ("-+1"), but not on sign as separator ("-1-2")
  768. if ( RE.SIGN.test( current )
  769. && number.length === 1
  770. && RE.SIGN.test( number[ 0 ] ) ) {
  771. throwSyntaxError( current, i, result );
  772. }
  773. }
  774. // parse decimal part
  775. if ( state === FLOAT ) {
  776. if ( RE.DIGIT.test( current ) ) {
  777. number += current;
  778. continue;
  779. }
  780. if ( RE.EXP.test( current ) ) {
  781. state = EXP;
  782. continue;
  783. }
  784. // throw on double decimal points (e.g. "1..2")
  785. if ( RE.POINT.test( current ) && number[ number.length - 1 ] === '.' ) {
  786. throwSyntaxError( current, i, result );
  787. }
  788. }
  789. // parse exponent part
  790. if ( state === EXP ) {
  791. if ( RE.DIGIT.test( current ) ) {
  792. exponent += current;
  793. continue;
  794. }
  795. if ( RE.SIGN.test( current ) ) {
  796. if ( exponent === '' ) {
  797. exponent += current;
  798. continue;
  799. }
  800. if ( exponent.length === 1 && RE.SIGN.test( exponent ) ) {
  801. throwSyntaxError( current, i, result );
  802. }
  803. }
  804. }
  805. // end of number
  806. if ( RE.WHITESPACE.test( current ) ) {
  807. newNumber();
  808. state = SEP;
  809. seenComma = false;
  810. } else if ( RE.COMMA.test( current ) ) {
  811. newNumber();
  812. state = SEP;
  813. seenComma = true;
  814. } else if ( RE.SIGN.test( current ) ) {
  815. newNumber();
  816. state = INT;
  817. number = current;
  818. } else if ( RE.POINT.test( current ) ) {
  819. newNumber();
  820. state = FLOAT;
  821. number = current;
  822. } else {
  823. throwSyntaxError( current, i, result );
  824. }
  825. }
  826. // add the last number found (if any)
  827. newNumber();
  828. return result;
  829. }
  830. // Units
  831. const units = [ 'mm', 'cm', 'in', 'pt', 'pc', 'px' ];
  832. // Conversion: [ fromUnit ][ toUnit ] (-1 means dpi dependent)
  833. const unitConversion = {
  834. 'mm': {
  835. 'mm': 1,
  836. 'cm': 0.1,
  837. 'in': 1 / 25.4,
  838. 'pt': 72 / 25.4,
  839. 'pc': 6 / 25.4,
  840. 'px': - 1
  841. },
  842. 'cm': {
  843. 'mm': 10,
  844. 'cm': 1,
  845. 'in': 1 / 2.54,
  846. 'pt': 72 / 2.54,
  847. 'pc': 6 / 2.54,
  848. 'px': - 1
  849. },
  850. 'in': {
  851. 'mm': 25.4,
  852. 'cm': 2.54,
  853. 'in': 1,
  854. 'pt': 72,
  855. 'pc': 6,
  856. 'px': - 1
  857. },
  858. 'pt': {
  859. 'mm': 25.4 / 72,
  860. 'cm': 2.54 / 72,
  861. 'in': 1 / 72,
  862. 'pt': 1,
  863. 'pc': 6 / 72,
  864. 'px': - 1
  865. },
  866. 'pc': {
  867. 'mm': 25.4 / 6,
  868. 'cm': 2.54 / 6,
  869. 'in': 1 / 6,
  870. 'pt': 72 / 6,
  871. 'pc': 1,
  872. 'px': - 1
  873. },
  874. 'px': {
  875. 'px': 1
  876. }
  877. };
  878. function parseFloatWithUnits( string ) {
  879. let theUnit = 'px';
  880. if ( typeof string === 'string' || string instanceof String ) {
  881. for ( let i = 0, n = units.length; i < n; i ++ ) {
  882. const u = units[ i ];
  883. if ( string.endsWith( u ) ) {
  884. theUnit = u;
  885. string = string.substring( 0, string.length - u.length );
  886. break;
  887. }
  888. }
  889. }
  890. let scale = undefined;
  891. if ( theUnit === 'px' && scope.defaultUnit !== 'px' ) {
  892. // Conversion scale from pixels to inches, then to default units
  893. scale = unitConversion[ 'in' ][ scope.defaultUnit ] / scope.defaultDPI;
  894. } else {
  895. scale = unitConversion[ theUnit ][ scope.defaultUnit ];
  896. if ( scale < 0 ) {
  897. // Conversion scale to pixels
  898. scale = unitConversion[ theUnit ][ 'in' ] * scope.defaultDPI;
  899. }
  900. }
  901. return scale * parseFloat( string );
  902. }
  903. // Transforms
  904. function getNodeTransform( node ) {
  905. if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) {
  906. return null;
  907. }
  908. const transform = parseNodeTransform( node );
  909. if ( transformStack.length > 0 ) {
  910. transform.premultiply( transformStack[ transformStack.length - 1 ] );
  911. }
  912. currentTransform.copy( transform );
  913. transformStack.push( transform );
  914. return transform;
  915. }
  916. function parseNodeTransform( node ) {
  917. const transform = new Matrix3();
  918. const currentTransform = tempTransform0;
  919. if ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) {
  920. const tx = parseFloatWithUnits( node.getAttribute( 'x' ) );
  921. const ty = parseFloatWithUnits( node.getAttribute( 'y' ) );
  922. transform.translate( tx, ty );
  923. }
  924. if ( node.hasAttribute( 'transform' ) ) {
  925. const transformsTexts = node.getAttribute( 'transform' ).split( ')' );
  926. for ( let tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) {
  927. const transformText = transformsTexts[ tIndex ].trim();
  928. if ( transformText === '' ) continue;
  929. const openParPos = transformText.indexOf( '(' );
  930. const closeParPos = transformText.length;
  931. if ( openParPos > 0 && openParPos < closeParPos ) {
  932. const transformType = transformText.substr( 0, openParPos );
  933. const array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) );
  934. currentTransform.identity();
  935. switch ( transformType ) {
  936. case 'translate':
  937. if ( array.length >= 1 ) {
  938. const tx = array[ 0 ];
  939. let ty = tx;
  940. if ( array.length >= 2 ) {
  941. ty = array[ 1 ];
  942. }
  943. currentTransform.translate( tx, ty );
  944. }
  945. break;
  946. case 'rotate':
  947. if ( array.length >= 1 ) {
  948. let angle = 0;
  949. let cx = 0;
  950. let cy = 0;
  951. // Angle
  952. angle = - array[ 0 ] * Math.PI / 180;
  953. if ( array.length >= 3 ) {
  954. // Center x, y
  955. cx = array[ 1 ];
  956. cy = array[ 2 ];
  957. }
  958. // Rotate around center (cx, cy)
  959. tempTransform1.identity().translate( - cx, - cy );
  960. tempTransform2.identity().rotate( angle );
  961. tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 );
  962. tempTransform1.identity().translate( cx, cy );
  963. currentTransform.multiplyMatrices( tempTransform1, tempTransform3 );
  964. }
  965. break;
  966. case 'scale':
  967. if ( array.length >= 1 ) {
  968. const scaleX = array[ 0 ];
  969. let scaleY = scaleX;
  970. if ( array.length >= 2 ) {
  971. scaleY = array[ 1 ];
  972. }
  973. currentTransform.scale( scaleX, scaleY );
  974. }
  975. break;
  976. case 'skewX':
  977. if ( array.length === 1 ) {
  978. currentTransform.set(
  979. 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0,
  980. 0, 1, 0,
  981. 0, 0, 1
  982. );
  983. }
  984. break;
  985. case 'skewY':
  986. if ( array.length === 1 ) {
  987. currentTransform.set(
  988. 1, 0, 0,
  989. Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0,
  990. 0, 0, 1
  991. );
  992. }
  993. break;
  994. case 'matrix':
  995. if ( array.length === 6 ) {
  996. currentTransform.set(
  997. array[ 0 ], array[ 2 ], array[ 4 ],
  998. array[ 1 ], array[ 3 ], array[ 5 ],
  999. 0, 0, 1
  1000. );
  1001. }
  1002. break;
  1003. }
  1004. }
  1005. transform.premultiply( currentTransform );
  1006. }
  1007. }
  1008. return transform;
  1009. }
  1010. function transformPath( path, m ) {
  1011. function transfVec2( v2 ) {
  1012. tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m );
  1013. v2.set( tempV3.x, tempV3.y );
  1014. }
  1015. const isRotated = isTransformRotated( m );
  1016. const subPaths = path.subPaths;
  1017. for ( let i = 0, n = subPaths.length; i < n; i ++ ) {
  1018. const subPath = subPaths[ i ];
  1019. const curves = subPath.curves;
  1020. for ( let j = 0; j < curves.length; j ++ ) {
  1021. const curve = curves[ j ];
  1022. if ( curve.isLineCurve ) {
  1023. transfVec2( curve.v1 );
  1024. transfVec2( curve.v2 );
  1025. } else if ( curve.isCubicBezierCurve ) {
  1026. transfVec2( curve.v0 );
  1027. transfVec2( curve.v1 );
  1028. transfVec2( curve.v2 );
  1029. transfVec2( curve.v3 );
  1030. } else if ( curve.isQuadraticBezierCurve ) {
  1031. transfVec2( curve.v0 );
  1032. transfVec2( curve.v1 );
  1033. transfVec2( curve.v2 );
  1034. } else if ( curve.isEllipseCurve ) {
  1035. if ( isRotated ) {
  1036. console.warn( 'SVGLoader: Elliptic arc or ellipse rotation or skewing is not implemented.' );
  1037. }
  1038. tempV2.set( curve.aX, curve.aY );
  1039. transfVec2( tempV2 );
  1040. curve.aX = tempV2.x;
  1041. curve.aY = tempV2.y;
  1042. curve.xRadius *= getTransformScaleX( m );
  1043. curve.yRadius *= getTransformScaleY( m );
  1044. }
  1045. }
  1046. }
  1047. }
  1048. function isTransformRotated( m ) {
  1049. return m.elements[ 1 ] !== 0 || m.elements[ 3 ] !== 0;
  1050. }
  1051. function getTransformScaleX( m ) {
  1052. const te = m.elements;
  1053. return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] );
  1054. }
  1055. function getTransformScaleY( m ) {
  1056. const te = m.elements;
  1057. return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] );
  1058. }
  1059. //
  1060. const paths = [];
  1061. const stylesheets = {};
  1062. const transformStack = [];
  1063. const tempTransform0 = new Matrix3();
  1064. const tempTransform1 = new Matrix3();
  1065. const tempTransform2 = new Matrix3();
  1066. const tempTransform3 = new Matrix3();
  1067. const tempV2 = new Vector2();
  1068. const tempV3 = new Vector3();
  1069. const currentTransform = new Matrix3();
  1070. const xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml
  1071. parseNode( xml.documentElement, {
  1072. fill: '#000',
  1073. fillOpacity: 1,
  1074. strokeOpacity: 1,
  1075. strokeWidth: 1,
  1076. strokeLineJoin: 'miter',
  1077. strokeLineCap: 'butt',
  1078. strokeMiterLimit: 4
  1079. } );
  1080. const data = { paths: paths, xml: xml.documentElement };
  1081. // console.log( paths );
  1082. return data;
  1083. }
  1084. static createShapes( shapePath ) {
  1085. // Param shapePath: a shapepath as returned by the parse function of this class
  1086. // Returns Shape object
  1087. const BIGNUMBER = 999999999;
  1088. const IntersectionLocationType = {
  1089. ORIGIN: 0,
  1090. DESTINATION: 1,
  1091. BETWEEN: 2,
  1092. LEFT: 3,
  1093. RIGHT: 4,
  1094. BEHIND: 5,
  1095. BEYOND: 6
  1096. };
  1097. const classifyResult = {
  1098. loc: IntersectionLocationType.ORIGIN,
  1099. t: 0
  1100. };
  1101. function findEdgeIntersection( a0, a1, b0, b1 ) {
  1102. const x1 = a0.x;
  1103. const x2 = a1.x;
  1104. const x3 = b0.x;
  1105. const x4 = b1.x;
  1106. const y1 = a0.y;
  1107. const y2 = a1.y;
  1108. const y3 = b0.y;
  1109. const y4 = b1.y;
  1110. const nom1 = ( x4 - x3 ) * ( y1 - y3 ) - ( y4 - y3 ) * ( x1 - x3 );
  1111. const nom2 = ( x2 - x1 ) * ( y1 - y3 ) - ( y2 - y1 ) * ( x1 - x3 );
  1112. const denom = ( y4 - y3 ) * ( x2 - x1 ) - ( x4 - x3 ) * ( y2 - y1 );
  1113. const t1 = nom1 / denom;
  1114. const t2 = nom2 / denom;
  1115. if ( ( ( denom === 0 ) && ( nom1 !== 0 ) ) || ( t1 <= 0 ) || ( t1 >= 1 ) || ( t2 < 0 ) || ( t2 > 1 ) ) {
  1116. //1. lines are parallel or edges don't intersect
  1117. return null;
  1118. } else if ( ( nom1 === 0 ) && ( denom === 0 ) ) {
  1119. //2. lines are colinear
  1120. //check if endpoints of edge2 (b0-b1) lies on edge1 (a0-a1)
  1121. for ( let i = 0; i < 2; i ++ ) {
  1122. classifyPoint( i === 0 ? b0 : b1, a0, a1 );
  1123. //find position of this endpoints relatively to edge1
  1124. if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) {
  1125. const point = ( i === 0 ? b0 : b1 );
  1126. return { x: point.x, y: point.y, t: classifyResult.t };
  1127. } else if ( classifyResult.loc == IntersectionLocationType.BETWEEN ) {
  1128. const x = + ( ( x1 + classifyResult.t * ( x2 - x1 ) ).toPrecision( 10 ) );
  1129. const y = + ( ( y1 + classifyResult.t * ( y2 - y1 ) ).toPrecision( 10 ) );
  1130. return { x: x, y: y, t: classifyResult.t, };
  1131. }
  1132. }
  1133. return null;
  1134. } else {
  1135. //3. edges intersect
  1136. for ( let i = 0; i < 2; i ++ ) {
  1137. classifyPoint( i === 0 ? b0 : b1, a0, a1 );
  1138. if ( classifyResult.loc == IntersectionLocationType.ORIGIN ) {
  1139. const point = ( i === 0 ? b0 : b1 );
  1140. return { x: point.x, y: point.y, t: classifyResult.t };
  1141. }
  1142. }
  1143. const x = + ( ( x1 + t1 * ( x2 - x1 ) ).toPrecision( 10 ) );
  1144. const y = + ( ( y1 + t1 * ( y2 - y1 ) ).toPrecision( 10 ) );
  1145. return { x: x, y: y, t: t1 };
  1146. }
  1147. }
  1148. function classifyPoint( p, edgeStart, edgeEnd ) {
  1149. const ax = edgeEnd.x - edgeStart.x;
  1150. const ay = edgeEnd.y - edgeStart.y;
  1151. const bx = p.x - edgeStart.x;
  1152. const by = p.y - edgeStart.y;
  1153. const sa = ax * by - bx * ay;
  1154. if ( ( p.x === edgeStart.x ) && ( p.y === edgeStart.y ) ) {
  1155. classifyResult.loc = IntersectionLocationType.ORIGIN;
  1156. classifyResult.t = 0;
  1157. return;
  1158. }
  1159. if ( ( p.x === edgeEnd.x ) && ( p.y === edgeEnd.y ) ) {
  1160. classifyResult.loc = IntersectionLocationType.DESTINATION;
  1161. classifyResult.t = 1;
  1162. return;
  1163. }
  1164. if ( sa < - Number.EPSILON ) {
  1165. classifyResult.loc = IntersectionLocationType.LEFT;
  1166. return;
  1167. }
  1168. if ( sa > Number.EPSILON ) {
  1169. classifyResult.loc = IntersectionLocationType.RIGHT;
  1170. return;
  1171. }
  1172. if ( ( ( ax * bx ) < 0 ) || ( ( ay * by ) < 0 ) ) {
  1173. classifyResult.loc = IntersectionLocationType.BEHIND;
  1174. return;
  1175. }
  1176. if ( ( Math.sqrt( ax * ax + ay * ay ) ) < ( Math.sqrt( bx * bx + by * by ) ) ) {
  1177. classifyResult.loc = IntersectionLocationType.BEYOND;
  1178. return;
  1179. }
  1180. let t;
  1181. if ( ax !== 0 ) {
  1182. t = bx / ax;
  1183. } else {
  1184. t = by / ay;
  1185. }
  1186. classifyResult.loc = IntersectionLocationType.BETWEEN;
  1187. classifyResult.t = t;
  1188. }
  1189. function getIntersections( path1, path2 ) {
  1190. const intersectionsRaw = [];
  1191. const intersections = [];
  1192. for ( let index = 1; index < path1.length; index ++ ) {
  1193. const path1EdgeStart = path1[ index - 1 ];
  1194. const path1EdgeEnd = path1[ index ];
  1195. for ( let index2 = 1; index2 < path2.length; index2 ++ ) {
  1196. const path2EdgeStart = path2[ index2 - 1 ];
  1197. const path2EdgeEnd = path2[ index2 ];
  1198. const intersection = findEdgeIntersection( path1EdgeStart, path1EdgeEnd, path2EdgeStart, path2EdgeEnd );
  1199. if ( intersection !== null && intersectionsRaw.find( i => i.t <= intersection.t + Number.EPSILON && i.t >= intersection.t - Number.EPSILON ) === undefined ) {
  1200. intersectionsRaw.push( intersection );
  1201. intersections.push( new Vector2( intersection.x, intersection.y ) );
  1202. }
  1203. }
  1204. }
  1205. return intersections;
  1206. }
  1207. function getScanlineIntersections( scanline, boundingBox, paths ) {
  1208. const center = new Vector2();
  1209. boundingBox.getCenter( center );
  1210. const allIntersections = [];
  1211. paths.forEach( path => {
  1212. // check if the center of the bounding box is in the bounding box of the paths.
  1213. // this is a pruning method to limit the search of intersections in paths that can't envelop of the current path.
  1214. // if a path envelops another path. The center of that oter path, has to be inside the bounding box of the enveloping path.
  1215. if ( path.boundingBox.containsPoint( center ) ) {
  1216. const intersections = getIntersections( scanline, path.points );
  1217. intersections.forEach( p => {
  1218. allIntersections.push( { identifier: path.identifier, isCW: path.isCW, point: p } );
  1219. } );
  1220. }
  1221. } );
  1222. allIntersections.sort( ( i1, i2 ) => {
  1223. return i1.point.x - i2.point.x;
  1224. } );
  1225. return allIntersections;
  1226. }
  1227. function isHoleTo( simplePath, allPaths, scanlineMinX, scanlineMaxX, _fillRule ) {
  1228. if ( _fillRule === null || _fillRule === undefined || _fillRule === '' ) {
  1229. _fillRule = 'nonzero';
  1230. }
  1231. const centerBoundingBox = new Vector2();
  1232. simplePath.boundingBox.getCenter( centerBoundingBox );
  1233. const scanline = [ new Vector2( scanlineMinX, centerBoundingBox.y ), new Vector2( scanlineMaxX, centerBoundingBox.y ) ];
  1234. const scanlineIntersections = getScanlineIntersections( scanline, simplePath.boundingBox, allPaths );
  1235. scanlineIntersections.sort( ( i1, i2 ) => {
  1236. return i1.point.x - i2.point.x;
  1237. } );
  1238. const baseIntersections = [];
  1239. const otherIntersections = [];
  1240. scanlineIntersections.forEach( i => {
  1241. if ( i.identifier === simplePath.identifier ) {
  1242. baseIntersections.push( i );
  1243. } else {
  1244. otherIntersections.push( i );
  1245. }
  1246. } );
  1247. const firstXOfPath = baseIntersections[ 0 ].point.x;
  1248. // build up the path hierarchy
  1249. const stack = [];
  1250. let i = 0;
  1251. while ( i < otherIntersections.length && otherIntersections[ i ].point.x < firstXOfPath ) {
  1252. if ( stack.length > 0 && stack[ stack.length - 1 ] === otherIntersections[ i ].identifier ) {
  1253. stack.pop();
  1254. } else {
  1255. stack.push( otherIntersections[ i ].identifier );
  1256. }
  1257. i ++;
  1258. }
  1259. stack.push( simplePath.identifier );
  1260. if ( _fillRule === 'evenodd' ) {
  1261. const isHole = stack.length % 2 === 0 ? true : false;
  1262. const isHoleFor = stack[ stack.length - 2 ];
  1263. return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor };
  1264. } else if ( _fillRule === 'nonzero' ) {
  1265. // check if path is a hole by counting the amount of paths with alternating rotations it has to cross.
  1266. let isHole = true;
  1267. let isHoleFor = null;
  1268. let lastCWValue = null;
  1269. for ( let i = 0; i < stack.length; i ++ ) {
  1270. const identifier = stack[ i ];
  1271. if ( isHole ) {
  1272. lastCWValue = allPaths[ identifier ].isCW;
  1273. isHole = false;
  1274. isHoleFor = identifier;
  1275. } else if ( lastCWValue !== allPaths[ identifier ].isCW ) {
  1276. lastCWValue = allPaths[ identifier ].isCW;
  1277. isHole = true;
  1278. }
  1279. }
  1280. return { identifier: simplePath.identifier, isHole: isHole, for: isHoleFor };
  1281. } else {
  1282. console.warn( 'fill-rule: "' + _fillRule + '" is currently not implemented.' );
  1283. }
  1284. }
  1285. // check for self intersecting paths
  1286. // TODO
  1287. // check intersecting paths
  1288. // TODO
  1289. // prepare paths for hole detection
  1290. let identifier = 0;
  1291. let scanlineMinX = BIGNUMBER;
  1292. let scanlineMaxX = - BIGNUMBER;
  1293. let simplePaths = shapePath.subPaths.map( p => {
  1294. const points = p.getPoints();
  1295. let maxY = - BIGNUMBER;
  1296. let minY = BIGNUMBER;
  1297. let maxX = - BIGNUMBER;
  1298. let minX = BIGNUMBER;
  1299. //points.forEach(p => p.y *= -1);
  1300. for ( let i = 0; i < points.length; i ++ ) {
  1301. const p = points[ i ];
  1302. if ( p.y > maxY ) {
  1303. maxY = p.y;
  1304. }
  1305. if ( p.y < minY ) {
  1306. minY = p.y;
  1307. }
  1308. if ( p.x > maxX ) {
  1309. maxX = p.x;
  1310. }
  1311. if ( p.x < minX ) {
  1312. minX = p.x;
  1313. }
  1314. }
  1315. //
  1316. if ( scanlineMaxX <= maxX ) {
  1317. scanlineMaxX = maxX + 1;
  1318. }
  1319. if ( scanlineMinX >= minX ) {
  1320. scanlineMinX = minX - 1;
  1321. }
  1322. return { points: points, isCW: ShapeUtils.isClockWise( points ), identifier: identifier ++, boundingBox: new Box2( new Vector2( minX, minY ), new Vector2( maxX, maxY ) ) };
  1323. } );
  1324. simplePaths = simplePaths.filter( sp => sp.points.length > 1 );
  1325. // check if path is solid or a hole
  1326. const isAHole = simplePaths.map( p => isHoleTo( p, simplePaths, scanlineMinX, scanlineMaxX, shapePath.userData.style.fillRule ) );
  1327. const shapesToReturn = [];
  1328. simplePaths.forEach( p => {
  1329. const amIAHole = isAHole[ p.identifier ];
  1330. if ( ! amIAHole.isHole ) {
  1331. const shape = new Shape( p.points );
  1332. const holes = isAHole.filter( h => h.isHole && h.for === p.identifier );
  1333. holes.forEach( h => {
  1334. const path = simplePaths[ h.identifier ];
  1335. shape.holes.push( new Path( path.points ) );
  1336. } );
  1337. shapesToReturn.push( shape );
  1338. }
  1339. } );
  1340. return shapesToReturn;
  1341. }
  1342. static getStrokeStyle( width, color, lineJoin, lineCap, miterLimit ) {
  1343. // Param width: Stroke width
  1344. // Param color: As returned by THREE.Color.getStyle()
  1345. // Param lineJoin: One of "round", "bevel", "miter" or "miter-limit"
  1346. // Param lineCap: One of "round", "square" or "butt"
  1347. // Param miterLimit: Maximum join length, in multiples of the "width" parameter (join is truncated if it exceeds that distance)
  1348. // Returns style object
  1349. width = width !== undefined ? width : 1;
  1350. color = color !== undefined ? color : '#000';
  1351. lineJoin = lineJoin !== undefined ? lineJoin : 'miter';
  1352. lineCap = lineCap !== undefined ? lineCap : 'butt';
  1353. miterLimit = miterLimit !== undefined ? miterLimit : 4;
  1354. return {
  1355. strokeColor: color,
  1356. strokeWidth: width,
  1357. strokeLineJoin: lineJoin,
  1358. strokeLineCap: lineCap,
  1359. strokeMiterLimit: miterLimit
  1360. };
  1361. }
  1362. static pointsToStroke( points, style, arcDivisions, minDistance ) {
  1363. // Generates a stroke with some witdh around the given path.
  1364. // The path can be open or closed (last point equals to first point)
  1365. // Param points: Array of Vector2D (the path). Minimum 2 points.
  1366. // Param style: Object with SVG properties as returned by SVGLoader.getStrokeStyle(), or SVGLoader.parse() in the path.userData.style object
  1367. // Params arcDivisions: Arc divisions for round joins and endcaps. (Optional)
  1368. // Param minDistance: Points closer to this distance will be merged. (Optional)
  1369. // Returns BufferGeometry with stroke triangles (In plane z = 0). UV coordinates are generated ('u' along path. 'v' across it, from left to right)
  1370. const vertices = [];
  1371. const normals = [];
  1372. const uvs = [];
  1373. if ( SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) {
  1374. return null;
  1375. }
  1376. const geometry = new BufferGeometry();
  1377. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  1378. geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  1379. geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  1380. return geometry;
  1381. }
  1382. static pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset ) {
  1383. // This function can be called to update existing arrays or buffers.
  1384. // Accepts same parameters as pointsToStroke, plus the buffers and optional offset.
  1385. // Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs)
  1386. // Returns number of written vertices / normals / uvs pairs
  1387. // if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers)
  1388. // 'normals' and 'uvs' buffers are optional
  1389. const tempV2_1 = new Vector2();
  1390. const tempV2_2 = new Vector2();
  1391. const tempV2_3 = new Vector2();
  1392. const tempV2_4 = new Vector2();
  1393. const tempV2_5 = new Vector2();
  1394. const tempV2_6 = new Vector2();
  1395. const tempV2_7 = new Vector2();
  1396. const lastPointL = new Vector2();
  1397. const lastPointR = new Vector2();
  1398. const point0L = new Vector2();
  1399. const point0R = new Vector2();
  1400. const currentPointL = new Vector2();
  1401. const currentPointR = new Vector2();
  1402. const nextPointL = new Vector2();
  1403. const nextPointR = new Vector2();
  1404. const innerPoint = new Vector2();
  1405. const outerPoint = new Vector2();
  1406. arcDivisions = arcDivisions !== undefined ? arcDivisions : 12;
  1407. minDistance = minDistance !== undefined ? minDistance : 0.001;
  1408. vertexOffset = vertexOffset !== undefined ? vertexOffset : 0;
  1409. // First ensure there are no duplicated points
  1410. points = removeDuplicatedPoints( points );
  1411. const numPoints = points.length;
  1412. if ( numPoints < 2 ) return 0;
  1413. const isClosed = points[ 0 ].equals( points[ numPoints - 1 ] );
  1414. let currentPoint;
  1415. let previousPoint = points[ 0 ];
  1416. let nextPoint;
  1417. const strokeWidth2 = style.strokeWidth / 2;
  1418. const deltaU = 1 / ( numPoints - 1 );
  1419. let u0 = 0, u1;
  1420. let innerSideModified;
  1421. let joinIsOnLeftSide;
  1422. let isMiter;
  1423. let initialJoinIsOnLeftSide = false;
  1424. let numVertices = 0;
  1425. let currentCoordinate = vertexOffset * 3;
  1426. let currentCoordinateUV = vertexOffset * 2;
  1427. // Get initial left and right stroke points
  1428. getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 );
  1429. lastPointL.copy( points[ 0 ] ).sub( tempV2_1 );
  1430. lastPointR.copy( points[ 0 ] ).add( tempV2_1 );
  1431. point0L.copy( lastPointL );
  1432. point0R.copy( lastPointR );
  1433. for ( let iPoint = 1; iPoint < numPoints; iPoint ++ ) {
  1434. currentPoint = points[ iPoint ];
  1435. // Get next point
  1436. if ( iPoint === numPoints - 1 ) {
  1437. if ( isClosed ) {
  1438. // Skip duplicated initial point
  1439. nextPoint = points[ 1 ];
  1440. } else nextPoint = undefined;
  1441. } else {
  1442. nextPoint = points[ iPoint + 1 ];
  1443. }
  1444. // Normal of previous segment in tempV2_1
  1445. const normal1 = tempV2_1;
  1446. getNormal( previousPoint, currentPoint, normal1 );
  1447. tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 );
  1448. currentPointL.copy( currentPoint ).sub( tempV2_3 );
  1449. currentPointR.copy( currentPoint ).add( tempV2_3 );
  1450. u1 = u0 + deltaU;
  1451. innerSideModified = false;
  1452. if ( nextPoint !== undefined ) {
  1453. // Normal of next segment in tempV2_2
  1454. getNormal( currentPoint, nextPoint, tempV2_2 );
  1455. tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 );
  1456. nextPointL.copy( currentPoint ).sub( tempV2_3 );
  1457. nextPointR.copy( currentPoint ).add( tempV2_3 );
  1458. joinIsOnLeftSide = true;
  1459. tempV2_3.subVectors( nextPoint, previousPoint );
  1460. if ( normal1.dot( tempV2_3 ) < 0 ) {
  1461. joinIsOnLeftSide = false;
  1462. }
  1463. if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide;
  1464. tempV2_3.subVectors( nextPoint, currentPoint );
  1465. tempV2_3.normalize();
  1466. const dot = Math.abs( normal1.dot( tempV2_3 ) );
  1467. // If path is straight, don't create join
  1468. if ( dot !== 0 ) {
  1469. // Compute inner and outer segment intersections
  1470. const miterSide = strokeWidth2 / dot;
  1471. tempV2_3.multiplyScalar( - miterSide );
  1472. tempV2_4.subVectors( currentPoint, previousPoint );
  1473. tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 );
  1474. innerPoint.copy( tempV2_5 ).negate();
  1475. const miterLength2 = tempV2_5.length();
  1476. const segmentLengthPrev = tempV2_4.length();
  1477. tempV2_4.divideScalar( segmentLengthPrev );
  1478. tempV2_6.subVectors( nextPoint, currentPoint );
  1479. const segmentLengthNext = tempV2_6.length();
  1480. tempV2_6.divideScalar( segmentLengthNext );
  1481. // Check that previous and next segments doesn't overlap with the innerPoint of intersection
  1482. if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) {
  1483. innerSideModified = true;
  1484. }
  1485. outerPoint.copy( tempV2_5 ).add( currentPoint );
  1486. innerPoint.add( currentPoint );
  1487. isMiter = false;
  1488. if ( innerSideModified ) {
  1489. if ( joinIsOnLeftSide ) {
  1490. nextPointR.copy( innerPoint );
  1491. currentPointR.copy( innerPoint );
  1492. } else {
  1493. nextPointL.copy( innerPoint );
  1494. currentPointL.copy( innerPoint );
  1495. }
  1496. } else {
  1497. // The segment triangles are generated here if there was overlapping
  1498. makeSegmentTriangles();
  1499. }
  1500. switch ( style.strokeLineJoin ) {
  1501. case 'bevel':
  1502. makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
  1503. break;
  1504. case 'round':
  1505. // Segment triangles
  1506. createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
  1507. // Join triangles
  1508. if ( joinIsOnLeftSide ) {
  1509. makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 );
  1510. } else {
  1511. makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 );
  1512. }
  1513. break;
  1514. case 'miter':
  1515. case 'miter-clip':
  1516. default:
  1517. const miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2;
  1518. if ( miterFraction < 1 ) {
  1519. // The join miter length exceeds the miter limit
  1520. if ( style.strokeLineJoin !== 'miter-clip' ) {
  1521. makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
  1522. break;
  1523. } else {
  1524. // Segment triangles
  1525. createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
  1526. // Miter-clip join triangles
  1527. if ( joinIsOnLeftSide ) {
  1528. tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL );
  1529. tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL );
  1530. addVertex( currentPointL, u1, 0 );
  1531. addVertex( tempV2_6, u1, 0 );
  1532. addVertex( currentPoint, u1, 0.5 );
  1533. addVertex( currentPoint, u1, 0.5 );
  1534. addVertex( tempV2_6, u1, 0 );
  1535. addVertex( tempV2_7, u1, 0 );
  1536. addVertex( currentPoint, u1, 0.5 );
  1537. addVertex( tempV2_7, u1, 0 );
  1538. addVertex( nextPointL, u1, 0 );
  1539. } else {
  1540. tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR );
  1541. tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR );
  1542. addVertex( currentPointR, u1, 1 );
  1543. addVertex( tempV2_6, u1, 1 );
  1544. addVertex( currentPoint, u1, 0.5 );
  1545. addVertex( currentPoint, u1, 0.5 );
  1546. addVertex( tempV2_6, u1, 1 );
  1547. addVertex( tempV2_7, u1, 1 );
  1548. addVertex( currentPoint, u1, 0.5 );
  1549. addVertex( tempV2_7, u1, 1 );
  1550. addVertex( nextPointR, u1, 1 );
  1551. }
  1552. }
  1553. } else {
  1554. // Miter join segment triangles
  1555. if ( innerSideModified ) {
  1556. // Optimized segment + join triangles
  1557. if ( joinIsOnLeftSide ) {
  1558. addVertex( lastPointR, u0, 1 );
  1559. addVertex( lastPointL, u0, 0 );
  1560. addVertex( outerPoint, u1, 0 );
  1561. addVertex( lastPointR, u0, 1 );
  1562. addVertex( outerPoint, u1, 0 );
  1563. addVertex( innerPoint, u1, 1 );
  1564. } else {
  1565. addVertex( lastPointR, u0, 1 );
  1566. addVertex( lastPointL, u0, 0 );
  1567. addVertex( outerPoint, u1, 1 );
  1568. addVertex( lastPointL, u0, 0 );
  1569. addVertex( innerPoint, u1, 0 );
  1570. addVertex( outerPoint, u1, 1 );
  1571. }
  1572. if ( joinIsOnLeftSide ) {
  1573. nextPointL.copy( outerPoint );
  1574. } else {
  1575. nextPointR.copy( outerPoint );
  1576. }
  1577. } else {
  1578. // Add extra miter join triangles
  1579. if ( joinIsOnLeftSide ) {
  1580. addVertex( currentPointL, u1, 0 );
  1581. addVertex( outerPoint, u1, 0 );
  1582. addVertex( currentPoint, u1, 0.5 );
  1583. addVertex( currentPoint, u1, 0.5 );
  1584. addVertex( outerPoint, u1, 0 );
  1585. addVertex( nextPointL, u1, 0 );
  1586. } else {
  1587. addVertex( currentPointR, u1, 1 );
  1588. addVertex( outerPoint, u1, 1 );
  1589. addVertex( currentPoint, u1, 0.5 );
  1590. addVertex( currentPoint, u1, 0.5 );
  1591. addVertex( outerPoint, u1, 1 );
  1592. addVertex( nextPointR, u1, 1 );
  1593. }
  1594. }
  1595. isMiter = true;
  1596. }
  1597. break;
  1598. }
  1599. } else {
  1600. // The segment triangles are generated here when two consecutive points are collinear
  1601. makeSegmentTriangles();
  1602. }
  1603. } else {
  1604. // The segment triangles are generated here if it is the ending segment
  1605. makeSegmentTriangles();
  1606. }
  1607. if ( ! isClosed && iPoint === numPoints - 1 ) {
  1608. // Start line endcap
  1609. addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 );
  1610. }
  1611. // Increment loop variables
  1612. u0 = u1;
  1613. previousPoint = currentPoint;
  1614. lastPointL.copy( nextPointL );
  1615. lastPointR.copy( nextPointR );
  1616. }
  1617. if ( ! isClosed ) {
  1618. // Ending line endcap
  1619. addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 );
  1620. } else if ( innerSideModified && vertices ) {
  1621. // Modify path first segment vertices to adjust to the segments inner and outer intersections
  1622. let lastOuter = outerPoint;
  1623. let lastInner = innerPoint;
  1624. if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) {
  1625. lastOuter = innerPoint;
  1626. lastInner = outerPoint;
  1627. }
  1628. if ( joinIsOnLeftSide ) {
  1629. if ( isMiter || initialJoinIsOnLeftSide ) {
  1630. lastInner.toArray( vertices, 0 * 3 );
  1631. lastInner.toArray( vertices, 3 * 3 );
  1632. if ( isMiter ) {
  1633. lastOuter.toArray( vertices, 1 * 3 );
  1634. }
  1635. }
  1636. } else {
  1637. if ( isMiter || ! initialJoinIsOnLeftSide ) {
  1638. lastInner.toArray( vertices, 1 * 3 );
  1639. lastInner.toArray( vertices, 3 * 3 );
  1640. if ( isMiter ) {
  1641. lastOuter.toArray( vertices, 0 * 3 );
  1642. }
  1643. }
  1644. }
  1645. }
  1646. return numVertices;
  1647. // -- End of algorithm
  1648. // -- Functions
  1649. function getNormal( p1, p2, result ) {
  1650. result.subVectors( p2, p1 );
  1651. return result.set( - result.y, result.x ).normalize();
  1652. }
  1653. function addVertex( position, u, v ) {
  1654. if ( vertices ) {
  1655. vertices[ currentCoordinate ] = position.x;
  1656. vertices[ currentCoordinate + 1 ] = position.y;
  1657. vertices[ currentCoordinate + 2 ] = 0;
  1658. if ( normals ) {
  1659. normals[ currentCoordinate ] = 0;
  1660. normals[ currentCoordinate + 1 ] = 0;
  1661. normals[ currentCoordinate + 2 ] = 1;
  1662. }
  1663. currentCoordinate += 3;
  1664. if ( uvs ) {
  1665. uvs[ currentCoordinateUV ] = u;
  1666. uvs[ currentCoordinateUV + 1 ] = v;
  1667. currentCoordinateUV += 2;
  1668. }
  1669. }
  1670. numVertices += 3;
  1671. }
  1672. function makeCircularSector( center, p1, p2, u, v ) {
  1673. // param p1, p2: Points in the circle arc.
  1674. // p1 and p2 are in clockwise direction.
  1675. tempV2_1.copy( p1 ).sub( center ).normalize();
  1676. tempV2_2.copy( p2 ).sub( center ).normalize();
  1677. let angle = Math.PI;
  1678. const dot = tempV2_1.dot( tempV2_2 );
  1679. if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) );
  1680. angle /= arcDivisions;
  1681. tempV2_3.copy( p1 );
  1682. for ( let i = 0, il = arcDivisions - 1; i < il; i ++ ) {
  1683. tempV2_4.copy( tempV2_3 ).rotateAround( center, angle );
  1684. addVertex( tempV2_3, u, v );
  1685. addVertex( tempV2_4, u, v );
  1686. addVertex( center, u, 0.5 );
  1687. tempV2_3.copy( tempV2_4 );
  1688. }
  1689. addVertex( tempV2_4, u, v );
  1690. addVertex( p2, u, v );
  1691. addVertex( center, u, 0.5 );
  1692. }
  1693. function makeSegmentTriangles() {
  1694. addVertex( lastPointR, u0, 1 );
  1695. addVertex( lastPointL, u0, 0 );
  1696. addVertex( currentPointL, u1, 0 );
  1697. addVertex( lastPointR, u0, 1 );
  1698. addVertex( currentPointL, u1, 1 );
  1699. addVertex( currentPointR, u1, 0 );
  1700. }
  1701. function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) {
  1702. if ( innerSideModified ) {
  1703. // Optimized segment + bevel triangles
  1704. if ( joinIsOnLeftSide ) {
  1705. // Path segments triangles
  1706. addVertex( lastPointR, u0, 1 );
  1707. addVertex( lastPointL, u0, 0 );
  1708. addVertex( currentPointL, u1, 0 );
  1709. addVertex( lastPointR, u0, 1 );
  1710. addVertex( currentPointL, u1, 0 );
  1711. addVertex( innerPoint, u1, 1 );
  1712. // Bevel join triangle
  1713. addVertex( currentPointL, u, 0 );
  1714. addVertex( nextPointL, u, 0 );
  1715. addVertex( innerPoint, u, 0.5 );
  1716. } else {
  1717. // Path segments triangles
  1718. addVertex( lastPointR, u0, 1 );
  1719. addVertex( lastPointL, u0, 0 );
  1720. addVertex( currentPointR, u1, 1 );
  1721. addVertex( lastPointL, u0, 0 );
  1722. addVertex( innerPoint, u1, 0 );
  1723. addVertex( currentPointR, u1, 1 );
  1724. // Bevel join triangle
  1725. addVertex( currentPointR, u, 1 );
  1726. addVertex( nextPointR, u, 0 );
  1727. addVertex( innerPoint, u, 0.5 );
  1728. }
  1729. } else {
  1730. // Bevel join triangle. The segment triangles are done in the main loop
  1731. if ( joinIsOnLeftSide ) {
  1732. addVertex( currentPointL, u, 0 );
  1733. addVertex( nextPointL, u, 0 );
  1734. addVertex( currentPoint, u, 0.5 );
  1735. } else {
  1736. addVertex( currentPointR, u, 1 );
  1737. addVertex( nextPointR, u, 0 );
  1738. addVertex( currentPoint, u, 0.5 );
  1739. }
  1740. }
  1741. }
  1742. function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) {
  1743. if ( innerSideModified ) {
  1744. if ( joinIsOnLeftSide ) {
  1745. addVertex( lastPointR, u0, 1 );
  1746. addVertex( lastPointL, u0, 0 );
  1747. addVertex( currentPointL, u1, 0 );
  1748. addVertex( lastPointR, u0, 1 );
  1749. addVertex( currentPointL, u1, 0 );
  1750. addVertex( innerPoint, u1, 1 );
  1751. addVertex( currentPointL, u0, 0 );
  1752. addVertex( currentPoint, u1, 0.5 );
  1753. addVertex( innerPoint, u1, 1 );
  1754. addVertex( currentPoint, u1, 0.5 );
  1755. addVertex( nextPointL, u0, 0 );
  1756. addVertex( innerPoint, u1, 1 );
  1757. } else {
  1758. addVertex( lastPointR, u0, 1 );
  1759. addVertex( lastPointL, u0, 0 );
  1760. addVertex( currentPointR, u1, 1 );
  1761. addVertex( lastPointL, u0, 0 );
  1762. addVertex( innerPoint, u1, 0 );
  1763. addVertex( currentPointR, u1, 1 );
  1764. addVertex( currentPointR, u0, 1 );
  1765. addVertex( innerPoint, u1, 0 );
  1766. addVertex( currentPoint, u1, 0.5 );
  1767. addVertex( currentPoint, u1, 0.5 );
  1768. addVertex( innerPoint, u1, 0 );
  1769. addVertex( nextPointR, u0, 1 );
  1770. }
  1771. }
  1772. }
  1773. function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) {
  1774. // param center: End point of the path
  1775. // param p1, p2: Left and right cap points
  1776. switch ( style.strokeLineCap ) {
  1777. case 'round':
  1778. if ( start ) {
  1779. makeCircularSector( center, p2, p1, u, 0.5 );
  1780. } else {
  1781. makeCircularSector( center, p1, p2, u, 0.5 );
  1782. }
  1783. break;
  1784. case 'square':
  1785. if ( start ) {
  1786. tempV2_1.subVectors( p1, center );
  1787. tempV2_2.set( tempV2_1.y, - tempV2_1.x );
  1788. tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
  1789. tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
  1790. // Modify already existing vertices
  1791. if ( joinIsOnLeftSide ) {
  1792. tempV2_3.toArray( vertices, 1 * 3 );
  1793. tempV2_4.toArray( vertices, 0 * 3 );
  1794. tempV2_4.toArray( vertices, 3 * 3 );
  1795. } else {
  1796. tempV2_3.toArray( vertices, 1 * 3 );
  1797. tempV2_3.toArray( vertices, 3 * 3 );
  1798. tempV2_4.toArray( vertices, 0 * 3 );
  1799. }
  1800. } else {
  1801. tempV2_1.subVectors( p2, center );
  1802. tempV2_2.set( tempV2_1.y, - tempV2_1.x );
  1803. tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
  1804. tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
  1805. const vl = vertices.length;
  1806. // Modify already existing vertices
  1807. if ( joinIsOnLeftSide ) {
  1808. tempV2_3.toArray( vertices, vl - 1 * 3 );
  1809. tempV2_4.toArray( vertices, vl - 2 * 3 );
  1810. tempV2_4.toArray( vertices, vl - 4 * 3 );
  1811. } else {
  1812. tempV2_3.toArray( vertices, vl - 2 * 3 );
  1813. tempV2_4.toArray( vertices, vl - 1 * 3 );
  1814. tempV2_4.toArray( vertices, vl - 4 * 3 );
  1815. }
  1816. }
  1817. break;
  1818. case 'butt':
  1819. default:
  1820. // Nothing to do here
  1821. break;
  1822. }
  1823. }
  1824. function removeDuplicatedPoints( points ) {
  1825. // Creates a new array if necessary with duplicated points removed.
  1826. // This does not remove duplicated initial and ending points of a closed path.
  1827. let dupPoints = false;
  1828. for ( let i = 1, n = points.length - 1; i < n; i ++ ) {
  1829. if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) {
  1830. dupPoints = true;
  1831. break;
  1832. }
  1833. }
  1834. if ( ! dupPoints ) return points;
  1835. const newPoints = [];
  1836. newPoints.push( points[ 0 ] );
  1837. for ( let i = 1, n = points.length - 1; i < n; i ++ ) {
  1838. if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) {
  1839. newPoints.push( points[ i ] );
  1840. }
  1841. }
  1842. newPoints.push( points[ points.length - 1 ] );
  1843. return newPoints;
  1844. }
  1845. }
  1846. }
  1847. export { SVGLoader };