SVGLoader.js 68 KB

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