SVGLoader.js 69 KB

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