SVGLoader.js 75 KB

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