SVGLoader.js 63 KB

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