2
0

SVGLoader.js 62 KB

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