SVGLoader.js 63 KB

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