SVGLoader.js 62 KB

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