SVGLoader.js 63 KB

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