SVGLoader.js 69 KB

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