SVGLoader.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267
  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 };