SVGLoader.js 64 KB

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