| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516 |
- import {
- Box2,
- BufferGeometry,
- CanvasTexture,
- ClampToEdgeWrapping,
- Color,
- DoubleSide,
- FileLoader,
- Float32BufferAttribute,
- Loader,
- Matrix3,
- MeshBasicMaterial,
- MirroredRepeatWrapping,
- Path,
- RepeatWrapping,
- Shape,
- ShapePath,
- ShapeUtils,
- SRGBColorSpace,
- Vector2,
- Vector3
- } from 'three';
- const COLOR_SPACE_SVG = SRGBColorSpace;
- /**
- * A loader for the SVG format.
- *
- * Scalable Vector Graphics is an XML-based vector image format for two-dimensional graphics
- * with support for interactivity and animation.
- *
- * ```js
- * const loader = new SVGLoader();
- * const data = await loader.loadAsync( 'data/svgSample.svg' );
- *
- * const paths = data.paths;
- * const group = new THREE.Group();
- *
- * for ( let i = 0; i < paths.length; i ++ ) {
- *
- * const path = paths[ i ];
- * const material = new THREE.MeshBasicMaterial( {
- * color: path.color,
- * side: THREE.DoubleSide,
- * depthWrite: false
- * } );
- *
- * const shapes = SVGLoader.createShapes( path );
- *
- * for ( let j = 0; j < shapes.length; j ++ ) {
- *
- * const shape = shapes[ j ];
- * const geometry = new THREE.ShapeGeometry( shape );
- * const mesh = new THREE.Mesh( geometry, material );
- * group.add( mesh );
- *
- * }
- *
- * }
- *
- * scene.add( group );
- * ```
- *
- * @augments Loader
- * @three_import import { SVGLoader } from 'three/addons/loaders/SVGLoader.js';
- */
- class SVGLoader extends Loader {
- /**
- * Constructs a new SVG loader.
- *
- * @param {LoadingManager} [manager] - The loading manager.
- */
- constructor( manager ) {
- super( manager );
- /**
- * Default dots per inch.
- *
- * @type {number}
- * @default 90
- */
- this.defaultDPI = 90;
- /**
- * Default unit.
- *
- * @type {('mm'|'cm'|'in'|'pt'|'pc'|'px')}
- * @default 'px'
- */
- this.defaultUnit = 'px';
- }
- /**
- * Starts loading from the given URL and passes the loaded SVG asset
- * to the `onLoad()` callback.
- *
- * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
- * @param {function({paths:Array<ShapePath>,xml:string})} onLoad - Executed when the loading process has been finished.
- * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
- * @param {onErrorCallback} onError - Executed when errors occur.
- */
- load( url, onLoad, onProgress, onError ) {
- const scope = this;
- const loader = new FileLoader( scope.manager );
- loader.setPath( scope.path );
- loader.setRequestHeader( scope.requestHeader );
- loader.setWithCredentials( scope.withCredentials );
- loader.load( url, function ( text ) {
- try {
- onLoad( scope.parse( text ) );
- } catch ( e ) {
- if ( onError ) {
- onError( e );
- } else {
- console.error( e );
- }
- scope.manager.itemError( url );
- }
- }, onProgress, onError );
- }
- /**
- * Parses the given SVG data and returns the resulting data.
- *
- * @param {string} text - The raw SVG data as a string.
- * @return {{paths:Array<ShapePath>,xml:string}} An object holding an array of shape paths and the
- * SVG XML document.
- */
- parse( text ) {
- const scope = this;
- function parseNode( node, style ) {
- if ( node.nodeType !== 1 ) return;
- if ( node.hasAttribute( 'filter' ) ) {
- console.warn( 'THREE.SVGLoader: Filters are not supported.' );
- }
- const transform = getNodeTransform( node );
- let isDefsNode = false;
- let path = null;
- switch ( node.nodeName ) {
- case 'svg':
- style = parseStyle( node, style );
- break;
- case 'style':
- parseCSSStylesheet( node );
- break;
- case 'g':
- style = parseStyle( node, style );
- break;
- case 'path':
- style = parseStyle( node, style );
- if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node );
- break;
- case 'rect':
- style = parseStyle( node, style );
- path = parseRectNode( node );
- break;
- case 'polygon':
- style = parseStyle( node, style );
- path = parsePolygonNode( node );
- break;
- case 'polyline':
- style = parseStyle( node, style );
- path = parsePolylineNode( node );
- break;
- case 'circle':
- style = parseStyle( node, style );
- path = parseCircleNode( node );
- break;
- case 'ellipse':
- style = parseStyle( node, style );
- path = parseEllipseNode( node );
- break;
- case 'line':
- style = parseStyle( node, style );
- path = parseLineNode( node );
- break;
- case 'defs':
- isDefsNode = true;
- break;
- case 'use':
- style = parseStyle( node, style );
- const href = node.getAttributeNS( 'http://www.w3.org/1999/xlink', 'href' ) || '';
- const usedNodeId = href.substring( 1 );
- const usedNode = node.viewportElement.getElementById( usedNodeId );
- if ( usedNode ) {
- parseNode( usedNode, style );
- } else {
- console.warn( 'SVGLoader: \'use node\' references non-existent node id: ' + usedNodeId );
- }
- break;
- default:
- // console.log( node );
- }
- if ( path ) {
- if ( style.fill !== undefined && style.fill !== 'none' && ! style.fill.startsWith( 'url' ) ) {
- path.color.setStyle( style.fill, COLOR_SPACE_SVG );
- }
- transformPath( path, currentTransform );
- paths.push( path );
- const pathStyle = Object.assign( {}, style );
- pathStyle.strokeWidth = style.strokeWidth * getTransformScale( currentTransform );
- path.userData = { node: node, style: pathStyle, transform: currentTransform.clone(), gradients: gradients };
- }
- const childNodes = node.childNodes;
- for ( let i = 0; i < childNodes.length; i ++ ) {
- const node = childNodes[ i ];
- if ( isDefsNode && node.nodeName !== 'style' && node.nodeName !== 'defs' ) {
- // Ignore everything in defs except CSS style definitions
- // and nested defs, because it is OK by the standard to have
- // <style/> there.
- continue;
- }
- parseNode( node, style );
- }
- if ( transform ) {
- transformStack.pop();
- if ( transformStack.length > 0 ) {
- currentTransform.copy( transformStack[ transformStack.length - 1 ] );
- } else {
- currentTransform.identity();
- }
- }
- }
- function parsePathNode( node ) {
- const path = new ShapePath();
- const point = new Vector2();
- const control = new Vector2();
- const firstPoint = new Vector2();
- let isFirstPoint = true;
- let doSetFirstPoint = false;
- const d = node.getAttribute( 'd' );
- if ( d === '' || d === 'none' ) return null;
- // console.log( d );
- const commands = d.match( /[a-df-z][^a-df-z]*/ig );
- for ( let i = 0, l = commands.length; i < l; i ++ ) {
- const command = commands[ i ];
- const type = command.charAt( 0 );
- const data = command.slice( 1 ).trim();
- if ( isFirstPoint === true ) {
- doSetFirstPoint = true;
- isFirstPoint = false;
- }
- let numbers;
- switch ( type ) {
- case 'M':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
- point.x = numbers[ j + 0 ];
- point.y = numbers[ j + 1 ];
- control.x = point.x;
- control.y = point.y;
- if ( j === 0 ) {
- path.moveTo( point.x, point.y );
- } else {
- path.lineTo( point.x, point.y );
- }
- if ( j === 0 ) firstPoint.copy( point );
- }
- break;
- case 'H':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
- point.x = numbers[ j ];
- control.x = point.x;
- control.y = point.y;
- path.lineTo( point.x, point.y );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'V':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
- point.y = numbers[ j ];
- control.x = point.x;
- control.y = point.y;
- path.lineTo( point.x, point.y );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'L':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
- point.x = numbers[ j + 0 ];
- point.y = numbers[ j + 1 ];
- control.x = point.x;
- control.y = point.y;
- path.lineTo( point.x, point.y );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'C':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 6 ) {
- path.bezierCurveTo(
- numbers[ j + 0 ],
- numbers[ j + 1 ],
- numbers[ j + 2 ],
- numbers[ j + 3 ],
- numbers[ j + 4 ],
- numbers[ j + 5 ]
- );
- control.x = numbers[ j + 2 ];
- control.y = numbers[ j + 3 ];
- point.x = numbers[ j + 4 ];
- point.y = numbers[ j + 5 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'S':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
- path.bezierCurveTo(
- getReflection( point.x, control.x ),
- getReflection( point.y, control.y ),
- numbers[ j + 0 ],
- numbers[ j + 1 ],
- numbers[ j + 2 ],
- numbers[ j + 3 ]
- );
- control.x = numbers[ j + 0 ];
- control.y = numbers[ j + 1 ];
- point.x = numbers[ j + 2 ];
- point.y = numbers[ j + 3 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'Q':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
- path.quadraticCurveTo(
- numbers[ j + 0 ],
- numbers[ j + 1 ],
- numbers[ j + 2 ],
- numbers[ j + 3 ]
- );
- control.x = numbers[ j + 0 ];
- control.y = numbers[ j + 1 ];
- point.x = numbers[ j + 2 ];
- point.y = numbers[ j + 3 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'T':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
- const rx = getReflection( point.x, control.x );
- const ry = getReflection( point.y, control.y );
- path.quadraticCurveTo(
- rx,
- ry,
- numbers[ j + 0 ],
- numbers[ j + 1 ]
- );
- control.x = rx;
- control.y = ry;
- point.x = numbers[ j + 0 ];
- point.y = numbers[ j + 1 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'A':
- numbers = parseFloats( data, [ 3, 4 ], 7 );
- for ( let j = 0, jl = numbers.length; j < jl; j += 7 ) {
- // skip command if start point == end point
- if ( numbers[ j + 5 ] == point.x && numbers[ j + 6 ] == point.y ) continue;
- const start = point.clone();
- point.x = numbers[ j + 5 ];
- point.y = numbers[ j + 6 ];
- control.x = point.x;
- control.y = point.y;
- parseArcCommand(
- path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
- );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'm':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
- point.x += numbers[ j + 0 ];
- point.y += numbers[ j + 1 ];
- control.x = point.x;
- control.y = point.y;
- if ( j === 0 ) {
- path.moveTo( point.x, point.y );
- } else {
- path.lineTo( point.x, point.y );
- }
- if ( j === 0 ) firstPoint.copy( point );
- }
- break;
- case 'h':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
- point.x += numbers[ j ];
- control.x = point.x;
- control.y = point.y;
- path.lineTo( point.x, point.y );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'v':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j ++ ) {
- point.y += numbers[ j ];
- control.x = point.x;
- control.y = point.y;
- path.lineTo( point.x, point.y );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'l':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
- point.x += numbers[ j + 0 ];
- point.y += numbers[ j + 1 ];
- control.x = point.x;
- control.y = point.y;
- path.lineTo( point.x, point.y );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'c':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 6 ) {
- path.bezierCurveTo(
- point.x + numbers[ j + 0 ],
- point.y + numbers[ j + 1 ],
- point.x + numbers[ j + 2 ],
- point.y + numbers[ j + 3 ],
- point.x + numbers[ j + 4 ],
- point.y + numbers[ j + 5 ]
- );
- control.x = point.x + numbers[ j + 2 ];
- control.y = point.y + numbers[ j + 3 ];
- point.x += numbers[ j + 4 ];
- point.y += numbers[ j + 5 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 's':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
- path.bezierCurveTo(
- getReflection( point.x, control.x ),
- getReflection( point.y, control.y ),
- point.x + numbers[ j + 0 ],
- point.y + numbers[ j + 1 ],
- point.x + numbers[ j + 2 ],
- point.y + numbers[ j + 3 ]
- );
- control.x = point.x + numbers[ j + 0 ];
- control.y = point.y + numbers[ j + 1 ];
- point.x += numbers[ j + 2 ];
- point.y += numbers[ j + 3 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'q':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 4 ) {
- path.quadraticCurveTo(
- point.x + numbers[ j + 0 ],
- point.y + numbers[ j + 1 ],
- point.x + numbers[ j + 2 ],
- point.y + numbers[ j + 3 ]
- );
- control.x = point.x + numbers[ j + 0 ];
- control.y = point.y + numbers[ j + 1 ];
- point.x += numbers[ j + 2 ];
- point.y += numbers[ j + 3 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 't':
- numbers = parseFloats( data );
- for ( let j = 0, jl = numbers.length; j < jl; j += 2 ) {
- const rx = getReflection( point.x, control.x );
- const ry = getReflection( point.y, control.y );
- path.quadraticCurveTo(
- rx,
- ry,
- point.x + numbers[ j + 0 ],
- point.y + numbers[ j + 1 ]
- );
- control.x = rx;
- control.y = ry;
- point.x = point.x + numbers[ j + 0 ];
- point.y = point.y + numbers[ j + 1 ];
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'a':
- numbers = parseFloats( data, [ 3, 4 ], 7 );
- for ( let j = 0, jl = numbers.length; j < jl; j += 7 ) {
- // skip command if no displacement
- if ( numbers[ j + 5 ] == 0 && numbers[ j + 6 ] == 0 ) continue;
- const start = point.clone();
- point.x += numbers[ j + 5 ];
- point.y += numbers[ j + 6 ];
- control.x = point.x;
- control.y = point.y;
- parseArcCommand(
- path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point
- );
- if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point );
- }
- break;
- case 'Z':
- case 'z':
- path.currentPath.autoClose = true;
- if ( path.currentPath.curves.length > 0 ) {
- // Reset point to beginning of Path
- point.copy( firstPoint );
- path.currentPath.currentPoint.copy( point );
- isFirstPoint = true;
- }
- break;
- default:
- console.warn( command );
- }
- // console.log( type, parseFloats( data ), parseFloats( data ).length )
- doSetFirstPoint = false;
- }
- return path;
- }
- function parseCSSStylesheet( node ) {
- if ( ! node.sheet || ! node.sheet.cssRules || ! node.sheet.cssRules.length ) return;
- for ( let i = 0; i < node.sheet.cssRules.length; i ++ ) {
- const stylesheet = node.sheet.cssRules[ i ];
- if ( stylesheet.type !== 1 ) continue;
- const selectorList = stylesheet.selectorText
- .split( /,/gm )
- .filter( Boolean )
- .map( i => i.trim() );
- for ( let j = 0; j < selectorList.length; j ++ ) {
- // Remove empty rules
- const definitions = Object.fromEntries(
- Object.entries( stylesheet.style ).filter( ( [ , v ] ) => v !== '' )
- );
- stylesheets[ selectorList[ j ] ] = Object.assign(
- stylesheets[ selectorList[ j ] ] || {},
- definitions
- );
- }
- }
- }
- /**
- * https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes
- * https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion
- * From
- * rx ry x-axis-rotation large-arc-flag sweep-flag x y
- * To
- * aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation
- */
- function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) {
- if ( rx == 0 || ry == 0 ) {
- // draw a line if either of the radii == 0
- path.lineTo( end.x, end.y );
- return;
- }
- x_axis_rotation = x_axis_rotation * Math.PI / 180;
- // Ensure radii are positive
- rx = Math.abs( rx );
- ry = Math.abs( ry );
- // Compute (x1', y1')
- const dx2 = ( start.x - end.x ) / 2.0;
- const dy2 = ( start.y - end.y ) / 2.0;
- const x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2;
- const y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2;
- // Compute (cx', cy')
- let rxs = rx * rx;
- let rys = ry * ry;
- const x1ps = x1p * x1p;
- const y1ps = y1p * y1p;
- // Ensure radii are large enough
- const cr = x1ps / rxs + y1ps / rys;
- if ( cr > 1 ) {
- // scale up rx,ry equally so cr == 1
- const s = Math.sqrt( cr );
- rx = s * rx;
- ry = s * ry;
- rxs = rx * rx;
- rys = ry * ry;
- }
- const dq = ( rxs * y1ps + rys * x1ps );
- const pq = ( rxs * rys - dq ) / dq;
- let q = Math.sqrt( Math.max( 0, pq ) );
- if ( large_arc_flag === sweep_flag ) q = - q;
- const cxp = q * rx * y1p / ry;
- const cyp = - q * ry * x1p / rx;
- // Step 3: Compute (cx, cy) from (cx', cy')
- const cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2;
- const cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2;
- // Step 4: Compute θ1 and Δθ
- const theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry );
- const delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 );
- path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation );
- }
- function svgAngle( ux, uy, vx, vy ) {
- const dot = ux * vx + uy * vy;
- const len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy );
- let ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear
- if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang;
- return ang;
- }
- /*
- * According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute
- * rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough
- */
- function parseRectNode( node ) {
- const x = parseFloatWithUnits( node.getAttribute( 'x' ) || 0 );
- const y = parseFloatWithUnits( node.getAttribute( 'y' ) || 0 );
- const rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || node.getAttribute( 'ry' ) || 0 );
- const ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || node.getAttribute( 'rx' ) || 0 );
- const w = parseFloatWithUnits( node.getAttribute( 'width' ) );
- const h = parseFloatWithUnits( node.getAttribute( 'height' ) );
- // Ellipse arc to Bezier approximation Coefficient (Inversed). See:
- // https://spencermortensen.com/articles/bezier-circle/
- const bci = 1 - 0.551915024494;
- const path = new ShapePath();
- // top left
- path.moveTo( x + rx, y );
- // top right
- path.lineTo( x + w - rx, y );
- if ( rx !== 0 || ry !== 0 ) {
- path.bezierCurveTo(
- x + w - rx * bci,
- y,
- x + w,
- y + ry * bci,
- x + w,
- y + ry
- );
- }
- // bottom right
- path.lineTo( x + w, y + h - ry );
- if ( rx !== 0 || ry !== 0 ) {
- path.bezierCurveTo(
- x + w,
- y + h - ry * bci,
- x + w - rx * bci,
- y + h,
- x + w - rx,
- y + h
- );
- }
- // bottom left
- path.lineTo( x + rx, y + h );
- if ( rx !== 0 || ry !== 0 ) {
- path.bezierCurveTo(
- x + rx * bci,
- y + h,
- x,
- y + h - ry * bci,
- x,
- y + h - ry
- );
- }
- // back to top left
- path.lineTo( x, y + ry );
- if ( rx !== 0 || ry !== 0 ) {
- path.bezierCurveTo( x, y + ry * bci, x + rx * bci, y, x + rx, y );
- }
- return path;
- }
- function parsePolygonNode( node ) {
- function iterator( match, a, b ) {
- const x = parseFloatWithUnits( a );
- const y = parseFloatWithUnits( b );
- if ( index === 0 ) {
- path.moveTo( x, y );
- } else {
- path.lineTo( x, y );
- }
- index ++;
- }
- const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g;
- const path = new ShapePath();
- let index = 0;
- node.getAttribute( 'points' ).replace( regex, iterator );
- path.currentPath.autoClose = true;
- return path;
- }
- function parsePolylineNode( node ) {
- function iterator( match, a, b ) {
- const x = parseFloatWithUnits( a );
- const y = parseFloatWithUnits( b );
- if ( index === 0 ) {
- path.moveTo( x, y );
- } else {
- path.lineTo( x, y );
- }
- index ++;
- }
- const regex = /([+-]?\d*\.?\d+(?:e[+-]?\d+)?)(?:,|\s)([+-]?\d*\.?\d+(?:e[+-]?\d+)?)/g;
- const path = new ShapePath();
- let index = 0;
- node.getAttribute( 'points' ).replace( regex, iterator );
- path.currentPath.autoClose = false;
- return path;
- }
- function parseCircleNode( node ) {
- const x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
- const y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
- const r = parseFloatWithUnits( node.getAttribute( 'r' ) || 0 );
- const subpath = new Path();
- subpath.absarc( x, y, r, 0, Math.PI * 2 );
- const path = new ShapePath();
- path.subPaths.push( subpath );
- return path;
- }
- function parseEllipseNode( node ) {
- const x = parseFloatWithUnits( node.getAttribute( 'cx' ) || 0 );
- const y = parseFloatWithUnits( node.getAttribute( 'cy' ) || 0 );
- const rx = parseFloatWithUnits( node.getAttribute( 'rx' ) || 0 );
- const ry = parseFloatWithUnits( node.getAttribute( 'ry' ) || 0 );
- const subpath = new Path();
- subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2 );
- const path = new ShapePath();
- path.subPaths.push( subpath );
- return path;
- }
- function parseLineNode( node ) {
- const x1 = parseFloatWithUnits( node.getAttribute( 'x1' ) || 0 );
- const y1 = parseFloatWithUnits( node.getAttribute( 'y1' ) || 0 );
- const x2 = parseFloatWithUnits( node.getAttribute( 'x2' ) || 0 );
- const y2 = parseFloatWithUnits( node.getAttribute( 'y2' ) || 0 );
- const path = new ShapePath();
- path.moveTo( x1, y1 );
- path.lineTo( x2, y2 );
- path.currentPath.autoClose = false;
- return path;
- }
- //
- function parseGradients( xml ) {
- const HREF_NS = 'http://www.w3.org/1999/xlink';
- const gradientNodes = xml.querySelectorAll( 'linearGradient, radialGradient' );
- const ATTRS = [ 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'fx', 'fy', 'gradientUnits', 'gradientTransform', 'spreadMethod' ];
- const parsed = {};
- for ( const node of gradientNodes ) {
- const id = node.getAttribute( 'id' );
- if ( ! id ) continue;
- const entry = {
- type: node.nodeName === 'radialGradient' ? 'radialGradient' : 'linearGradient',
- attrs: {},
- stops: null,
- href: null,
- };
- const href = node.getAttributeNS( HREF_NS, 'href' ) || node.getAttribute( 'href' ) || '';
- if ( href.startsWith( '#' ) ) entry.href = href.substring( 1 );
- for ( const name of ATTRS ) {
- if ( node.hasAttribute( name ) ) entry.attrs[ name ] = node.getAttribute( name );
- }
- const stopNodes = node.querySelectorAll( 'stop' );
- if ( stopNodes.length > 0 ) {
- entry.stops = [];
- for ( const s of stopNodes ) {
- let color = s.getAttribute( 'stop-color' );
- if ( ! color && s.style ) color = s.style[ 'stop-color' ];
- if ( ! color ) color = '#000';
- let opacity = s.getAttribute( 'stop-opacity' );
- if ( ( opacity === null || opacity === '' ) && s.style ) opacity = s.style[ 'stop-opacity' ];
- opacity = ( opacity === null || opacity === '' || opacity === undefined )
- ? 1
- : Math.max( 0, Math.min( 1, parseFloat( opacity ) ) );
- const offset = Math.max( 0, Math.min( 1, parseFloat( s.getAttribute( 'offset' ) || '0' ) ) );
- entry.stops.push( { offset, color, opacity } );
- }
- }
- parsed[ id ] = entry;
- }
- function inherit( id, visited ) {
- const entry = parsed[ id ];
- if ( ! entry || visited.has( id ) ) return entry;
- visited.add( id );
- if ( entry.href && parsed[ entry.href ] ) {
- const parent = inherit( entry.href, visited );
- if ( parent ) {
- if ( ! entry.stops ) entry.stops = parent.stops;
- for ( const key in parent.attrs ) {
- if ( ! ( key in entry.attrs ) ) entry.attrs[ key ] = parent.attrs[ key ];
- }
- }
- }
- return entry;
- }
- for ( const id in parsed ) inherit( id, new Set() );
- for ( const id in parsed ) {
- const entry = parsed[ id ];
- const a = entry.attrs;
- const units = a.gradientUnits === 'userSpaceOnUse' ? 'userSpaceOnUse' : 'objectBoundingBox';
- const gradient = {
- type: entry.type,
- gradientUnits: units,
- spreadMethod: a.spreadMethod === 'reflect' || a.spreadMethod === 'repeat' ? a.spreadMethod : 'pad',
- gradientTransform: null,
- stops: ( entry.stops || [] ).slice().sort( ( x, y ) => x.offset - y.offset ),
- };
- if ( a.gradientTransform ) {
- gradient.gradientTransform = new Matrix3();
- parseTransformString( a.gradientTransform, gradient.gradientTransform );
- }
- function coord( str ) {
- if ( typeof str !== 'string' ) return 0;
- if ( str.endsWith( '%' ) ) return parseFloat( str ) / 100;
- return parseFloatWithUnits( str );
- }
- if ( entry.type === 'linearGradient' ) {
- gradient.x1 = a.x1 !== undefined ? coord( a.x1 ) : 0;
- gradient.y1 = a.y1 !== undefined ? coord( a.y1 ) : 0;
- gradient.x2 = a.x2 !== undefined ? coord( a.x2 ) : ( units === 'objectBoundingBox' ? 1 : 0 );
- gradient.y2 = a.y2 !== undefined ? coord( a.y2 ) : 0;
- } else {
- const defCenter = units === 'objectBoundingBox' ? 0.5 : 0;
- const defR = units === 'objectBoundingBox' ? 0.5 : 0;
- gradient.cx = a.cx !== undefined ? coord( a.cx ) : defCenter;
- gradient.cy = a.cy !== undefined ? coord( a.cy ) : defCenter;
- gradient.r = a.r !== undefined ? coord( a.r ) : defR;
- gradient.fx = a.fx !== undefined ? coord( a.fx ) : gradient.cx;
- gradient.fy = a.fy !== undefined ? coord( a.fy ) : gradient.cy;
- }
- gradients[ id ] = gradient;
- }
- }
- //
- function parseStyle( node, style ) {
- style = Object.assign( {}, style ); // clone style
- let stylesheetStyles = {};
- if ( node.hasAttribute( 'class' ) ) {
- const classSelectors = node.getAttribute( 'class' )
- .split( /\s/ )
- .filter( Boolean )
- .map( i => i.trim() );
- for ( let i = 0; i < classSelectors.length; i ++ ) {
- stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '.' + classSelectors[ i ] ] );
- }
- }
- if ( node.hasAttribute( 'id' ) ) {
- stylesheetStyles = Object.assign( stylesheetStyles, stylesheets[ '#' + node.getAttribute( 'id' ) ] );
- }
- function addStyle( svgName, jsName, adjustFunction ) {
- if ( adjustFunction === undefined ) adjustFunction = function copy( v ) {
- return v;
- };
- if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) );
- if ( stylesheetStyles[ jsName ] ) style[ jsName ] = adjustFunction( stylesheetStyles[ jsName ] );
- if ( node.style && node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] );
- }
- function clamp( v ) {
- return Math.max( 0, Math.min( 1, parseFloatWithUnits( v ) ) );
- }
- function positive( v ) {
- return Math.max( 0, parseFloatWithUnits( v ) );
- }
- addStyle( 'fill', 'fill' );
- addStyle( 'fill-opacity', 'fillOpacity', clamp );
- addStyle( 'fill-rule', 'fillRule' );
- addStyle( 'opacity', 'opacity', clamp );
- addStyle( 'stroke', 'stroke' );
- addStyle( 'stroke-opacity', 'strokeOpacity', clamp );
- addStyle( 'stroke-width', 'strokeWidth', positive );
- addStyle( 'stroke-linejoin', 'strokeLineJoin' );
- addStyle( 'stroke-linecap', 'strokeLineCap' );
- addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive );
- addStyle( 'visibility', 'visibility' );
- return style;
- }
- // http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes
- function getReflection( a, b ) {
- return a - ( b - a );
- }
- // from https://github.com/ppvg/svg-numbers (MIT License)
- function parseFloats( input, flags, stride ) {
- if ( typeof input !== 'string' ) {
- throw new TypeError( 'Invalid input: ' + typeof input );
- }
- // Character groups
- const RE = {
- SEPARATOR: /[ \t\r\n\,.\-+]/,
- WHITESPACE: /[ \t\r\n]/,
- DIGIT: /[\d]/,
- SIGN: /[-+]/,
- POINT: /\./,
- COMMA: /,/,
- EXP: /e/i,
- FLAGS: /[01]/
- };
- // States
- const SEP = 0;
- const INT = 1;
- const FLOAT = 2;
- const EXP = 3;
- let state = SEP;
- let seenComma = true;
- let number = '', exponent = '';
- const result = [];
- function throwSyntaxError( current, i, partial ) {
- const error = new SyntaxError( 'Unexpected character "' + current + '" at index ' + i + '.' );
- error.partial = partial;
- throw error;
- }
- function newNumber() {
- if ( number !== '' ) {
- if ( exponent === '' ) result.push( Number( number ) );
- else result.push( Number( number ) * Math.pow( 10, Number( exponent ) ) );
- }
- number = '';
- exponent = '';
- }
- let current;
- const length = input.length;
- for ( let i = 0; i < length; i ++ ) {
- current = input[ i ];
- // check for flags
- if ( Array.isArray( flags ) && flags.includes( result.length % stride ) && RE.FLAGS.test( current ) ) {
- state = INT;
- number = current;
- newNumber();
- continue;
- }
- // parse until next number
- if ( state === SEP ) {
- // eat whitespace
- if ( RE.WHITESPACE.test( current ) ) {
- continue;
- }
- // start new number
- if ( RE.DIGIT.test( current ) || RE.SIGN.test( current ) ) {
- state = INT;
- number = current;
- continue;
- }
- if ( RE.POINT.test( current ) ) {
- state = FLOAT;
- number = current;
- continue;
- }
- // throw on double commas (e.g. "1, , 2")
- if ( RE.COMMA.test( current ) ) {
- if ( seenComma ) {
- throwSyntaxError( current, i, result );
- }
- seenComma = true;
- }
- }
- // parse integer part
- if ( state === INT ) {
- if ( RE.DIGIT.test( current ) ) {
- number += current;
- continue;
- }
- if ( RE.POINT.test( current ) ) {
- number += current;
- state = FLOAT;
- continue;
- }
- if ( RE.EXP.test( current ) ) {
- state = EXP;
- continue;
- }
- // throw on double signs ("-+1"), but not on sign as separator ("-1-2")
- if ( RE.SIGN.test( current )
- && number.length === 1
- && RE.SIGN.test( number[ 0 ] ) ) {
- throwSyntaxError( current, i, result );
- }
- }
- // parse decimal part
- if ( state === FLOAT ) {
- if ( RE.DIGIT.test( current ) ) {
- number += current;
- continue;
- }
- if ( RE.EXP.test( current ) ) {
- state = EXP;
- continue;
- }
- // throw on double decimal points (e.g. "1..2")
- if ( RE.POINT.test( current ) && number[ number.length - 1 ] === '.' ) {
- throwSyntaxError( current, i, result );
- }
- }
- // parse exponent part
- if ( state === EXP ) {
- if ( RE.DIGIT.test( current ) ) {
- exponent += current;
- continue;
- }
- if ( RE.SIGN.test( current ) ) {
- if ( exponent === '' ) {
- exponent += current;
- continue;
- }
- if ( exponent.length === 1 && RE.SIGN.test( exponent ) ) {
- throwSyntaxError( current, i, result );
- }
- }
- }
- // end of number
- if ( RE.WHITESPACE.test( current ) ) {
- newNumber();
- state = SEP;
- seenComma = false;
- } else if ( RE.COMMA.test( current ) ) {
- newNumber();
- state = SEP;
- seenComma = true;
- } else if ( RE.SIGN.test( current ) ) {
- newNumber();
- state = INT;
- number = current;
- } else if ( RE.POINT.test( current ) ) {
- newNumber();
- state = FLOAT;
- number = current;
- } else {
- throwSyntaxError( current, i, result );
- }
- }
- // add the last number found (if any)
- newNumber();
- return result;
- }
- // Units
- const units = [ 'mm', 'cm', 'in', 'pt', 'pc', 'px' ];
- // Conversion: [ fromUnit ][ toUnit ] (-1 means dpi dependent)
- const unitConversion = {
- 'mm': {
- 'mm': 1,
- 'cm': 0.1,
- 'in': 1 / 25.4,
- 'pt': 72 / 25.4,
- 'pc': 6 / 25.4,
- 'px': - 1
- },
- 'cm': {
- 'mm': 10,
- 'cm': 1,
- 'in': 1 / 2.54,
- 'pt': 72 / 2.54,
- 'pc': 6 / 2.54,
- 'px': - 1
- },
- 'in': {
- 'mm': 25.4,
- 'cm': 2.54,
- 'in': 1,
- 'pt': 72,
- 'pc': 6,
- 'px': - 1
- },
- 'pt': {
- 'mm': 25.4 / 72,
- 'cm': 2.54 / 72,
- 'in': 1 / 72,
- 'pt': 1,
- 'pc': 6 / 72,
- 'px': - 1
- },
- 'pc': {
- 'mm': 25.4 / 6,
- 'cm': 2.54 / 6,
- 'in': 1 / 6,
- 'pt': 72 / 6,
- 'pc': 1,
- 'px': - 1
- },
- 'px': {
- 'px': 1
- }
- };
- function parseFloatWithUnits( string ) {
- let theUnit = 'px';
- if ( typeof string === 'string' || string instanceof String ) {
- for ( let i = 0, n = units.length; i < n; i ++ ) {
- const u = units[ i ];
- if ( string.endsWith( u ) ) {
- theUnit = u;
- string = string.substring( 0, string.length - u.length );
- break;
- }
- }
- }
- let scale = undefined;
- if ( theUnit === 'px' && scope.defaultUnit !== 'px' ) {
- // Conversion scale from pixels to inches, then to default units
- scale = unitConversion[ 'in' ][ scope.defaultUnit ] / scope.defaultDPI;
- } else {
- scale = unitConversion[ theUnit ][ scope.defaultUnit ];
- if ( scale < 0 ) {
- // Conversion scale to pixels
- scale = unitConversion[ theUnit ][ 'in' ] * scope.defaultDPI;
- }
- }
- return scale * parseFloat( string );
- }
- // Transforms
- function getNodeTransform( node ) {
- if ( ! ( node.hasAttribute( 'transform' ) || ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) ) ) {
- return null;
- }
- const transform = parseNodeTransform( node );
- if ( transformStack.length > 0 ) {
- transform.premultiply( transformStack[ transformStack.length - 1 ] );
- }
- currentTransform.copy( transform );
- transformStack.push( transform );
- return transform;
- }
- function parseNodeTransform( node ) {
- const transform = new Matrix3();
- if ( node.nodeName === 'use' && ( node.hasAttribute( 'x' ) || node.hasAttribute( 'y' ) ) ) {
- const tx = parseFloatWithUnits( node.getAttribute( 'x' ) || 0 );
- const ty = parseFloatWithUnits( node.getAttribute( 'y' ) || 0 );
- transform.translate( tx, ty );
- }
- if ( node.hasAttribute( 'transform' ) ) {
- parseTransformString( node.getAttribute( 'transform' ), transform );
- }
- return transform;
- }
- function parseTransformString( text, transform ) {
- const currentTransform = tempTransform0;
- const transformsTexts = text.split( ')' );
- for ( let tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) {
- const transformText = transformsTexts[ tIndex ].trim();
- if ( transformText === '' ) continue;
- const openParPos = transformText.indexOf( '(' );
- const closeParPos = transformText.length;
- if ( openParPos > 0 && openParPos < closeParPos ) {
- const transformType = transformText.slice( 0, openParPos );
- const array = parseFloats( transformText.slice( openParPos + 1 ) );
- currentTransform.identity();
- switch ( transformType ) {
- case 'translate':
- if ( array.length >= 1 ) {
- const tx = array[ 0 ];
- let ty = 0;
- if ( array.length >= 2 ) {
- ty = array[ 1 ];
- }
- currentTransform.translate( tx, ty );
- }
- break;
- case 'rotate':
- if ( array.length >= 1 ) {
- let angle = 0;
- let cx = 0;
- let cy = 0;
- // Angle
- angle = array[ 0 ] * Math.PI / 180;
- if ( array.length >= 3 ) {
- // Center x, y
- cx = array[ 1 ];
- cy = array[ 2 ];
- }
- // Rotate around center (cx, cy)
- tempTransform1.makeTranslation( - cx, - cy );
- tempTransform2.makeRotation( angle );
- tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 );
- tempTransform1.makeTranslation( cx, cy );
- currentTransform.multiplyMatrices( tempTransform1, tempTransform3 );
- }
- break;
- case 'scale':
- if ( array.length >= 1 ) {
- const scaleX = array[ 0 ];
- let scaleY = scaleX;
- if ( array.length >= 2 ) {
- scaleY = array[ 1 ];
- }
- currentTransform.scale( scaleX, scaleY );
- }
- break;
- case 'skewX':
- if ( array.length === 1 ) {
- currentTransform.set(
- 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0,
- 0, 1, 0,
- 0, 0, 1
- );
- }
- break;
- case 'skewY':
- if ( array.length === 1 ) {
- currentTransform.set(
- 1, 0, 0,
- Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0,
- 0, 0, 1
- );
- }
- break;
- case 'matrix':
- if ( array.length === 6 ) {
- currentTransform.set(
- array[ 0 ], array[ 2 ], array[ 4 ],
- array[ 1 ], array[ 3 ], array[ 5 ],
- 0, 0, 1
- );
- }
- break;
- }
- transform.premultiply( currentTransform );
- }
- }
- return transform;
- }
- function transformPath( path, m ) {
- function transfVec2( v2 ) {
- tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m );
- v2.set( tempV3.x, tempV3.y );
- }
- function transfEllipseGeneric( curve ) {
- // For math description see:
- // https://math.stackexchange.com/questions/4544164
- const a = curve.xRadius;
- const b = curve.yRadius;
- const cosTheta = Math.cos( curve.aRotation );
- const sinTheta = Math.sin( curve.aRotation );
- const v1 = new Vector3( a * cosTheta, a * sinTheta, 0 );
- const v2 = new Vector3( - b * sinTheta, b * cosTheta, 0 );
- const f1 = v1.applyMatrix3( m );
- const f2 = v2.applyMatrix3( m );
- const mF = tempTransform0.set(
- f1.x, f2.x, 0,
- f1.y, f2.y, 0,
- 0, 0, 1,
- );
- const mFInv = tempTransform1.copy( mF ).invert();
- const mFInvT = tempTransform2.copy( mFInv ).transpose();
- const mQ = mFInvT.multiply( mFInv );
- const mQe = mQ.elements;
- const ed = eigenDecomposition( mQe[ 0 ], mQe[ 1 ], mQe[ 4 ] );
- const rt1sqrt = Math.sqrt( ed.rt1 );
- const rt2sqrt = Math.sqrt( ed.rt2 );
- curve.xRadius = 1 / rt1sqrt;
- curve.yRadius = 1 / rt2sqrt;
- curve.aRotation = Math.atan2( ed.sn, ed.cs );
- const isFullEllipse =
- ( curve.aEndAngle - curve.aStartAngle ) % ( 2 * Math.PI ) < Number.EPSILON;
- // Do not touch angles of a full ellipse because after transformation they
- // would converge to a single value effectively removing the whole curve
- if ( ! isFullEllipse ) {
- const mDsqrt = tempTransform1.set(
- rt1sqrt, 0, 0,
- 0, rt2sqrt, 0,
- 0, 0, 1,
- );
- const mRT = tempTransform2.set(
- ed.cs, ed.sn, 0,
- - ed.sn, ed.cs, 0,
- 0, 0, 1,
- );
- const mDRF = mDsqrt.multiply( mRT ).multiply( mF );
- const transformAngle = phi => {
- const { x: cosR, y: sinR } =
- new Vector3( Math.cos( phi ), Math.sin( phi ), 0 ).applyMatrix3( mDRF );
- return Math.atan2( sinR, cosR );
- };
- curve.aStartAngle = transformAngle( curve.aStartAngle );
- curve.aEndAngle = transformAngle( curve.aEndAngle );
- if ( isTransformFlipped( m ) ) {
- curve.aClockwise = ! curve.aClockwise;
- }
- }
- }
- function transfEllipseNoSkew( curve ) {
- // Faster shortcut if no skew is applied
- // (e.g, a euclidean transform of a group containing the ellipse)
- const sx = getTransformScaleX( m );
- const sy = getTransformScaleY( m );
- curve.xRadius *= sx;
- curve.yRadius *= sy;
- // Extract rotation angle from the matrix of form:
- //
- // | cosθ sx -sinθ sy |
- // | sinθ sx cosθ sy |
- //
- // Remembering that tanθ = sinθ / cosθ; and that
- // `sx`, `sy`, or both might be zero.
- const theta =
- sx > Number.EPSILON
- ? Math.atan2( m.elements[ 1 ], m.elements[ 0 ] )
- : Math.atan2( - m.elements[ 3 ], m.elements[ 4 ] );
- curve.aRotation += theta;
- if ( isTransformFlipped( m ) ) {
- curve.aStartAngle *= - 1;
- curve.aEndAngle *= - 1;
- curve.aClockwise = ! curve.aClockwise;
- }
- }
- const subPaths = path.subPaths;
- for ( let i = 0, n = subPaths.length; i < n; i ++ ) {
- const subPath = subPaths[ i ];
- const curves = subPath.curves;
- for ( let j = 0; j < curves.length; j ++ ) {
- const curve = curves[ j ];
- if ( curve.isLineCurve ) {
- transfVec2( curve.v1 );
- transfVec2( curve.v2 );
- } else if ( curve.isCubicBezierCurve ) {
- transfVec2( curve.v0 );
- transfVec2( curve.v1 );
- transfVec2( curve.v2 );
- transfVec2( curve.v3 );
- } else if ( curve.isQuadraticBezierCurve ) {
- transfVec2( curve.v0 );
- transfVec2( curve.v1 );
- transfVec2( curve.v2 );
- } else if ( curve.isEllipseCurve ) {
- // Transform ellipse center point
- tempV2.set( curve.aX, curve.aY );
- transfVec2( tempV2 );
- curve.aX = tempV2.x;
- curve.aY = tempV2.y;
- // Transform ellipse shape parameters
- if ( isTransformSkewed( m ) ) {
- transfEllipseGeneric( curve );
- } else {
- transfEllipseNoSkew( curve );
- }
- }
- }
- }
- }
- function isTransformFlipped( m ) {
- const te = m.elements;
- return te[ 0 ] * te[ 4 ] - te[ 1 ] * te[ 3 ] < 0;
- }
- function isTransformSkewed( m ) {
- const te = m.elements;
- const basisDot = te[ 0 ] * te[ 3 ] + te[ 1 ] * te[ 4 ];
- // Shortcut for trivial rotations and transformations
- if ( basisDot === 0 ) return false;
- const sx = getTransformScaleX( m );
- const sy = getTransformScaleY( m );
- return Math.abs( basisDot / ( sx * sy ) ) > Number.EPSILON;
- }
- function getTransformScaleX( m ) {
- const te = m.elements;
- return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] );
- }
- function getTransformScaleY( m ) {
- const te = m.elements;
- return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] );
- }
- function getTransformScale( m ) {
- const te = m.elements;
- const det = te[ 0 ] * te[ 4 ] - te[ 1 ] * te[ 3 ];
- return Math.sqrt( Math.abs( det ) );
- }
- // Calculates the eigensystem of a real symmetric 2x2 matrix
- // [ A B ]
- // [ B C ]
- // in the form
- // [ A B ] = [ cs -sn ] [ rt1 0 ] [ cs sn ]
- // [ B C ] [ sn cs ] [ 0 rt2 ] [ -sn cs ]
- // where rt1 >= rt2.
- //
- // Adapted from: https://www.mpi-hd.mpg.de/personalhomes/globes/3x3/index.html
- // -> Algorithms for real symmetric matrices -> Analytical (2x2 symmetric)
- function eigenDecomposition( A, B, C ) {
- let rt1, rt2, cs, sn, t;
- const sm = A + C;
- const df = A - C;
- const rt = Math.sqrt( df * df + 4 * B * B );
- if ( sm > 0 ) {
- rt1 = 0.5 * ( sm + rt );
- t = 1 / rt1;
- rt2 = A * t * C - B * t * B;
- } else if ( sm < 0 ) {
- rt2 = 0.5 * ( sm - rt );
- } else {
- // This case needs to be treated separately to avoid div by 0
- rt1 = 0.5 * rt;
- rt2 = - 0.5 * rt;
- }
- // Calculate eigenvectors
- if ( df > 0 ) {
- cs = df + rt;
- } else {
- cs = df - rt;
- }
- if ( Math.abs( cs ) > 2 * Math.abs( B ) ) {
- t = - 2 * B / cs;
- sn = 1 / Math.sqrt( 1 + t * t );
- cs = t * sn;
- } else if ( Math.abs( B ) === 0 ) {
- cs = 1;
- sn = 0;
- } else {
- t = - 0.5 * cs / B;
- cs = 1 / Math.sqrt( 1 + t * t );
- sn = t * cs;
- }
- if ( df > 0 ) {
- t = cs;
- cs = - sn;
- sn = t;
- }
- return { rt1, rt2, cs, sn };
- }
- //
- const paths = [];
- const stylesheets = {};
- const gradients = {};
- const transformStack = [];
- const tempTransform0 = new Matrix3();
- const tempTransform1 = new Matrix3();
- const tempTransform2 = new Matrix3();
- const tempTransform3 = new Matrix3();
- const tempV2 = new Vector2();
- const tempV3 = new Vector3();
- const currentTransform = new Matrix3();
- const xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml
- parseGradients( xml );
- parseNode( xml.documentElement, {
- fill: '#000',
- fillOpacity: 1,
- strokeOpacity: 1,
- strokeWidth: 1,
- strokeLineJoin: 'miter',
- strokeLineCap: 'butt',
- strokeMiterLimit: 4
- } );
- const data = { paths: paths, gradients: gradients, xml: xml.documentElement };
- // console.log( paths );
- return data;
- }
- /**
- * Creates a material for rendering the fill of the given path.
- *
- * @param {ShapePath} shapePath - The shape path.
- * @return {?MeshBasicMaterial} The fill material. `null` if the path has no fill.
- */
- static createFillMaterial( shapePath ) {
- const style = shapePath.userData.style;
- if ( style.fill === undefined || style.fill === 'none' ) return null;
- const color = shapePath.color;
- let texture = null;
- const urlMatch = GRADIENT_URL_RE.exec( style.fill );
- if ( urlMatch ) {
- const gradient = shapePath.userData.gradients && shapePath.userData.gradients[ urlMatch[ 1 ] ];
- texture = buildGradientTexture( gradient, shapePath );
- }
- const material = new MeshBasicMaterial( {
- opacity: style.fillOpacity * ( style.opacity || 1 ),
- transparent: true,
- side: DoubleSide,
- depthWrite: false,
- } );
- if ( texture !== null ) {
- material.map = texture;
- } else {
- material.color = color;
- }
- return material;
- }
- /**
- * Creates a material for rendering the stroke of the given path.
- *
- * @param {ShapePath} shapePath - The shape path.
- * @return {?MeshBasicMaterial} The stroke material. `null` if the path has no stroke.
- */
- static createStrokeMaterial( shapePath ) {
- const style = shapePath.userData.style;
- if ( style.stroke === undefined || style.stroke === 'none' ) return null;
- if ( GRADIENT_URL_RE.test( style.stroke ) ) {
- console.warn( 'THREE.SVGLoader: Gradient strokes are not supported.' );
- }
- return new MeshBasicMaterial( {
- color: new Color().setStyle( style.stroke, COLOR_SPACE_SVG ),
- opacity: style.strokeOpacity * ( style.opacity || 1 ),
- transparent: true,
- side: DoubleSide,
- depthWrite: false,
- } );
- }
- /**
- * Creates from the given shape path and array of shapes.
- *
- * @param {ShapePath} shapePath - The shape path.
- * @return {Array<Shape>} An array of shapes.
- */
- static createShapes( shapePath ) {
- // Point-in-polygon test using the even-odd ray-casting rule. Valid for
- // simple (non self-intersecting) polygons.
- function pointInPolygon( p, polygon ) {
- let inside = false;
- const n = polygon.length;
- for ( let i = 0, j = n - 1; i < n; j = i ++ ) {
- const a = polygon[ i ];
- const b = polygon[ j ];
- if ( ( a.y > p.y ) !== ( b.y > p.y ) &&
- p.x < ( b.x - a.x ) * ( p.y - a.y ) / ( b.y - a.y ) + a.x ) {
- inside = ! inside;
- }
- }
- return inside;
- }
- // Returns a point guaranteed to be strictly inside the given simple
- // polygon. First tries the bounding-box center; if that falls outside
- // the polygon, casts a horizontal ray at the center's y and picks the
- // midpoint between the first two sorted intercepts.
- //
- // Port of paper.js' Path#getInteriorPoint()
- // https://github.com/paperjs/paper.js/blob/develop/src/path/PathItem.Boolean.js
- function getInteriorPoint( polygon, boundingBox ) {
- const point = boundingBox.getCenter( new Vector2() );
- if ( pointInPolygon( point, polygon ) ) return point;
- const y = point.y;
- const intercepts = [];
- const n = polygon.length;
- for ( let i = 0; i < n; i ++ ) {
- const a = polygon[ i ];
- const b = polygon[ ( i + 1 ) % n ];
- // Half-open crossing rule — counts each vertex exactly once and
- // skips horizontal edges.
- if ( ( a.y > y ) !== ( b.y > y ) ) {
- const x = a.x + ( y - a.y ) * ( b.x - a.x ) / ( b.y - a.y );
- intercepts.push( x );
- }
- }
- if ( intercepts.length > 1 ) {
- intercepts.sort( ( a, b ) => a - b );
- point.x = ( intercepts[ 0 ] + intercepts[ 1 ] ) / 2;
- }
- return point;
- }
- // Resolve fill-rule. SVG defaults to 'nonzero'.
- let fillRule = ( shapePath.userData && shapePath.userData.style && shapePath.userData.style.fillRule ) || 'nonzero';
- if ( fillRule !== 'nonzero' && fillRule !== 'evenodd' ) {
- console.warn( 'THREE.SVGLoader: fill-rule "' + fillRule + '" is not supported, falling back to "nonzero".' );
- fillRule = 'nonzero';
- }
- // Predicate that decides whether a winding number falls inside the fill
- // region, per the SVG fill-rule spec. Works for negative windings too,
- // because JavaScript's bitwise AND preserves odd/even under two's
- // complement.
- const isInside = fillRule === 'nonzero'
- ? ( w => w !== 0 )
- : ( w => ( w & 1 ) !== 0 );
- // Build an entry per usable subpath. Self-winding follows the standard
- // convention used by ShapeUtils: counter-clockwise (signed area > 0)
- // contributes +1 to the winding number at an interior point,
- // clockwise contributes -1.
- const entries = [];
- for ( const subPath of shapePath.subPaths ) {
- const points = subPath.getPoints();
- if ( points.length < 3 ) continue;
- const area = ShapeUtils.area( points );
- if ( area === 0 ) continue;
- const boundingBox = new Box2();
- for ( let i = 0; i < points.length; i ++ ) boundingBox.expandByPoint( points[ i ] );
- entries.push( {
- subPath: subPath,
- points: points,
- boundingBox: boundingBox,
- interiorPoint: getInteriorPoint( points, boundingBox ),
- absArea: Math.abs( area ),
- winding: area < 0 ? - 1 : 1,
- container: null,
- exclude: false,
- role: null
- } );
- }
- // Sort by area descending. This guarantees that any subpath that could
- // contain `entries[i]` is located at a smaller index and has already
- // been processed when it's entries[i]'s turn. Port of paper.js'
- // reorientPaths() algorithm.
- entries.sort( ( a, b ) => b.absArea - a.absArea );
- // Walk already-processed entries from closest-in-size to largest,
- // stopping at the innermost container. Accumulate the container's
- // cumulative winding into this entry's winding so that the final value
- // equals the winding number at this entry's interior point.
- //
- // A subpath only contributes to the fill boundary when crossing it
- // actually flips the "insideness" per the fill rule; otherwise it's a
- // redundant overlap and gets excluded to avoid double-counting.
- for ( let i = 0; i < entries.length; i ++ ) {
- const entry = entries[ i ];
- let containerWinding = 0;
- for ( let j = i - 1; j >= 0; j -- ) {
- const candidate = entries[ j ];
- if ( ! candidate.boundingBox.containsPoint( entry.interiorPoint ) ) continue;
- if ( ! pointInPolygon( entry.interiorPoint, candidate.points ) ) continue;
- entry.container = candidate.exclude ? candidate.container : candidate;
- containerWinding = candidate.winding;
- entry.winding += containerWinding;
- break;
- }
- if ( isInside( entry.winding ) === isInside( containerWinding ) ) {
- entry.exclude = true;
- }
- }
- // Classify retained entries. An entry is an outer shape if it has no
- // container or if its container is itself a hole (a solid nested inside
- // a hole becomes a new top-level shape); otherwise it's a hole in its
- // container. Entries were already sorted outermost-first, so each
- // container's role is known by the time we look at it.
- for ( const entry of entries ) {
- if ( entry.exclude ) continue;
- entry.role = ( entry.container === null || entry.container.role === 'hole' ) ? 'outer' : 'hole';
- }
- // Build Shapes for outers first, then attach holes to their container's
- // Shape.
- const shapes = [];
- const shapeByEntry = new Map();
- for ( const entry of entries ) {
- if ( entry.exclude || entry.role !== 'outer' ) continue;
- const shape = new Shape();
- shape.curves = entry.subPath.curves;
- shapes.push( shape );
- shapeByEntry.set( entry, shape );
- }
- for ( const entry of entries ) {
- if ( entry.exclude || entry.role !== 'hole' ) continue;
- const shape = shapeByEntry.get( entry.container );
- if ( ! shape ) continue;
- const hole = new Path();
- hole.curves = entry.subPath.curves;
- shape.holes.push( hole );
- }
- return shapes;
- }
- /**
- * Returns a stroke style object from the given parameters.
- *
- * @param {number} [width=1] - The stroke width.
- * @param {string} [color='#000'] - The stroke color, as returned by {@link Color#getStyle}.
- * @param {'round'|'bevel'|'miter'|'miter-limit'} [lineJoin='miter'] - The line join style.
- * @param {'round'|'square'|'butt'} [lineCap='butt'] - The line cap style.
- * @param {number} [miterLimit=4] - Maximum join length, in multiples of the `width` parameter (join is truncated if it exceeds that distance).
- * @return {Object} The style object.
- */
- static getStrokeStyle( width, color, lineJoin, lineCap, miterLimit ) {
- width = width !== undefined ? width : 1;
- color = color !== undefined ? color : '#000';
- lineJoin = lineJoin !== undefined ? lineJoin : 'miter';
- lineCap = lineCap !== undefined ? lineCap : 'butt';
- miterLimit = miterLimit !== undefined ? miterLimit : 4;
- return {
- strokeColor: color,
- strokeWidth: width,
- strokeLineJoin: lineJoin,
- strokeLineCap: lineCap,
- strokeMiterLimit: miterLimit
- };
- }
- /**
- * Creates a stroke from an array of points.
- *
- * @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).
- * @param {Object} style - Object with SVG properties as returned by `SVGLoader.getStrokeStyle()`, or `SVGLoader.parse()` in the `path.userData.style` object.
- * @param {number} [arcDivisions=12] - Arc divisions for round joins and endcaps.
- * @param {number} [minDistance=0.001] - Points closer to this distance will be merged.
- * @return {?BufferGeometry} The stroke geometry. UV coordinates are generated ('u' along path. 'v' across it, from left to right).
- * Returns `null` if not geometry was generated.
- */
- static pointsToStroke( points, style, arcDivisions, minDistance ) {
- const vertices = [];
- const normals = [];
- const uvs = [];
- if ( SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) {
- return null;
- }
- const geometry = new BufferGeometry();
- geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
- geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
- geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
- return geometry;
- }
- /**
- * Creates a stroke from an array of points.
- *
- * @param {Array<Vector2>} points - The points in 2D space. Minimum 2 points.
- * @param {Object} style - Object with SVG properties as returned by `SVGLoader.getStrokeStyle()`, or `SVGLoader.parse()` in the `path.userData.style` object.
- * @param {number} [arcDivisions=12] - Arc divisions for round joins and endcaps.
- * @param {number} [minDistance=0.001] - Points closer to this distance will be merged.
- * @param {Array<number>} vertices - An array holding vertices.
- * @param {Array<number>} normals - An array holding normals.
- * @param {Array<number>} uvs - An array holding uvs.
- * @param {number} [vertexOffset=0] - The vertex offset.
- * @return {number} The number of vertices.
- */
- static pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset ) {
- // This function can be called to update existing arrays or buffers.
- // Accepts same parameters as pointsToStroke, plus the buffers and optional offset.
- // Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs)
- // Returns number of written vertices / normals / uvs pairs
- // if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers)
- // 'normals' and 'uvs' buffers are optional
- const tempV2_1 = new Vector2();
- const tempV2_2 = new Vector2();
- const tempV2_3 = new Vector2();
- const tempV2_4 = new Vector2();
- const tempV2_5 = new Vector2();
- const tempV2_6 = new Vector2();
- const tempV2_7 = new Vector2();
- const lastPointL = new Vector2();
- const lastPointR = new Vector2();
- const point0L = new Vector2();
- const point0R = new Vector2();
- const currentPointL = new Vector2();
- const currentPointR = new Vector2();
- const nextPointL = new Vector2();
- const nextPointR = new Vector2();
- const innerPoint = new Vector2();
- const outerPoint = new Vector2();
- arcDivisions = arcDivisions !== undefined ? arcDivisions : 12;
- minDistance = minDistance !== undefined ? minDistance : 0.001;
- vertexOffset = vertexOffset !== undefined ? vertexOffset : 0;
- // First ensure there are no duplicated points
- points = removeDuplicatedPoints( points );
- const numPoints = points.length;
- if ( numPoints < 2 ) return 0;
- const isClosed = points[ 0 ].equals( points[ numPoints - 1 ] );
- let currentPoint;
- let previousPoint = points[ 0 ];
- let nextPoint;
- const strokeWidth2 = style.strokeWidth / 2;
- const deltaU = 1 / ( numPoints - 1 );
- let u0 = 0, u1;
- let innerSideModified;
- let joinIsOnLeftSide;
- let isMiter;
- let initialJoinIsOnLeftSide = false;
- let numVertices = 0;
- let currentCoordinate = vertexOffset * 3;
- let currentCoordinateUV = vertexOffset * 2;
- // Get initial left and right stroke points
- getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 );
- lastPointL.copy( points[ 0 ] ).sub( tempV2_1 );
- lastPointR.copy( points[ 0 ] ).add( tempV2_1 );
- point0L.copy( lastPointL );
- point0R.copy( lastPointR );
- for ( let iPoint = 1; iPoint < numPoints; iPoint ++ ) {
- currentPoint = points[ iPoint ];
- // Get next point
- if ( iPoint === numPoints - 1 ) {
- if ( isClosed ) {
- // Skip duplicated initial point
- nextPoint = points[ 1 ];
- } else nextPoint = undefined;
- } else {
- nextPoint = points[ iPoint + 1 ];
- }
- // Normal of previous segment in tempV2_1
- const normal1 = tempV2_1;
- getNormal( previousPoint, currentPoint, normal1 );
- tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 );
- currentPointL.copy( currentPoint ).sub( tempV2_3 );
- currentPointR.copy( currentPoint ).add( tempV2_3 );
- u1 = u0 + deltaU;
- innerSideModified = false;
- if ( nextPoint !== undefined ) {
- // Normal of next segment in tempV2_2
- getNormal( currentPoint, nextPoint, tempV2_2 );
- tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 );
- nextPointL.copy( currentPoint ).sub( tempV2_3 );
- nextPointR.copy( currentPoint ).add( tempV2_3 );
- joinIsOnLeftSide = true;
- tempV2_3.subVectors( nextPoint, previousPoint );
- if ( normal1.dot( tempV2_3 ) < 0 ) {
- joinIsOnLeftSide = false;
- }
- if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide;
- tempV2_3.subVectors( nextPoint, currentPoint );
- tempV2_3.normalize();
- const dot = Math.abs( normal1.dot( tempV2_3 ) );
- // If path is straight, don't create join
- if ( dot > Number.EPSILON ) {
- // Compute inner and outer segment intersections
- const miterSide = strokeWidth2 / dot;
- tempV2_3.multiplyScalar( - miterSide );
- tempV2_4.subVectors( currentPoint, previousPoint );
- tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 );
- innerPoint.copy( tempV2_5 ).negate();
- const miterLength2 = tempV2_5.length();
- const segmentLengthPrev = tempV2_4.length();
- tempV2_4.divideScalar( segmentLengthPrev );
- tempV2_6.subVectors( nextPoint, currentPoint );
- const segmentLengthNext = tempV2_6.length();
- tempV2_6.divideScalar( segmentLengthNext );
- // Check that previous and next segments doesn't overlap with the innerPoint of intersection
- if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) {
- innerSideModified = true;
- }
- outerPoint.copy( tempV2_5 ).add( currentPoint );
- innerPoint.add( currentPoint );
- // in-loop fold detection to mitigate #25326
- if ( innerSideModified ) {
- // when the second triangle's signed area would flip, snap innerPoint to the previous inner-side vertex
- const refPt = joinIsOnLeftSide ? lastPointR : lastPointL;
- const foldCross = ( outerPoint.x - refPt.x ) * ( innerPoint.y - refPt.y )
- - ( outerPoint.y - refPt.y ) * ( innerPoint.x - refPt.x );
- if ( ( joinIsOnLeftSide && foldCross < 0 ) || ( ! joinIsOnLeftSide && foldCross > 0 ) ) {
- innerPoint.copy( refPt );
- }
- }
- isMiter = false;
- if ( innerSideModified ) {
- if ( joinIsOnLeftSide ) {
- nextPointR.copy( innerPoint );
- currentPointR.copy( innerPoint );
- } else {
- nextPointL.copy( innerPoint );
- currentPointL.copy( innerPoint );
- }
- } else {
- // The segment triangles are generated here if there was overlapping
- makeSegmentTriangles();
- }
- switch ( style.strokeLineJoin ) {
- case 'bevel':
- makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
- break;
- case 'round':
- // Segment triangles
- createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
- // Join triangles
- if ( joinIsOnLeftSide ) {
- makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 );
- } else {
- makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 );
- }
- break;
- case 'miter':
- case 'miter-clip':
- default:
- const miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2;
- if ( miterFraction < 1 ) {
- // The join miter length exceeds the miter limit
- if ( style.strokeLineJoin !== 'miter-clip' ) {
- makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 );
- break;
- } else {
- // Segment triangles
- createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified );
- // Miter-clip join triangles
- if ( joinIsOnLeftSide ) {
- tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL );
- tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL );
- addVertex( currentPointL, u1, 0 );
- addVertex( tempV2_6, u1, 0 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( tempV2_6, u1, 0 );
- addVertex( tempV2_7, u1, 0 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( tempV2_7, u1, 0 );
- addVertex( nextPointL, u1, 0 );
- } else {
- tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR );
- tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR );
- addVertex( currentPointR, u1, 1 );
- addVertex( tempV2_6, u1, 1 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( tempV2_6, u1, 1 );
- addVertex( tempV2_7, u1, 1 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( tempV2_7, u1, 1 );
- addVertex( nextPointR, u1, 1 );
- }
- }
- } else {
- // Miter join segment triangles
- if ( innerSideModified ) {
- // Optimized segment + join triangles
- if ( joinIsOnLeftSide ) {
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( outerPoint, u1, 0 );
- addVertex( lastPointR, u0, 1 );
- addVertex( outerPoint, u1, 0 );
- addVertex( innerPoint, u1, 1 );
- } else {
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( outerPoint, u1, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( innerPoint, u1, 0 );
- addVertex( outerPoint, u1, 1 );
- }
- if ( joinIsOnLeftSide ) {
- nextPointL.copy( outerPoint );
- } else {
- nextPointR.copy( outerPoint );
- }
- } else {
- // Add extra miter join triangles
- if ( joinIsOnLeftSide ) {
- addVertex( currentPointL, u1, 0 );
- addVertex( outerPoint, u1, 0 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( outerPoint, u1, 0 );
- addVertex( nextPointL, u1, 0 );
- } else {
- addVertex( currentPointR, u1, 1 );
- addVertex( outerPoint, u1, 1 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( outerPoint, u1, 1 );
- addVertex( nextPointR, u1, 1 );
- }
- }
- isMiter = true;
- }
- break;
- }
- } else {
- // The segment triangles are generated here when two consecutive points are collinear
- makeSegmentTriangles();
- }
- } else {
- // The segment triangles are generated here if it is the ending segment
- makeSegmentTriangles();
- }
- if ( ! isClosed && iPoint === numPoints - 1 ) {
- // Start line endcap
- addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 );
- }
- // Increment loop variables
- u0 = u1;
- previousPoint = currentPoint;
- lastPointL.copy( nextPointL );
- lastPointR.copy( nextPointR );
- }
- if ( ! isClosed ) {
- // Ending line endcap
- addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 );
- } else if ( innerSideModified && vertices ) {
- // Modify path first segment vertices to adjust to the segments inner and outer intersections
- let lastOuter = outerPoint;
- let lastInner = innerPoint;
- if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) {
- lastOuter = innerPoint;
- lastInner = outerPoint;
- }
- if ( joinIsOnLeftSide ) {
- if ( isMiter || initialJoinIsOnLeftSide ) {
- lastInner.toArray( vertices, 0 * 3 );
- lastInner.toArray( vertices, 3 * 3 );
- if ( isMiter ) {
- lastOuter.toArray( vertices, 1 * 3 );
- }
- }
- } else {
- if ( isMiter || ! initialJoinIsOnLeftSide ) {
- lastInner.toArray( vertices, 1 * 3 );
- lastInner.toArray( vertices, 3 * 3 );
- if ( isMiter ) {
- lastOuter.toArray( vertices, 0 * 3 );
- }
- }
- }
- }
- // Second fix for #25326: Scan for reamining flipped (CW) triangles and collapse them to
- // degenerated ones. This is safe and leaves no "holes" in the stroke because the flipped
- // triangle's area is covered by neighbouring (CCW) triangles.
- if ( vertices ) {
- const tri = [ new Vector2(), new Vector2(), new Vector2() ];
- const startFloat = vertexOffset * 3;
- for ( let t = startFloat; t < currentCoordinate; t += 9 ) {
- tri[ 0 ].set( vertices[ t ], vertices[ t + 1 ] );
- tri[ 1 ].set( vertices[ t + 3 ], vertices[ t + 4 ] );
- tri[ 2 ].set( vertices[ t + 6 ], vertices[ t + 7 ] );
- if ( ShapeUtils.area( tri ) < 0 ) {
- vertices[ t + 3 ] = tri[ 0 ].x;
- vertices[ t + 4 ] = tri[ 0 ].y;
- }
- }
- }
- return numVertices;
- // -- End of algorithm
- // -- Functions
- function getNormal( p1, p2, result ) {
- result.subVectors( p2, p1 );
- return result.set( - result.y, result.x ).normalize();
- }
- function addVertex( position, u, v ) {
- if ( vertices ) {
- vertices[ currentCoordinate ] = position.x;
- vertices[ currentCoordinate + 1 ] = position.y;
- vertices[ currentCoordinate + 2 ] = 0;
- if ( normals ) {
- normals[ currentCoordinate ] = 0;
- normals[ currentCoordinate + 1 ] = 0;
- normals[ currentCoordinate + 2 ] = 1;
- }
- currentCoordinate += 3;
- if ( uvs ) {
- uvs[ currentCoordinateUV ] = u;
- uvs[ currentCoordinateUV + 1 ] = v;
- currentCoordinateUV += 2;
- }
- }
- numVertices += 3;
- }
- function makeCircularSector( center, p1, p2, u, v ) {
- // param p1, p2: Points in the circle arc.
- // p1 and p2 are in clockwise direction.
- tempV2_1.copy( p1 ).sub( center ).normalize();
- tempV2_2.copy( p2 ).sub( center ).normalize();
- let angle = Math.PI;
- const dot = tempV2_1.dot( tempV2_2 );
- if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) );
- angle /= arcDivisions;
- tempV2_3.copy( p1 );
- for ( let i = 0, il = arcDivisions - 1; i < il; i ++ ) {
- tempV2_4.copy( tempV2_3 ).rotateAround( center, angle );
- addVertex( tempV2_3, u, v );
- addVertex( tempV2_4, u, v );
- addVertex( center, u, 0.5 );
- tempV2_3.copy( tempV2_4 );
- }
- addVertex( tempV2_3, u, v );
- addVertex( p2, u, v );
- addVertex( center, u, 0.5 );
- }
- function makeSegmentTriangles() {
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( currentPointL, u1, 0 );
- addVertex( lastPointR, u0, 1 );
- addVertex( currentPointL, u1, 0 );
- addVertex( currentPointR, u1, 1 );
- }
- function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) {
- if ( innerSideModified ) {
- // Optimized segment + bevel triangles
- if ( joinIsOnLeftSide ) {
- // Path segments triangles
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( currentPointL, u1, 0 );
- addVertex( lastPointR, u0, 1 );
- addVertex( currentPointL, u1, 0 );
- addVertex( innerPoint, u1, 1 );
- // Bevel join triangle
- addVertex( currentPointL, u, 0 );
- addVertex( nextPointL, u, 0 );
- addVertex( innerPoint, u, 0.5 );
- } else {
- // Path segments triangles
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( currentPointR, u1, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( innerPoint, u1, 0 );
- addVertex( currentPointR, u1, 1 );
- // Bevel join triangle
- addVertex( currentPointR, u, 1 );
- addVertex( innerPoint, u, 0 );
- addVertex( nextPointR, u, 1 );
- }
- } else {
- // Bevel join triangle. The segment triangles are done in the main loop
- if ( joinIsOnLeftSide ) {
- addVertex( currentPointL, u, 0 );
- addVertex( nextPointL, u, 0 );
- addVertex( currentPoint, u, 0.5 );
- } else {
- addVertex( currentPointR, u, 1 );
- addVertex( nextPointR, u, 0 );
- addVertex( currentPoint, u, 0.5 );
- }
- }
- }
- function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) {
- if ( innerSideModified ) {
- if ( joinIsOnLeftSide ) {
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( currentPointL, u1, 0 );
- addVertex( lastPointR, u0, 1 );
- addVertex( currentPointL, u1, 0 );
- addVertex( innerPoint, u1, 1 );
- addVertex( currentPointL, u0, 0 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( innerPoint, u1, 1 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( nextPointL, u0, 0 );
- addVertex( innerPoint, u1, 1 );
- } else {
- addVertex( lastPointR, u0, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( currentPointR, u1, 1 );
- addVertex( lastPointL, u0, 0 );
- addVertex( innerPoint, u1, 0 );
- addVertex( currentPointR, u1, 1 );
- addVertex( currentPointR, u0, 1 );
- addVertex( innerPoint, u1, 0 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( currentPoint, u1, 0.5 );
- addVertex( innerPoint, u1, 0 );
- addVertex( nextPointR, u0, 1 );
- }
- }
- }
- function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) {
- // param center: End point of the path
- // param p1, p2: Left and right cap points
- switch ( style.strokeLineCap ) {
- case 'round':
- if ( start ) {
- makeCircularSector( center, p2, p1, u, 0.5 );
- } else {
- makeCircularSector( center, p1, p2, u, 0.5 );
- }
- break;
- case 'square':
- if ( start ) {
- tempV2_1.subVectors( p1, center );
- tempV2_2.set( tempV2_1.y, - tempV2_1.x );
- tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
- tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
- // Modify already existing vertices
- if ( joinIsOnLeftSide ) {
- tempV2_3.toArray( vertices, 1 * 3 );
- tempV2_4.toArray( vertices, 0 * 3 );
- tempV2_4.toArray( vertices, 3 * 3 );
- } else {
- tempV2_3.toArray( vertices, 1 * 3 );
- // using tempV2_4 to update 3rd vertex if the uv.y of 3rd vertex is 1
- uvs[ 3 * 2 + 1 ] === 1 ? tempV2_4.toArray( vertices, 3 * 3 ) : tempV2_3.toArray( vertices, 3 * 3 );
- tempV2_4.toArray( vertices, 0 * 3 );
- }
- } else {
- tempV2_1.subVectors( p2, center );
- tempV2_2.set( tempV2_1.y, - tempV2_1.x );
- tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center );
- tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center );
- const vl = vertices.length;
- // Modify already existing vertices
- if ( joinIsOnLeftSide ) {
- tempV2_3.toArray( vertices, vl - 1 * 3 );
- tempV2_4.toArray( vertices, vl - 2 * 3 );
- tempV2_4.toArray( vertices, vl - 4 * 3 );
- } else {
- tempV2_4.toArray( vertices, vl - 2 * 3 );
- tempV2_3.toArray( vertices, vl - 1 * 3 );
- tempV2_4.toArray( vertices, vl - 4 * 3 );
- }
- }
- break;
- case 'butt':
- default:
- // Nothing to do here
- break;
- }
- }
- function removeDuplicatedPoints( points ) {
- // Creates a new array if necessary with duplicated points removed.
- // This does not remove duplicated initial and ending points of a closed path.
- let dupPoints = false;
- for ( let i = 1, n = points.length - 1; i < n; i ++ ) {
- if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) {
- dupPoints = true;
- break;
- }
- }
- if ( ! dupPoints ) return points;
- const newPoints = [];
- newPoints.push( points[ 0 ] );
- for ( let i = 1, n = points.length - 1; i < n; i ++ ) {
- if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) {
- newPoints.push( points[ i ] );
- }
- }
- newPoints.push( points[ points.length - 1 ] );
- return newPoints;
- }
- }
- }
- const GRADIENT_URL_RE = /^\s*url\(\s*(?:["']\s*)?#([^)'"\s]+)(?:\s*["'])?\s*\)\s*$/;
- // Bakes a gradient into a CanvasTexture in its own local frame and configures
- // `texture.matrix` (with `matrixAutoUpdate = false`) so that shape-space UVs —
- // which, because transformPath bakes the world matrix into geometry vertex
- // positions, equal world xy — sample the correct gradient color. The caller
- // just sets `material.map = texture`; no bounding box, no geometry, no
- // per-vertex UV work required.
- function buildGradientTexture( gradient, shapePath, resolution = 256 ) {
- if ( ! gradient || ! Array.isArray( gradient.stops ) || gradient.stops.length === 0 ) return null;
- const worldTransform = shapePath.userData.transform;
- const isBBoxUnits = gradient.gradientUnits === 'objectBoundingBox';
- // For objectBoundingBox gradients we need the element's local bounding
- // box. Path points are in world space (transformPath already applied the
- // world transform), so invert that first.
- let localBBox = null;
- if ( isBBoxUnits ) {
- localBBox = computeLocalBBox( shapePath, worldTransform );
- if ( localBBox === null ) return null;
- }
- // Resolves a gradient-space point to the geometry's (world) coordinate
- // space: gradient coord → gradientTransform → target coord → (for
- // objectBoundingBox: bbox → local) → worldTransform → world.
- function resolvePoint( x, y, out ) {
- out.set( x, y, 1 );
- if ( gradient.gradientTransform ) out.applyMatrix3( gradient.gradientTransform );
- if ( isBBoxUnits ) out.set(
- localBBox.minX + out.x * localBBox.width,
- localBBox.minY + out.y * localBBox.height,
- 1,
- );
- if ( worldTransform ) out.applyMatrix3( worldTransform );
- }
- const canvas = document.createElement( 'canvas' );
- let textureMatrix;
- if ( gradient.type === 'linearGradient' ) {
- // 1D bake along the gradient vector.
- canvas.width = resolution;
- canvas.height = 1;
- const ctx = canvas.getContext( '2d' );
- const grad = ctx.createLinearGradient( 0, 0, resolution, 0 );
- addStops( grad, gradient.stops );
- ctx.fillStyle = grad;
- ctx.fillRect( 0, 0, resolution, 1 );
- const p1 = new Vector3();
- const p2 = new Vector3();
- resolvePoint( gradient.x1, gradient.y1, p1 );
- resolvePoint( gradient.x2, gradient.y2, p2 );
- const dx = p2.x - p1.x;
- const dy = p2.y - p1.y;
- const len2 = dx * dx + dy * dy || 1e-20;
- const a = dx / len2;
- const b = dy / len2;
- const c = - ( a * p1.x + b * p1.y );
- // M * (vx, vy, 1) = (t, 0.5, 1)
- textureMatrix = new Matrix3().set(
- a, b, c,
- 0, 0, 0.5,
- 0, 0, 1,
- );
- } else {
- // Resolve cx/cy/fx/fy into local space and scale r per the SVG spec
- // (objectBoundingBox scales lengths by sqrt((w² + h²) / 2)). The canvas
- // only draws circular radial gradients, so any ellipticity induced by
- // a non-uniform world transform is picked up later via the UV matrix.
- let cx = gradient.cx, cy = gradient.cy;
- let fx = gradient.fx, fy = gradient.fy;
- let r = gradient.r;
- if ( gradient.gradientTransform ) {
- const tmp = new Vector3();
- tmp.set( cx, cy, 1 ).applyMatrix3( gradient.gradientTransform );
- cx = tmp.x; cy = tmp.y;
- tmp.set( fx, fy, 1 ).applyMatrix3( gradient.gradientTransform );
- fx = tmp.x; fy = tmp.y;
- }
- if ( isBBoxUnits ) {
- cx = localBBox.minX + cx * localBBox.width;
- cy = localBBox.minY + cy * localBBox.height;
- fx = localBBox.minX + fx * localBBox.width;
- fy = localBBox.minY + fy * localBBox.height;
- r = r * Math.sqrt( ( localBBox.width * localBBox.width + localBBox.height * localBBox.height ) / 2 );
- }
- if ( r <= 0 ) return null;
- // 2D bake in the gradient's local frame, covering [cx-r, cx+r]².
- canvas.width = resolution;
- canvas.height = resolution;
- const ctx = canvas.getContext( '2d' );
- const localMinX = cx - r;
- const localMinY = cy - r;
- const localSpan = 2 * r;
- const scale = resolution / localSpan;
- // Canvas pixel = (local - localMin) * scale.
- ctx.setTransform( scale, 0, 0, scale, - localMinX * scale, - localMinY * scale );
- const grad = ctx.createRadialGradient( fx, fy, 0, cx, cy, r );
- addStops( grad, gradient.stops );
- ctx.fillStyle = grad;
- ctx.fillRect( localMinX, localMinY, localSpan, localSpan );
- // UV matrix: world → local (via worldTransform⁻¹) → normalized canvas UV.
- const inv = worldTransform ? worldTransform.clone().invert() : new Matrix3();
- const norm = new Matrix3().set(
- 1 / localSpan, 0, - localMinX / localSpan,
- 0, 1 / localSpan, - localMinY / localSpan,
- 0, 0, 1,
- );
- textureMatrix = norm.multiply( inv );
- }
- const texture = new CanvasTexture( canvas );
- texture.colorSpace = COLOR_SPACE_SVG;
- texture.flipY = false;
- texture.matrixAutoUpdate = false;
- texture.matrix = textureMatrix;
- const wrap = gradient.spreadMethod === 'reflect' ? MirroredRepeatWrapping
- : gradient.spreadMethod === 'repeat' ? RepeatWrapping
- : ClampToEdgeWrapping;
- texture.wrapS = wrap;
- texture.wrapT = wrap;
- return texture;
- }
- function computeLocalBBox( shapePath, worldTransform ) {
- const inv = worldTransform ? worldTransform.clone().invert() : null;
- const tmp = new Vector2();
- const box = new Box2();
- for ( const subPath of shapePath.subPaths ) {
- for ( const p of subPath.getPoints() ) {
- tmp.copy( p );
- if ( inv ) tmp.applyMatrix3( inv );
- box.expandByPoint( tmp );
- }
- }
- if ( box.isEmpty() ) return null;
- return { minX: box.min.x, minY: box.min.y, width: box.max.x - box.min.x, height: box.max.y - box.min.y };
- }
- function addStops( canvasGradient, stops ) {
- const tmpColor = new Color();
- for ( const stop of stops ) {
- let css = stop.color;
- if ( stop.opacity < 1 ) {
- tmpColor.setStyle( stop.color, COLOR_SPACE_SVG );
- const m = /rgb\(([^)]+)\)/.exec( tmpColor.getStyle( COLOR_SPACE_SVG ) );
- if ( m ) css = `rgba(${m[ 1 ]},${stop.opacity})`;
- }
- canvasGradient.addColorStop( Math.max( 0, Math.min( 1, stop.offset ) ), css );
- }
- }
- export { SVGLoader };
|