SVGLoader.js 63 KB

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