SVGLoader.js 64 KB

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