SVGLoader.js 71 KB

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