SVGLoader.js 66 KB

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