| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.G = {}));
- }(this, (function (exports) { 'use strict';
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
- var rbush = createCommonjsModule(function (module, exports) {
- (function (global, factory) {
- module.exports = factory() ;
- }(commonjsGlobal, function () {
- function quickselect(arr, k, left, right, compare) {
- quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
- }
- function quickselectStep(arr, k, left, right, compare) {
- while (right > left) {
- if (right - left > 600) {
- var n = right - left + 1;
- var m = k - left + 1;
- var z = Math.log(n);
- var s = 0.5 * Math.exp(2 * z / 3);
- var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
- var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
- var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
- quickselectStep(arr, k, newLeft, newRight, compare);
- }
- var t = arr[k];
- var i = left;
- var j = right;
- swap(arr, left, k);
- if (compare(arr[right], t) > 0) { swap(arr, left, right); }
- while (i < j) {
- swap(arr, i, j);
- i++;
- j--;
- while (compare(arr[i], t) < 0) { i++; }
- while (compare(arr[j], t) > 0) { j--; }
- }
- if (compare(arr[left], t) === 0) { swap(arr, left, j); }
- else {
- j++;
- swap(arr, j, right);
- }
- if (j <= k) { left = j + 1; }
- if (k <= j) { right = j - 1; }
- }
- }
- function swap(arr, i, j) {
- var tmp = arr[i];
- arr[i] = arr[j];
- arr[j] = tmp;
- }
- function defaultCompare(a, b) {
- return a < b ? -1 : a > b ? 1 : 0;
- }
- var RBush = function RBush(maxEntries) {
- if ( maxEntries === void 0 ) maxEntries = 9;
- // max entries in a node is 9 by default; min node fill is 40% for best performance
- this._maxEntries = Math.max(4, maxEntries);
- this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
- this.clear();
- };
- RBush.prototype.all = function all () {
- return this._all(this.data, []);
- };
- RBush.prototype.search = function search (bbox) {
- var node = this.data;
- var result = [];
- if (!intersects(bbox, node)) { return result; }
- var toBBox = this.toBBox;
- var nodesToSearch = [];
- while (node) {
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- var childBBox = node.leaf ? toBBox(child) : child;
- if (intersects(bbox, childBBox)) {
- if (node.leaf) { result.push(child); }
- else if (contains(bbox, childBBox)) { this._all(child, result); }
- else { nodesToSearch.push(child); }
- }
- }
- node = nodesToSearch.pop();
- }
- return result;
- };
- RBush.prototype.collides = function collides (bbox) {
- var node = this.data;
- if (!intersects(bbox, node)) { return false; }
- var nodesToSearch = [];
- while (node) {
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- var childBBox = node.leaf ? this.toBBox(child) : child;
- if (intersects(bbox, childBBox)) {
- if (node.leaf || contains(bbox, childBBox)) { return true; }
- nodesToSearch.push(child);
- }
- }
- node = nodesToSearch.pop();
- }
- return false;
- };
- RBush.prototype.load = function load (data) {
- if (!(data && data.length)) { return this; }
- if (data.length < this._minEntries) {
- for (var i = 0; i < data.length; i++) {
- this.insert(data[i]);
- }
- return this;
- }
- // recursively build the tree with the given data from scratch using OMT algorithm
- var node = this._build(data.slice(), 0, data.length - 1, 0);
- if (!this.data.children.length) {
- // save as is if tree is empty
- this.data = node;
- } else if (this.data.height === node.height) {
- // split root if trees have the same height
- this._splitRoot(this.data, node);
- } else {
- if (this.data.height < node.height) {
- // swap trees if inserted one is bigger
- var tmpNode = this.data;
- this.data = node;
- node = tmpNode;
- }
- // insert the small tree into the large tree at appropriate level
- this._insert(node, this.data.height - node.height - 1, true);
- }
- return this;
- };
- RBush.prototype.insert = function insert (item) {
- if (item) { this._insert(item, this.data.height - 1); }
- return this;
- };
- RBush.prototype.clear = function clear () {
- this.data = createNode([]);
- return this;
- };
- RBush.prototype.remove = function remove (item, equalsFn) {
- if (!item) { return this; }
- var node = this.data;
- var bbox = this.toBBox(item);
- var path = [];
- var indexes = [];
- var i, parent, goingUp;
- // depth-first iterative tree traversal
- while (node || path.length) {
- if (!node) { // go up
- node = path.pop();
- parent = path[path.length - 1];
- i = indexes.pop();
- goingUp = true;
- }
- if (node.leaf) { // check current node
- var index = findItem(item, node.children, equalsFn);
- if (index !== -1) {
- // item found, remove the item and condense tree upwards
- node.children.splice(index, 1);
- path.push(node);
- this._condense(path);
- return this;
- }
- }
- if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
- path.push(node);
- indexes.push(i);
- i = 0;
- parent = node;
- node = node.children[0];
- } else if (parent) { // go right
- i++;
- node = parent.children[i];
- goingUp = false;
- } else { node = null; } // nothing found
- }
- return this;
- };
- RBush.prototype.toBBox = function toBBox (item) { return item; };
- RBush.prototype.compareMinX = function compareMinX (a, b) { return a.minX - b.minX; };
- RBush.prototype.compareMinY = function compareMinY (a, b) { return a.minY - b.minY; };
- RBush.prototype.toJSON = function toJSON () { return this.data; };
- RBush.prototype.fromJSON = function fromJSON (data) {
- this.data = data;
- return this;
- };
- RBush.prototype._all = function _all (node, result) {
- var nodesToSearch = [];
- while (node) {
- if (node.leaf) { result.push.apply(result, node.children); }
- else { nodesToSearch.push.apply(nodesToSearch, node.children); }
- node = nodesToSearch.pop();
- }
- return result;
- };
- RBush.prototype._build = function _build (items, left, right, height) {
- var N = right - left + 1;
- var M = this._maxEntries;
- var node;
- if (N <= M) {
- // reached leaf level; return leaf
- node = createNode(items.slice(left, right + 1));
- calcBBox(node, this.toBBox);
- return node;
- }
- if (!height) {
- // target height of the bulk-loaded tree
- height = Math.ceil(Math.log(N) / Math.log(M));
- // target number of root entries to maximize storage utilization
- M = Math.ceil(N / Math.pow(M, height - 1));
- }
- node = createNode([]);
- node.leaf = false;
- node.height = height;
- // split the items into M mostly square tiles
- var N2 = Math.ceil(N / M);
- var N1 = N2 * Math.ceil(Math.sqrt(M));
- multiSelect(items, left, right, N1, this.compareMinX);
- for (var i = left; i <= right; i += N1) {
- var right2 = Math.min(i + N1 - 1, right);
- multiSelect(items, i, right2, N2, this.compareMinY);
- for (var j = i; j <= right2; j += N2) {
- var right3 = Math.min(j + N2 - 1, right2);
- // pack each entry recursively
- node.children.push(this._build(items, j, right3, height - 1));
- }
- }
- calcBBox(node, this.toBBox);
- return node;
- };
- RBush.prototype._chooseSubtree = function _chooseSubtree (bbox, node, level, path) {
- while (true) {
- path.push(node);
- if (node.leaf || path.length - 1 === level) { break; }
- var minArea = Infinity;
- var minEnlargement = Infinity;
- var targetNode = (void 0);
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- var area = bboxArea(child);
- var enlargement = enlargedArea(bbox, child) - area;
- // choose entry with the least area enlargement
- if (enlargement < minEnlargement) {
- minEnlargement = enlargement;
- minArea = area < minArea ? area : minArea;
- targetNode = child;
- } else if (enlargement === minEnlargement) {
- // otherwise choose one with the smallest area
- if (area < minArea) {
- minArea = area;
- targetNode = child;
- }
- }
- }
- node = targetNode || node.children[0];
- }
- return node;
- };
- RBush.prototype._insert = function _insert (item, level, isNode) {
- var bbox = isNode ? item : this.toBBox(item);
- var insertPath = [];
- // find the best node for accommodating the item, saving all nodes along the path too
- var node = this._chooseSubtree(bbox, this.data, level, insertPath);
- // put the item into the node
- node.children.push(item);
- extend(node, bbox);
- // split on node overflow; propagate upwards if necessary
- while (level >= 0) {
- if (insertPath[level].children.length > this._maxEntries) {
- this._split(insertPath, level);
- level--;
- } else { break; }
- }
- // adjust bboxes along the insertion path
- this._adjustParentBBoxes(bbox, insertPath, level);
- };
- // split overflowed node into two
- RBush.prototype._split = function _split (insertPath, level) {
- var node = insertPath[level];
- var M = node.children.length;
- var m = this._minEntries;
- this._chooseSplitAxis(node, m, M);
- var splitIndex = this._chooseSplitIndex(node, m, M);
- var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
- newNode.height = node.height;
- newNode.leaf = node.leaf;
- calcBBox(node, this.toBBox);
- calcBBox(newNode, this.toBBox);
- if (level) { insertPath[level - 1].children.push(newNode); }
- else { this._splitRoot(node, newNode); }
- };
- RBush.prototype._splitRoot = function _splitRoot (node, newNode) {
- // split root node
- this.data = createNode([node, newNode]);
- this.data.height = node.height + 1;
- this.data.leaf = false;
- calcBBox(this.data, this.toBBox);
- };
- RBush.prototype._chooseSplitIndex = function _chooseSplitIndex (node, m, M) {
- var index;
- var minOverlap = Infinity;
- var minArea = Infinity;
- for (var i = m; i <= M - m; i++) {
- var bbox1 = distBBox(node, 0, i, this.toBBox);
- var bbox2 = distBBox(node, i, M, this.toBBox);
- var overlap = intersectionArea(bbox1, bbox2);
- var area = bboxArea(bbox1) + bboxArea(bbox2);
- // choose distribution with minimum overlap
- if (overlap < minOverlap) {
- minOverlap = overlap;
- index = i;
- minArea = area < minArea ? area : minArea;
- } else if (overlap === minOverlap) {
- // otherwise choose distribution with minimum area
- if (area < minArea) {
- minArea = area;
- index = i;
- }
- }
- }
- return index || M - m;
- };
- // sorts node children by the best axis for split
- RBush.prototype._chooseSplitAxis = function _chooseSplitAxis (node, m, M) {
- var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
- var compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
- var xMargin = this._allDistMargin(node, m, M, compareMinX);
- var yMargin = this._allDistMargin(node, m, M, compareMinY);
- // if total distributions margin value is minimal for x, sort by minX,
- // otherwise it's already sorted by minY
- if (xMargin < yMargin) { node.children.sort(compareMinX); }
- };
- // total margin of all possible split distributions where each node is at least m full
- RBush.prototype._allDistMargin = function _allDistMargin (node, m, M, compare) {
- node.children.sort(compare);
- var toBBox = this.toBBox;
- var leftBBox = distBBox(node, 0, m, toBBox);
- var rightBBox = distBBox(node, M - m, M, toBBox);
- var margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);
- for (var i = m; i < M - m; i++) {
- var child = node.children[i];
- extend(leftBBox, node.leaf ? toBBox(child) : child);
- margin += bboxMargin(leftBBox);
- }
- for (var i$1 = M - m - 1; i$1 >= m; i$1--) {
- var child$1 = node.children[i$1];
- extend(rightBBox, node.leaf ? toBBox(child$1) : child$1);
- margin += bboxMargin(rightBBox);
- }
- return margin;
- };
- RBush.prototype._adjustParentBBoxes = function _adjustParentBBoxes (bbox, path, level) {
- // adjust bboxes along the given tree path
- for (var i = level; i >= 0; i--) {
- extend(path[i], bbox);
- }
- };
- RBush.prototype._condense = function _condense (path) {
- // go through the path, removing empty nodes and updating bboxes
- for (var i = path.length - 1, siblings = (void 0); i >= 0; i--) {
- if (path[i].children.length === 0) {
- if (i > 0) {
- siblings = path[i - 1].children;
- siblings.splice(siblings.indexOf(path[i]), 1);
- } else { this.clear(); }
- } else { calcBBox(path[i], this.toBBox); }
- }
- };
- function findItem(item, items, equalsFn) {
- if (!equalsFn) { return items.indexOf(item); }
- for (var i = 0; i < items.length; i++) {
- if (equalsFn(item, items[i])) { return i; }
- }
- return -1;
- }
- // calculate node's bbox from bboxes of its children
- function calcBBox(node, toBBox) {
- distBBox(node, 0, node.children.length, toBBox, node);
- }
- // min bounding rectangle of node children from k to p-1
- function distBBox(node, k, p, toBBox, destNode) {
- if (!destNode) { destNode = createNode(null); }
- destNode.minX = Infinity;
- destNode.minY = Infinity;
- destNode.maxX = -Infinity;
- destNode.maxY = -Infinity;
- for (var i = k; i < p; i++) {
- var child = node.children[i];
- extend(destNode, node.leaf ? toBBox(child) : child);
- }
- return destNode;
- }
- function extend(a, b) {
- a.minX = Math.min(a.minX, b.minX);
- a.minY = Math.min(a.minY, b.minY);
- a.maxX = Math.max(a.maxX, b.maxX);
- a.maxY = Math.max(a.maxY, b.maxY);
- return a;
- }
- function compareNodeMinX(a, b) { return a.minX - b.minX; }
- function compareNodeMinY(a, b) { return a.minY - b.minY; }
- function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
- function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
- function enlargedArea(a, b) {
- return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
- (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
- }
- function intersectionArea(a, b) {
- var minX = Math.max(a.minX, b.minX);
- var minY = Math.max(a.minY, b.minY);
- var maxX = Math.min(a.maxX, b.maxX);
- var maxY = Math.min(a.maxY, b.maxY);
- return Math.max(0, maxX - minX) *
- Math.max(0, maxY - minY);
- }
- function contains(a, b) {
- return a.minX <= b.minX &&
- a.minY <= b.minY &&
- b.maxX <= a.maxX &&
- b.maxY <= a.maxY;
- }
- function intersects(a, b) {
- return b.minX <= a.maxX &&
- b.minY <= a.maxY &&
- b.maxX >= a.minX &&
- b.maxY >= a.minY;
- }
- function createNode(children) {
- return {
- children: children,
- height: 1,
- leaf: true,
- minX: Infinity,
- minY: Infinity,
- maxX: -Infinity,
- maxY: -Infinity
- };
- }
- // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
- // combines selection algorithm with binary divide & conquer approach
- function multiSelect(arr, left, right, n, compare) {
- var stack = [left, right];
- while (stack.length) {
- right = stack.pop();
- left = stack.pop();
- if (right - left <= n) { continue; }
- var mid = left + Math.ceil((right - left) / n / 2) * n;
- quickselect(arr, mid, left, right, compare);
- stack.push(left, mid, mid, right);
- }
- }
- return RBush;
- }));
- });
- /**
- * Common utilities
- * @module glMatrix
- */
- // Configuration Constants
- var EPSILON = 0.000001;
- var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
- if (!Math.hypot) Math.hypot = function () {
- var y = 0,
- i = arguments.length;
- while (i--) {
- y += arguments[i] * arguments[i];
- }
- return Math.sqrt(y);
- };
- /**
- * 3x3 Matrix
- * @module mat3
- */
- /**
- * Creates a new identity mat3
- *
- * @returns {mat3} a new 3x3 matrix
- */
- function create() {
- var out = new ARRAY_TYPE(9);
- if (ARRAY_TYPE != Float32Array) {
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[5] = 0;
- out[6] = 0;
- out[7] = 0;
- }
- out[0] = 1;
- out[4] = 1;
- out[8] = 1;
- return out;
- }
- /**
- * Copies the upper-left 3x3 values into the given mat3.
- *
- * @param {mat3} out the receiving 3x3 matrix
- * @param {ReadonlyMat4} a the source 4x4 matrix
- * @returns {mat3} out
- */
- function fromMat4(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[4];
- out[4] = a[5];
- out[5] = a[6];
- out[6] = a[8];
- out[7] = a[9];
- out[8] = a[10];
- return out;
- }
- /**
- * Create a new mat3 with the given values
- *
- * @param {Number} m00 Component in column 0, row 0 position (index 0)
- * @param {Number} m01 Component in column 0, row 1 position (index 1)
- * @param {Number} m02 Component in column 0, row 2 position (index 2)
- * @param {Number} m10 Component in column 1, row 0 position (index 3)
- * @param {Number} m11 Component in column 1, row 1 position (index 4)
- * @param {Number} m12 Component in column 1, row 2 position (index 5)
- * @param {Number} m20 Component in column 2, row 0 position (index 6)
- * @param {Number} m21 Component in column 2, row 1 position (index 7)
- * @param {Number} m22 Component in column 2, row 2 position (index 8)
- * @returns {mat3} A new mat3
- */
- function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
- var out = new ARRAY_TYPE(9);
- out[0] = m00;
- out[1] = m01;
- out[2] = m02;
- out[3] = m10;
- out[4] = m11;
- out[5] = m12;
- out[6] = m20;
- out[7] = m21;
- out[8] = m22;
- return out;
- }
- /**
- * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.
- * @module mat4
- */
- /**
- * Creates a new identity mat4
- *
- * @returns {mat4} a new 4x4 matrix
- */
- function create$1() {
- var out = new ARRAY_TYPE(16);
- if (ARRAY_TYPE != Float32Array) {
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- }
- out[0] = 1;
- out[5] = 1;
- out[10] = 1;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a new mat4 initialized with values from an existing matrix
- *
- * @param {ReadonlyMat4} a matrix to clone
- * @returns {mat4} a new 4x4 matrix
- */
- function clone(a) {
- var out = new ARRAY_TYPE(16);
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- out[4] = a[4];
- out[5] = a[5];
- out[6] = a[6];
- out[7] = a[7];
- out[8] = a[8];
- out[9] = a[9];
- out[10] = a[10];
- out[11] = a[11];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- return out;
- }
- /**
- * Copy the values from one mat4 to another
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function copy(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- out[4] = a[4];
- out[5] = a[5];
- out[6] = a[6];
- out[7] = a[7];
- out[8] = a[8];
- out[9] = a[9];
- out[10] = a[10];
- out[11] = a[11];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- return out;
- }
- /**
- * Create a new mat4 with the given values
- *
- * @param {Number} m00 Component in column 0, row 0 position (index 0)
- * @param {Number} m01 Component in column 0, row 1 position (index 1)
- * @param {Number} m02 Component in column 0, row 2 position (index 2)
- * @param {Number} m03 Component in column 0, row 3 position (index 3)
- * @param {Number} m10 Component in column 1, row 0 position (index 4)
- * @param {Number} m11 Component in column 1, row 1 position (index 5)
- * @param {Number} m12 Component in column 1, row 2 position (index 6)
- * @param {Number} m13 Component in column 1, row 3 position (index 7)
- * @param {Number} m20 Component in column 2, row 0 position (index 8)
- * @param {Number} m21 Component in column 2, row 1 position (index 9)
- * @param {Number} m22 Component in column 2, row 2 position (index 10)
- * @param {Number} m23 Component in column 2, row 3 position (index 11)
- * @param {Number} m30 Component in column 3, row 0 position (index 12)
- * @param {Number} m31 Component in column 3, row 1 position (index 13)
- * @param {Number} m32 Component in column 3, row 2 position (index 14)
- * @param {Number} m33 Component in column 3, row 3 position (index 15)
- * @returns {mat4} A new mat4
- */
- function fromValues$1(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
- var out = new ARRAY_TYPE(16);
- out[0] = m00;
- out[1] = m01;
- out[2] = m02;
- out[3] = m03;
- out[4] = m10;
- out[5] = m11;
- out[6] = m12;
- out[7] = m13;
- out[8] = m20;
- out[9] = m21;
- out[10] = m22;
- out[11] = m23;
- out[12] = m30;
- out[13] = m31;
- out[14] = m32;
- out[15] = m33;
- return out;
- }
- /**
- * Set the components of a mat4 to the given values
- *
- * @param {mat4} out the receiving matrix
- * @param {Number} m00 Component in column 0, row 0 position (index 0)
- * @param {Number} m01 Component in column 0, row 1 position (index 1)
- * @param {Number} m02 Component in column 0, row 2 position (index 2)
- * @param {Number} m03 Component in column 0, row 3 position (index 3)
- * @param {Number} m10 Component in column 1, row 0 position (index 4)
- * @param {Number} m11 Component in column 1, row 1 position (index 5)
- * @param {Number} m12 Component in column 1, row 2 position (index 6)
- * @param {Number} m13 Component in column 1, row 3 position (index 7)
- * @param {Number} m20 Component in column 2, row 0 position (index 8)
- * @param {Number} m21 Component in column 2, row 1 position (index 9)
- * @param {Number} m22 Component in column 2, row 2 position (index 10)
- * @param {Number} m23 Component in column 2, row 3 position (index 11)
- * @param {Number} m30 Component in column 3, row 0 position (index 12)
- * @param {Number} m31 Component in column 3, row 1 position (index 13)
- * @param {Number} m32 Component in column 3, row 2 position (index 14)
- * @param {Number} m33 Component in column 3, row 3 position (index 15)
- * @returns {mat4} out
- */
- function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
- out[0] = m00;
- out[1] = m01;
- out[2] = m02;
- out[3] = m03;
- out[4] = m10;
- out[5] = m11;
- out[6] = m12;
- out[7] = m13;
- out[8] = m20;
- out[9] = m21;
- out[10] = m22;
- out[11] = m23;
- out[12] = m30;
- out[13] = m31;
- out[14] = m32;
- out[15] = m33;
- return out;
- }
- /**
- * Set a mat4 to the identity matrix
- *
- * @param {mat4} out the receiving matrix
- * @returns {mat4} out
- */
- function identity(out) {
- out[0] = 1;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = 1;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 1;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Transpose the values of a mat4
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function transpose(out, a) {
- // If we are transposing ourselves we can skip a few steps but have to cache some values
- if (out === a) {
- var a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a12 = a[6],
- a13 = a[7];
- var a23 = a[11];
- out[1] = a[4];
- out[2] = a[8];
- out[3] = a[12];
- out[4] = a01;
- out[6] = a[9];
- out[7] = a[13];
- out[8] = a02;
- out[9] = a12;
- out[11] = a[14];
- out[12] = a03;
- out[13] = a13;
- out[14] = a23;
- } else {
- out[0] = a[0];
- out[1] = a[4];
- out[2] = a[8];
- out[3] = a[12];
- out[4] = a[1];
- out[5] = a[5];
- out[6] = a[9];
- out[7] = a[13];
- out[8] = a[2];
- out[9] = a[6];
- out[10] = a[10];
- out[11] = a[14];
- out[12] = a[3];
- out[13] = a[7];
- out[14] = a[11];
- out[15] = a[15];
- }
- return out;
- }
- /**
- * Inverts a mat4
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function invert(out, a) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15];
- var b00 = a00 * a11 - a01 * a10;
- var b01 = a00 * a12 - a02 * a10;
- var b02 = a00 * a13 - a03 * a10;
- var b03 = a01 * a12 - a02 * a11;
- var b04 = a01 * a13 - a03 * a11;
- var b05 = a02 * a13 - a03 * a12;
- var b06 = a20 * a31 - a21 * a30;
- var b07 = a20 * a32 - a22 * a30;
- var b08 = a20 * a33 - a23 * a30;
- var b09 = a21 * a32 - a22 * a31;
- var b10 = a21 * a33 - a23 * a31;
- var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
- var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
- if (!det) {
- return null;
- }
- det = 1.0 / det;
- out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
- out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
- out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
- out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
- out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
- out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
- out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
- out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
- out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
- out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
- out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
- out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
- out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
- out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
- out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
- out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
- return out;
- }
- /**
- * Calculates the adjugate of a mat4
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function adjoint(out, a) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15];
- out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
- out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
- out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
- out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
- out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
- out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
- out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
- out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
- out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
- out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
- out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
- out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
- out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
- out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
- out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
- out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
- return out;
- }
- /**
- * Calculates the determinant of a mat4
- *
- * @param {ReadonlyMat4} a the source matrix
- * @returns {Number} determinant of a
- */
- function determinant(a) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15];
- var b00 = a00 * a11 - a01 * a10;
- var b01 = a00 * a12 - a02 * a10;
- var b02 = a00 * a13 - a03 * a10;
- var b03 = a01 * a12 - a02 * a11;
- var b04 = a01 * a13 - a03 * a11;
- var b05 = a02 * a13 - a03 * a12;
- var b06 = a20 * a31 - a21 * a30;
- var b07 = a20 * a32 - a22 * a30;
- var b08 = a20 * a33 - a23 * a30;
- var b09 = a21 * a32 - a22 * a31;
- var b10 = a21 * a33 - a23 * a31;
- var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
- return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
- }
- /**
- * Multiplies two mat4s
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @returns {mat4} out
- */
- function multiply(out, a, b) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15]; // Cache only the current line of the second matrix
- var b0 = b[0],
- b1 = b[1],
- b2 = b[2],
- b3 = b[3];
- out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- b0 = b[4];
- b1 = b[5];
- b2 = b[6];
- b3 = b[7];
- out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- b0 = b[8];
- b1 = b[9];
- b2 = b[10];
- b3 = b[11];
- out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- b0 = b[12];
- b1 = b[13];
- b2 = b[14];
- b3 = b[15];
- out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- return out;
- }
- /**
- * Translate a mat4 by the given vector
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to translate
- * @param {ReadonlyVec3} v vector to translate by
- * @returns {mat4} out
- */
- function translate(out, a, v) {
- var x = v[0],
- y = v[1],
- z = v[2];
- var a00, a01, a02, a03;
- var a10, a11, a12, a13;
- var a20, a21, a22, a23;
- if (a === out) {
- out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
- out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
- out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
- out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
- } else {
- a00 = a[0];
- a01 = a[1];
- a02 = a[2];
- a03 = a[3];
- a10 = a[4];
- a11 = a[5];
- a12 = a[6];
- a13 = a[7];
- a20 = a[8];
- a21 = a[9];
- a22 = a[10];
- a23 = a[11];
- out[0] = a00;
- out[1] = a01;
- out[2] = a02;
- out[3] = a03;
- out[4] = a10;
- out[5] = a11;
- out[6] = a12;
- out[7] = a13;
- out[8] = a20;
- out[9] = a21;
- out[10] = a22;
- out[11] = a23;
- out[12] = a00 * x + a10 * y + a20 * z + a[12];
- out[13] = a01 * x + a11 * y + a21 * z + a[13];
- out[14] = a02 * x + a12 * y + a22 * z + a[14];
- out[15] = a03 * x + a13 * y + a23 * z + a[15];
- }
- return out;
- }
- /**
- * Scales the mat4 by the dimensions in the given vec3 not using vectorization
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to scale
- * @param {ReadonlyVec3} v the vec3 to scale the matrix by
- * @returns {mat4} out
- **/
- function scale(out, a, v) {
- var x = v[0],
- y = v[1],
- z = v[2];
- out[0] = a[0] * x;
- out[1] = a[1] * x;
- out[2] = a[2] * x;
- out[3] = a[3] * x;
- out[4] = a[4] * y;
- out[5] = a[5] * y;
- out[6] = a[6] * y;
- out[7] = a[7] * y;
- out[8] = a[8] * z;
- out[9] = a[9] * z;
- out[10] = a[10] * z;
- out[11] = a[11] * z;
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- return out;
- }
- /**
- * Rotates a mat4 by the given angle around the given axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @param {ReadonlyVec3} axis the axis to rotate around
- * @returns {mat4} out
- */
- function rotate(out, a, rad, axis) {
- var x = axis[0],
- y = axis[1],
- z = axis[2];
- var len = Math.hypot(x, y, z);
- var s, c, t;
- var a00, a01, a02, a03;
- var a10, a11, a12, a13;
- var a20, a21, a22, a23;
- var b00, b01, b02;
- var b10, b11, b12;
- var b20, b21, b22;
- if (len < EPSILON) {
- return null;
- }
- len = 1 / len;
- x *= len;
- y *= len;
- z *= len;
- s = Math.sin(rad);
- c = Math.cos(rad);
- t = 1 - c;
- a00 = a[0];
- a01 = a[1];
- a02 = a[2];
- a03 = a[3];
- a10 = a[4];
- a11 = a[5];
- a12 = a[6];
- a13 = a[7];
- a20 = a[8];
- a21 = a[9];
- a22 = a[10];
- a23 = a[11]; // Construct the elements of the rotation matrix
- b00 = x * x * t + c;
- b01 = y * x * t + z * s;
- b02 = z * x * t - y * s;
- b10 = x * y * t - z * s;
- b11 = y * y * t + c;
- b12 = z * y * t + x * s;
- b20 = x * z * t + y * s;
- b21 = y * z * t - x * s;
- b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
- out[0] = a00 * b00 + a10 * b01 + a20 * b02;
- out[1] = a01 * b00 + a11 * b01 + a21 * b02;
- out[2] = a02 * b00 + a12 * b01 + a22 * b02;
- out[3] = a03 * b00 + a13 * b01 + a23 * b02;
- out[4] = a00 * b10 + a10 * b11 + a20 * b12;
- out[5] = a01 * b10 + a11 * b11 + a21 * b12;
- out[6] = a02 * b10 + a12 * b11 + a22 * b12;
- out[7] = a03 * b10 + a13 * b11 + a23 * b12;
- out[8] = a00 * b20 + a10 * b21 + a20 * b22;
- out[9] = a01 * b20 + a11 * b21 + a21 * b22;
- out[10] = a02 * b20 + a12 * b21 + a22 * b22;
- out[11] = a03 * b20 + a13 * b21 + a23 * b22;
- if (a !== out) {
- // If the source and destination differ, copy the unchanged last row
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- }
- return out;
- }
- /**
- * Rotates a matrix by the given angle around the X axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function rotateX(out, a, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad);
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- if (a !== out) {
- // If the source and destination differ, copy the unchanged rows
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- } // Perform axis-specific matrix multiplication
- out[4] = a10 * c + a20 * s;
- out[5] = a11 * c + a21 * s;
- out[6] = a12 * c + a22 * s;
- out[7] = a13 * c + a23 * s;
- out[8] = a20 * c - a10 * s;
- out[9] = a21 * c - a11 * s;
- out[10] = a22 * c - a12 * s;
- out[11] = a23 * c - a13 * s;
- return out;
- }
- /**
- * Rotates a matrix by the given angle around the Y axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function rotateY(out, a, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad);
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- if (a !== out) {
- // If the source and destination differ, copy the unchanged rows
- out[4] = a[4];
- out[5] = a[5];
- out[6] = a[6];
- out[7] = a[7];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- } // Perform axis-specific matrix multiplication
- out[0] = a00 * c - a20 * s;
- out[1] = a01 * c - a21 * s;
- out[2] = a02 * c - a22 * s;
- out[3] = a03 * c - a23 * s;
- out[8] = a00 * s + a20 * c;
- out[9] = a01 * s + a21 * c;
- out[10] = a02 * s + a22 * c;
- out[11] = a03 * s + a23 * c;
- return out;
- }
- /**
- * Rotates a matrix by the given angle around the Z axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function rotateZ(out, a, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad);
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- if (a !== out) {
- // If the source and destination differ, copy the unchanged last row
- out[8] = a[8];
- out[9] = a[9];
- out[10] = a[10];
- out[11] = a[11];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- } // Perform axis-specific matrix multiplication
- out[0] = a00 * c + a10 * s;
- out[1] = a01 * c + a11 * s;
- out[2] = a02 * c + a12 * s;
- out[3] = a03 * c + a13 * s;
- out[4] = a10 * c - a00 * s;
- out[5] = a11 * c - a01 * s;
- out[6] = a12 * c - a02 * s;
- out[7] = a13 * c - a03 * s;
- return out;
- }
- /**
- * Creates a matrix from a vector translation
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, dest, vec);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {ReadonlyVec3} v Translation vector
- * @returns {mat4} out
- */
- function fromTranslation(out, v) {
- out[0] = 1;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = 1;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 1;
- out[11] = 0;
- out[12] = v[0];
- out[13] = v[1];
- out[14] = v[2];
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a vector scaling
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.scale(dest, dest, vec);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {ReadonlyVec3} v Scaling vector
- * @returns {mat4} out
- */
- function fromScaling(out, v) {
- out[0] = v[0];
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = v[1];
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = v[2];
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a given angle around a given axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotate(dest, dest, rad, axis);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @param {ReadonlyVec3} axis the axis to rotate around
- * @returns {mat4} out
- */
- function fromRotation(out, rad, axis) {
- var x = axis[0],
- y = axis[1],
- z = axis[2];
- var len = Math.hypot(x, y, z);
- var s, c, t;
- if (len < EPSILON) {
- return null;
- }
- len = 1 / len;
- x *= len;
- y *= len;
- z *= len;
- s = Math.sin(rad);
- c = Math.cos(rad);
- t = 1 - c; // Perform rotation-specific matrix multiplication
- out[0] = x * x * t + c;
- out[1] = y * x * t + z * s;
- out[2] = z * x * t - y * s;
- out[3] = 0;
- out[4] = x * y * t - z * s;
- out[5] = y * y * t + c;
- out[6] = z * y * t + x * s;
- out[7] = 0;
- out[8] = x * z * t + y * s;
- out[9] = y * z * t - x * s;
- out[10] = z * z * t + c;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from the given angle around the X axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotateX(dest, dest, rad);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function fromXRotation(out, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad); // Perform axis-specific matrix multiplication
- out[0] = 1;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = c;
- out[6] = s;
- out[7] = 0;
- out[8] = 0;
- out[9] = -s;
- out[10] = c;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from the given angle around the Y axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotateY(dest, dest, rad);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function fromYRotation(out, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad); // Perform axis-specific matrix multiplication
- out[0] = c;
- out[1] = 0;
- out[2] = -s;
- out[3] = 0;
- out[4] = 0;
- out[5] = 1;
- out[6] = 0;
- out[7] = 0;
- out[8] = s;
- out[9] = 0;
- out[10] = c;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from the given angle around the Z axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotateZ(dest, dest, rad);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function fromZRotation(out, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad); // Perform axis-specific matrix multiplication
- out[0] = c;
- out[1] = s;
- out[2] = 0;
- out[3] = 0;
- out[4] = -s;
- out[5] = c;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 1;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a quaternion rotation and vector translation
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, vec);
- * let quatMat = mat4.create();
- * quat4.toMat4(quat, quatMat);
- * mat4.multiply(dest, quatMat);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {quat4} q Rotation quaternion
- * @param {ReadonlyVec3} v Translation vector
- * @returns {mat4} out
- */
- function fromRotationTranslation(out, q, v) {
- // Quaternion math
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var xy = x * y2;
- var xz = x * z2;
- var yy = y * y2;
- var yz = y * z2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- out[0] = 1 - (yy + zz);
- out[1] = xy + wz;
- out[2] = xz - wy;
- out[3] = 0;
- out[4] = xy - wz;
- out[5] = 1 - (xx + zz);
- out[6] = yz + wx;
- out[7] = 0;
- out[8] = xz + wy;
- out[9] = yz - wx;
- out[10] = 1 - (xx + yy);
- out[11] = 0;
- out[12] = v[0];
- out[13] = v[1];
- out[14] = v[2];
- out[15] = 1;
- return out;
- }
- /**
- * Creates a new mat4 from a dual quat.
- *
- * @param {mat4} out Matrix
- * @param {ReadonlyQuat2} a Dual Quaternion
- * @returns {mat4} mat4 receiving operation result
- */
- function fromQuat2(out, a) {
- var translation = new ARRAY_TYPE(3);
- var bx = -a[0],
- by = -a[1],
- bz = -a[2],
- bw = a[3],
- ax = a[4],
- ay = a[5],
- az = a[6],
- aw = a[7];
- var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense
- if (magnitude > 0) {
- translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;
- translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;
- translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;
- } else {
- translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
- translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
- translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
- }
- fromRotationTranslation(out, a, translation);
- return out;
- }
- /**
- * Returns the translation vector component of a transformation
- * matrix. If a matrix is built with fromRotationTranslation,
- * the returned vector will be the same as the translation vector
- * originally supplied.
- * @param {vec3} out Vector to receive translation component
- * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
- * @return {vec3} out
- */
- function getTranslation(out, mat) {
- out[0] = mat[12];
- out[1] = mat[13];
- out[2] = mat[14];
- return out;
- }
- /**
- * Returns the scaling factor component of a transformation
- * matrix. If a matrix is built with fromRotationTranslationScale
- * with a normalized Quaternion paramter, the returned vector will be
- * the same as the scaling vector
- * originally supplied.
- * @param {vec3} out Vector to receive scaling factor component
- * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
- * @return {vec3} out
- */
- function getScaling(out, mat) {
- var m11 = mat[0];
- var m12 = mat[1];
- var m13 = mat[2];
- var m21 = mat[4];
- var m22 = mat[5];
- var m23 = mat[6];
- var m31 = mat[8];
- var m32 = mat[9];
- var m33 = mat[10];
- out[0] = Math.hypot(m11, m12, m13);
- out[1] = Math.hypot(m21, m22, m23);
- out[2] = Math.hypot(m31, m32, m33);
- return out;
- }
- /**
- * Returns a quaternion representing the rotational component
- * of a transformation matrix. If a matrix is built with
- * fromRotationTranslation, the returned quaternion will be the
- * same as the quaternion originally supplied.
- * @param {quat} out Quaternion to receive the rotation component
- * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
- * @return {quat} out
- */
- function getRotation(out, mat) {
- var scaling = new ARRAY_TYPE(3);
- getScaling(scaling, mat);
- var is1 = 1 / scaling[0];
- var is2 = 1 / scaling[1];
- var is3 = 1 / scaling[2];
- var sm11 = mat[0] * is1;
- var sm12 = mat[1] * is2;
- var sm13 = mat[2] * is3;
- var sm21 = mat[4] * is1;
- var sm22 = mat[5] * is2;
- var sm23 = mat[6] * is3;
- var sm31 = mat[8] * is1;
- var sm32 = mat[9] * is2;
- var sm33 = mat[10] * is3;
- var trace = sm11 + sm22 + sm33;
- var S = 0;
- if (trace > 0) {
- S = Math.sqrt(trace + 1.0) * 2;
- out[3] = 0.25 * S;
- out[0] = (sm23 - sm32) / S;
- out[1] = (sm31 - sm13) / S;
- out[2] = (sm12 - sm21) / S;
- } else if (sm11 > sm22 && sm11 > sm33) {
- S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;
- out[3] = (sm23 - sm32) / S;
- out[0] = 0.25 * S;
- out[1] = (sm12 + sm21) / S;
- out[2] = (sm31 + sm13) / S;
- } else if (sm22 > sm33) {
- S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;
- out[3] = (sm31 - sm13) / S;
- out[0] = (sm12 + sm21) / S;
- out[1] = 0.25 * S;
- out[2] = (sm23 + sm32) / S;
- } else {
- S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;
- out[3] = (sm12 - sm21) / S;
- out[0] = (sm31 + sm13) / S;
- out[1] = (sm23 + sm32) / S;
- out[2] = 0.25 * S;
- }
- return out;
- }
- /**
- * Creates a matrix from a quaternion rotation, vector translation and vector scale
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, vec);
- * let quatMat = mat4.create();
- * quat4.toMat4(quat, quatMat);
- * mat4.multiply(dest, quatMat);
- * mat4.scale(dest, scale)
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {quat4} q Rotation quaternion
- * @param {ReadonlyVec3} v Translation vector
- * @param {ReadonlyVec3} s Scaling vector
- * @returns {mat4} out
- */
- function fromRotationTranslationScale(out, q, v, s) {
- // Quaternion math
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var xy = x * y2;
- var xz = x * z2;
- var yy = y * y2;
- var yz = y * z2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- var sx = s[0];
- var sy = s[1];
- var sz = s[2];
- out[0] = (1 - (yy + zz)) * sx;
- out[1] = (xy + wz) * sx;
- out[2] = (xz - wy) * sx;
- out[3] = 0;
- out[4] = (xy - wz) * sy;
- out[5] = (1 - (xx + zz)) * sy;
- out[6] = (yz + wx) * sy;
- out[7] = 0;
- out[8] = (xz + wy) * sz;
- out[9] = (yz - wx) * sz;
- out[10] = (1 - (xx + yy)) * sz;
- out[11] = 0;
- out[12] = v[0];
- out[13] = v[1];
- out[14] = v[2];
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, vec);
- * mat4.translate(dest, origin);
- * let quatMat = mat4.create();
- * quat4.toMat4(quat, quatMat);
- * mat4.multiply(dest, quatMat);
- * mat4.scale(dest, scale)
- * mat4.translate(dest, negativeOrigin);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {quat4} q Rotation quaternion
- * @param {ReadonlyVec3} v Translation vector
- * @param {ReadonlyVec3} s Scaling vector
- * @param {ReadonlyVec3} o The origin vector around which to scale and rotate
- * @returns {mat4} out
- */
- function fromRotationTranslationScaleOrigin(out, q, v, s, o) {
- // Quaternion math
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var xy = x * y2;
- var xz = x * z2;
- var yy = y * y2;
- var yz = y * z2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- var sx = s[0];
- var sy = s[1];
- var sz = s[2];
- var ox = o[0];
- var oy = o[1];
- var oz = o[2];
- var out0 = (1 - (yy + zz)) * sx;
- var out1 = (xy + wz) * sx;
- var out2 = (xz - wy) * sx;
- var out4 = (xy - wz) * sy;
- var out5 = (1 - (xx + zz)) * sy;
- var out6 = (yz + wx) * sy;
- var out8 = (xz + wy) * sz;
- var out9 = (yz - wx) * sz;
- var out10 = (1 - (xx + yy)) * sz;
- out[0] = out0;
- out[1] = out1;
- out[2] = out2;
- out[3] = 0;
- out[4] = out4;
- out[5] = out5;
- out[6] = out6;
- out[7] = 0;
- out[8] = out8;
- out[9] = out9;
- out[10] = out10;
- out[11] = 0;
- out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
- out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
- out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
- out[15] = 1;
- return out;
- }
- /**
- * Calculates a 4x4 matrix from the given quaternion
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {ReadonlyQuat} q Quaternion to create matrix from
- *
- * @returns {mat4} out
- */
- function fromQuat(out, q) {
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var yx = y * x2;
- var yy = y * y2;
- var zx = z * x2;
- var zy = z * y2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- out[0] = 1 - yy - zz;
- out[1] = yx + wz;
- out[2] = zx - wy;
- out[3] = 0;
- out[4] = yx - wz;
- out[5] = 1 - xx - zz;
- out[6] = zy + wx;
- out[7] = 0;
- out[8] = zx + wy;
- out[9] = zy - wx;
- out[10] = 1 - xx - yy;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Generates a frustum matrix with the given bounds
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {Number} left Left bound of the frustum
- * @param {Number} right Right bound of the frustum
- * @param {Number} bottom Bottom bound of the frustum
- * @param {Number} top Top bound of the frustum
- * @param {Number} near Near bound of the frustum
- * @param {Number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function frustum(out, left, right, bottom, top, near, far) {
- var rl = 1 / (right - left);
- var tb = 1 / (top - bottom);
- var nf = 1 / (near - far);
- out[0] = near * 2 * rl;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = near * 2 * tb;
- out[6] = 0;
- out[7] = 0;
- out[8] = (right + left) * rl;
- out[9] = (top + bottom) * tb;
- out[10] = (far + near) * nf;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[14] = far * near * 2 * nf;
- out[15] = 0;
- return out;
- }
- /**
- * Generates a perspective projection matrix with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
- * which matches WebGL/OpenGL's clip volume.
- * Passing null/undefined/no value for far will generate infinite projection matrix.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} fovy Vertical field of view in radians
- * @param {number} aspect Aspect ratio. typically viewport width/height
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum, can be null or Infinity
- * @returns {mat4} out
- */
- function perspectiveNO(out, fovy, aspect, near, far) {
- var f = 1.0 / Math.tan(fovy / 2),
- nf;
- out[0] = f / aspect;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = f;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[15] = 0;
- if (far != null && far !== Infinity) {
- nf = 1 / (near - far);
- out[10] = (far + near) * nf;
- out[14] = 2 * far * near * nf;
- } else {
- out[10] = -1;
- out[14] = -2 * near;
- }
- return out;
- }
- /**
- * Alias for {@link mat4.perspectiveNO}
- * @function
- */
- var perspective = perspectiveNO;
- /**
- * Generates a perspective projection matrix suitable for WebGPU with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
- * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
- * Passing null/undefined/no value for far will generate infinite projection matrix.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} fovy Vertical field of view in radians
- * @param {number} aspect Aspect ratio. typically viewport width/height
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum, can be null or Infinity
- * @returns {mat4} out
- */
- function perspectiveZO(out, fovy, aspect, near, far) {
- var f = 1.0 / Math.tan(fovy / 2),
- nf;
- out[0] = f / aspect;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = f;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[15] = 0;
- if (far != null && far !== Infinity) {
- nf = 1 / (near - far);
- out[10] = far * nf;
- out[14] = far * near * nf;
- } else {
- out[10] = -1;
- out[14] = -near;
- }
- return out;
- }
- /**
- * Generates a perspective projection matrix with the given field of view.
- * This is primarily useful for generating projection matrices to be used
- * with the still experiemental WebVR API.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function perspectiveFromFieldOfView(out, fov, near, far) {
- var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
- var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
- var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
- var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
- var xScale = 2.0 / (leftTan + rightTan);
- var yScale = 2.0 / (upTan + downTan);
- out[0] = xScale;
- out[1] = 0.0;
- out[2] = 0.0;
- out[3] = 0.0;
- out[4] = 0.0;
- out[5] = yScale;
- out[6] = 0.0;
- out[7] = 0.0;
- out[8] = -((leftTan - rightTan) * xScale * 0.5);
- out[9] = (upTan - downTan) * yScale * 0.5;
- out[10] = far / (near - far);
- out[11] = -1.0;
- out[12] = 0.0;
- out[13] = 0.0;
- out[14] = far * near / (near - far);
- out[15] = 0.0;
- return out;
- }
- /**
- * Generates a orthogonal projection matrix with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
- * which matches WebGL/OpenGL's clip volume.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} left Left bound of the frustum
- * @param {number} right Right bound of the frustum
- * @param {number} bottom Bottom bound of the frustum
- * @param {number} top Top bound of the frustum
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function orthoNO(out, left, right, bottom, top, near, far) {
- var lr = 1 / (left - right);
- var bt = 1 / (bottom - top);
- var nf = 1 / (near - far);
- out[0] = -2 * lr;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = -2 * bt;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 2 * nf;
- out[11] = 0;
- out[12] = (left + right) * lr;
- out[13] = (top + bottom) * bt;
- out[14] = (far + near) * nf;
- out[15] = 1;
- return out;
- }
- /**
- * Alias for {@link mat4.orthoNO}
- * @function
- */
- var ortho = orthoNO;
- /**
- * Generates a orthogonal projection matrix with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
- * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} left Left bound of the frustum
- * @param {number} right Right bound of the frustum
- * @param {number} bottom Bottom bound of the frustum
- * @param {number} top Top bound of the frustum
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function orthoZO(out, left, right, bottom, top, near, far) {
- var lr = 1 / (left - right);
- var bt = 1 / (bottom - top);
- var nf = 1 / (near - far);
- out[0] = -2 * lr;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = -2 * bt;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = nf;
- out[11] = 0;
- out[12] = (left + right) * lr;
- out[13] = (top + bottom) * bt;
- out[14] = near * nf;
- out[15] = 1;
- return out;
- }
- /**
- * Generates a look-at matrix with the given eye position, focal point, and up axis.
- * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {ReadonlyVec3} eye Position of the viewer
- * @param {ReadonlyVec3} center Point the viewer is looking at
- * @param {ReadonlyVec3} up vec3 pointing up
- * @returns {mat4} out
- */
- function lookAt(out, eye, center, up) {
- var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
- var eyex = eye[0];
- var eyey = eye[1];
- var eyez = eye[2];
- var upx = up[0];
- var upy = up[1];
- var upz = up[2];
- var centerx = center[0];
- var centery = center[1];
- var centerz = center[2];
- if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
- return identity(out);
- }
- z0 = eyex - centerx;
- z1 = eyey - centery;
- z2 = eyez - centerz;
- len = 1 / Math.hypot(z0, z1, z2);
- z0 *= len;
- z1 *= len;
- z2 *= len;
- x0 = upy * z2 - upz * z1;
- x1 = upz * z0 - upx * z2;
- x2 = upx * z1 - upy * z0;
- len = Math.hypot(x0, x1, x2);
- if (!len) {
- x0 = 0;
- x1 = 0;
- x2 = 0;
- } else {
- len = 1 / len;
- x0 *= len;
- x1 *= len;
- x2 *= len;
- }
- y0 = z1 * x2 - z2 * x1;
- y1 = z2 * x0 - z0 * x2;
- y2 = z0 * x1 - z1 * x0;
- len = Math.hypot(y0, y1, y2);
- if (!len) {
- y0 = 0;
- y1 = 0;
- y2 = 0;
- } else {
- len = 1 / len;
- y0 *= len;
- y1 *= len;
- y2 *= len;
- }
- out[0] = x0;
- out[1] = y0;
- out[2] = z0;
- out[3] = 0;
- out[4] = x1;
- out[5] = y1;
- out[6] = z1;
- out[7] = 0;
- out[8] = x2;
- out[9] = y2;
- out[10] = z2;
- out[11] = 0;
- out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
- out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
- out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
- out[15] = 1;
- return out;
- }
- /**
- * Generates a matrix that makes something look at something else.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {ReadonlyVec3} eye Position of the viewer
- * @param {ReadonlyVec3} center Point the viewer is looking at
- * @param {ReadonlyVec3} up vec3 pointing up
- * @returns {mat4} out
- */
- function targetTo(out, eye, target, up) {
- var eyex = eye[0],
- eyey = eye[1],
- eyez = eye[2],
- upx = up[0],
- upy = up[1],
- upz = up[2];
- var z0 = eyex - target[0],
- z1 = eyey - target[1],
- z2 = eyez - target[2];
- var len = z0 * z0 + z1 * z1 + z2 * z2;
- if (len > 0) {
- len = 1 / Math.sqrt(len);
- z0 *= len;
- z1 *= len;
- z2 *= len;
- }
- var x0 = upy * z2 - upz * z1,
- x1 = upz * z0 - upx * z2,
- x2 = upx * z1 - upy * z0;
- len = x0 * x0 + x1 * x1 + x2 * x2;
- if (len > 0) {
- len = 1 / Math.sqrt(len);
- x0 *= len;
- x1 *= len;
- x2 *= len;
- }
- out[0] = x0;
- out[1] = x1;
- out[2] = x2;
- out[3] = 0;
- out[4] = z1 * x2 - z2 * x1;
- out[5] = z2 * x0 - z0 * x2;
- out[6] = z0 * x1 - z1 * x0;
- out[7] = 0;
- out[8] = z0;
- out[9] = z1;
- out[10] = z2;
- out[11] = 0;
- out[12] = eyex;
- out[13] = eyey;
- out[14] = eyez;
- out[15] = 1;
- return out;
- }
- /**
- * Returns a string representation of a mat4
- *
- * @param {ReadonlyMat4} a matrix to represent as a string
- * @returns {String} string representation of the matrix
- */
- function str(a) {
- return "mat4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ", " + a[9] + ", " + a[10] + ", " + a[11] + ", " + a[12] + ", " + a[13] + ", " + a[14] + ", " + a[15] + ")";
- }
- /**
- * Returns Frobenius norm of a mat4
- *
- * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of
- * @returns {Number} Frobenius norm
- */
- function frob(a) {
- return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);
- }
- /**
- * Adds two mat4's
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @returns {mat4} out
- */
- function add(out, a, b) {
- out[0] = a[0] + b[0];
- out[1] = a[1] + b[1];
- out[2] = a[2] + b[2];
- out[3] = a[3] + b[3];
- out[4] = a[4] + b[4];
- out[5] = a[5] + b[5];
- out[6] = a[6] + b[6];
- out[7] = a[7] + b[7];
- out[8] = a[8] + b[8];
- out[9] = a[9] + b[9];
- out[10] = a[10] + b[10];
- out[11] = a[11] + b[11];
- out[12] = a[12] + b[12];
- out[13] = a[13] + b[13];
- out[14] = a[14] + b[14];
- out[15] = a[15] + b[15];
- return out;
- }
- /**
- * Subtracts matrix b from matrix a
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @returns {mat4} out
- */
- function subtract(out, a, b) {
- out[0] = a[0] - b[0];
- out[1] = a[1] - b[1];
- out[2] = a[2] - b[2];
- out[3] = a[3] - b[3];
- out[4] = a[4] - b[4];
- out[5] = a[5] - b[5];
- out[6] = a[6] - b[6];
- out[7] = a[7] - b[7];
- out[8] = a[8] - b[8];
- out[9] = a[9] - b[9];
- out[10] = a[10] - b[10];
- out[11] = a[11] - b[11];
- out[12] = a[12] - b[12];
- out[13] = a[13] - b[13];
- out[14] = a[14] - b[14];
- out[15] = a[15] - b[15];
- return out;
- }
- /**
- * Multiply each element of the matrix by a scalar.
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to scale
- * @param {Number} b amount to scale the matrix's elements by
- * @returns {mat4} out
- */
- function multiplyScalar(out, a, b) {
- out[0] = a[0] * b;
- out[1] = a[1] * b;
- out[2] = a[2] * b;
- out[3] = a[3] * b;
- out[4] = a[4] * b;
- out[5] = a[5] * b;
- out[6] = a[6] * b;
- out[7] = a[7] * b;
- out[8] = a[8] * b;
- out[9] = a[9] * b;
- out[10] = a[10] * b;
- out[11] = a[11] * b;
- out[12] = a[12] * b;
- out[13] = a[13] * b;
- out[14] = a[14] * b;
- out[15] = a[15] * b;
- return out;
- }
- /**
- * Adds two mat4's after multiplying each element of the second operand by a scalar value.
- *
- * @param {mat4} out the receiving vector
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @param {Number} scale the amount to scale b's elements by before adding
- * @returns {mat4} out
- */
- function multiplyScalarAndAdd(out, a, b, scale) {
- out[0] = a[0] + b[0] * scale;
- out[1] = a[1] + b[1] * scale;
- out[2] = a[2] + b[2] * scale;
- out[3] = a[3] + b[3] * scale;
- out[4] = a[4] + b[4] * scale;
- out[5] = a[5] + b[5] * scale;
- out[6] = a[6] + b[6] * scale;
- out[7] = a[7] + b[7] * scale;
- out[8] = a[8] + b[8] * scale;
- out[9] = a[9] + b[9] * scale;
- out[10] = a[10] + b[10] * scale;
- out[11] = a[11] + b[11] * scale;
- out[12] = a[12] + b[12] * scale;
- out[13] = a[13] + b[13] * scale;
- out[14] = a[14] + b[14] * scale;
- out[15] = a[15] + b[15] * scale;
- return out;
- }
- /**
- * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
- *
- * @param {ReadonlyMat4} a The first matrix.
- * @param {ReadonlyMat4} b The second matrix.
- * @returns {Boolean} True if the matrices are equal, false otherwise.
- */
- function exactEquals(a, b) {
- return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];
- }
- /**
- * Returns whether or not the matrices have approximately the same elements in the same position.
- *
- * @param {ReadonlyMat4} a The first matrix.
- * @param {ReadonlyMat4} b The second matrix.
- * @returns {Boolean} True if the matrices are equal, false otherwise.
- */
- function equals(a, b) {
- var a0 = a[0],
- a1 = a[1],
- a2 = a[2],
- a3 = a[3];
- var a4 = a[4],
- a5 = a[5],
- a6 = a[6],
- a7 = a[7];
- var a8 = a[8],
- a9 = a[9],
- a10 = a[10],
- a11 = a[11];
- var a12 = a[12],
- a13 = a[13],
- a14 = a[14],
- a15 = a[15];
- var b0 = b[0],
- b1 = b[1],
- b2 = b[2],
- b3 = b[3];
- var b4 = b[4],
- b5 = b[5],
- b6 = b[6],
- b7 = b[7];
- var b8 = b[8],
- b9 = b[9],
- b10 = b[10],
- b11 = b[11];
- var b12 = b[12],
- b13 = b[13],
- b14 = b[14],
- b15 = b[15];
- return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));
- }
- /**
- * Alias for {@link mat4.multiply}
- * @function
- */
- var mul = multiply;
- /**
- * Alias for {@link mat4.subtract}
- * @function
- */
- var sub = subtract;
- var mat4 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- create: create$1,
- clone: clone,
- copy: copy,
- fromValues: fromValues$1,
- set: set,
- identity: identity,
- transpose: transpose,
- invert: invert,
- adjoint: adjoint,
- determinant: determinant,
- multiply: multiply,
- translate: translate,
- scale: scale,
- rotate: rotate,
- rotateX: rotateX,
- rotateY: rotateY,
- rotateZ: rotateZ,
- fromTranslation: fromTranslation,
- fromScaling: fromScaling,
- fromRotation: fromRotation,
- fromXRotation: fromXRotation,
- fromYRotation: fromYRotation,
- fromZRotation: fromZRotation,
- fromRotationTranslation: fromRotationTranslation,
- fromQuat2: fromQuat2,
- getTranslation: getTranslation,
- getScaling: getScaling,
- getRotation: getRotation,
- fromRotationTranslationScale: fromRotationTranslationScale,
- fromRotationTranslationScaleOrigin: fromRotationTranslationScaleOrigin,
- fromQuat: fromQuat,
- frustum: frustum,
- perspectiveNO: perspectiveNO,
- perspective: perspective,
- perspectiveZO: perspectiveZO,
- perspectiveFromFieldOfView: perspectiveFromFieldOfView,
- orthoNO: orthoNO,
- ortho: ortho,
- orthoZO: orthoZO,
- lookAt: lookAt,
- targetTo: targetTo,
- str: str,
- frob: frob,
- add: add,
- subtract: subtract,
- multiplyScalar: multiplyScalar,
- multiplyScalarAndAdd: multiplyScalarAndAdd,
- exactEquals: exactEquals,
- equals: equals,
- mul: mul,
- sub: sub
- });
- /**
- * 3 Dimensional Vector
- * @module vec3
- */
- /**
- * Creates a new, empty vec3
- *
- * @returns {vec3} a new 3D vector
- */
- function create$2() {
- var out = new ARRAY_TYPE(3);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- }
- return out;
- }
- /**
- * Creates a new vec3 initialized with values from an existing vector
- *
- * @param {ReadonlyVec3} a vector to clone
- * @returns {vec3} a new 3D vector
- */
- function clone$1(a) {
- var out = new ARRAY_TYPE(3);
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- return out;
- }
- /**
- * Calculates the length of a vec3
- *
- * @param {ReadonlyVec3} a vector to calculate length of
- * @returns {Number} length of a
- */
- function length(a) {
- var x = a[0];
- var y = a[1];
- var z = a[2];
- return Math.hypot(x, y, z);
- }
- /**
- * Creates a new vec3 initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @returns {vec3} a new 3D vector
- */
- function fromValues$2(x, y, z) {
- var out = new ARRAY_TYPE(3);
- out[0] = x;
- out[1] = y;
- out[2] = z;
- return out;
- }
- /**
- * Copy the values from one vec3 to another
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the source vector
- * @returns {vec3} out
- */
- function copy$1(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- return out;
- }
- /**
- * Set the components of a vec3 to the given values
- *
- * @param {vec3} out the receiving vector
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @returns {vec3} out
- */
- function set$1(out, x, y, z) {
- out[0] = x;
- out[1] = y;
- out[2] = z;
- return out;
- }
- /**
- * Adds two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function add$1(out, a, b) {
- out[0] = a[0] + b[0];
- out[1] = a[1] + b[1];
- out[2] = a[2] + b[2];
- return out;
- }
- /**
- * Subtracts vector b from vector a
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function subtract$1(out, a, b) {
- out[0] = a[0] - b[0];
- out[1] = a[1] - b[1];
- out[2] = a[2] - b[2];
- return out;
- }
- /**
- * Multiplies two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function multiply$1(out, a, b) {
- out[0] = a[0] * b[0];
- out[1] = a[1] * b[1];
- out[2] = a[2] * b[2];
- return out;
- }
- /**
- * Scales a vec3 by a scalar number
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to scale
- * @param {Number} b amount to scale the vector by
- * @returns {vec3} out
- */
- function scale$1(out, a, b) {
- out[0] = a[0] * b;
- out[1] = a[1] * b;
- out[2] = a[2] * b;
- return out;
- }
- /**
- * Calculates the euclidian distance between two vec3's
- *
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {Number} distance between a and b
- */
- function distance(a, b) {
- var x = b[0] - a[0];
- var y = b[1] - a[1];
- var z = b[2] - a[2];
- return Math.hypot(x, y, z);
- }
- /**
- * Normalize a vec3
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a vector to normalize
- * @returns {vec3} out
- */
- function normalize(out, a) {
- var x = a[0];
- var y = a[1];
- var z = a[2];
- var len = x * x + y * y + z * z;
- if (len > 0) {
- //TODO: evaluate use of glm_invsqrt here?
- len = 1 / Math.sqrt(len);
- }
- out[0] = a[0] * len;
- out[1] = a[1] * len;
- out[2] = a[2] * len;
- return out;
- }
- /**
- * Calculates the dot product of two vec3's
- *
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {Number} dot product of a and b
- */
- function dot(a, b) {
- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
- }
- /**
- * Computes the cross product of two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function cross(out, a, b) {
- var ax = a[0],
- ay = a[1],
- az = a[2];
- var bx = b[0],
- by = b[1],
- bz = b[2];
- out[0] = ay * bz - az * by;
- out[1] = az * bx - ax * bz;
- out[2] = ax * by - ay * bx;
- return out;
- }
- /**
- * Performs a linear interpolation between two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
- * @returns {vec3} out
- */
- function lerp(out, a, b, t) {
- var ax = a[0];
- var ay = a[1];
- var az = a[2];
- out[0] = ax + t * (b[0] - ax);
- out[1] = ay + t * (b[1] - ay);
- out[2] = az + t * (b[2] - az);
- return out;
- }
- /**
- * Transforms the vec3 with a mat4.
- * 4th vector component is implicitly '1'
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to transform
- * @param {ReadonlyMat4} m matrix to transform with
- * @returns {vec3} out
- */
- function transformMat4(out, a, m) {
- var x = a[0],
- y = a[1],
- z = a[2];
- var w = m[3] * x + m[7] * y + m[11] * z + m[15];
- w = w || 1.0;
- out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
- out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
- out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
- return out;
- }
- /**
- * Transforms the vec3 with a mat3.
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to transform
- * @param {ReadonlyMat3} m the 3x3 matrix to transform with
- * @returns {vec3} out
- */
- function transformMat3(out, a, m) {
- var x = a[0],
- y = a[1],
- z = a[2];
- out[0] = x * m[0] + y * m[3] + z * m[6];
- out[1] = x * m[1] + y * m[4] + z * m[7];
- out[2] = x * m[2] + y * m[5] + z * m[8];
- return out;
- }
- /**
- * Transforms the vec3 with a quat
- * Can also be used for dual quaternions. (Multiply it with the real part)
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to transform
- * @param {ReadonlyQuat} q quaternion to transform with
- * @returns {vec3} out
- */
- function transformQuat(out, a, q) {
- // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
- var qx = q[0],
- qy = q[1],
- qz = q[2],
- qw = q[3];
- var x = a[0],
- y = a[1],
- z = a[2]; // var qvec = [qx, qy, qz];
- // var uv = vec3.cross([], qvec, a);
- var uvx = qy * z - qz * y,
- uvy = qz * x - qx * z,
- uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
- var uuvx = qy * uvz - qz * uvy,
- uuvy = qz * uvx - qx * uvz,
- uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
- var w2 = qw * 2;
- uvx *= w2;
- uvy *= w2;
- uvz *= w2; // vec3.scale(uuv, uuv, 2);
- uuvx *= 2;
- uuvy *= 2;
- uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
- out[0] = x + uvx + uuvx;
- out[1] = y + uvy + uuvy;
- out[2] = z + uvz + uuvz;
- return out;
- }
- /**
- * Returns whether or not the vectors have approximately the same elements in the same position.
- *
- * @param {ReadonlyVec3} a The first vector.
- * @param {ReadonlyVec3} b The second vector.
- * @returns {Boolean} True if the vectors are equal, false otherwise.
- */
- function equals$1(a, b) {
- var a0 = a[0],
- a1 = a[1],
- a2 = a[2];
- var b0 = b[0],
- b1 = b[1],
- b2 = b[2];
- return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));
- }
- /**
- * Alias for {@link vec3.distance}
- * @function
- */
- var dist = distance;
- /**
- * Alias for {@link vec3.length}
- * @function
- */
- var len = length;
- /**
- * Perform some operation over an array of vec3s.
- *
- * @param {Array} a the array of vectors to iterate over
- * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
- * @param {Number} offset Number of elements to skip at the beginning of the array
- * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
- * @param {Function} fn Function to call for each vector in the array
- * @param {Object} [arg] additional argument to pass to fn
- * @returns {Array} a
- * @function
- */
- var forEach = function () {
- var vec = create$2();
- return function (a, stride, offset, count, fn, arg) {
- var i, l;
- if (!stride) {
- stride = 3;
- }
- if (!offset) {
- offset = 0;
- }
- if (count) {
- l = Math.min(count * stride + offset, a.length);
- } else {
- l = a.length;
- }
- for (i = offset; i < l; i += stride) {
- vec[0] = a[i];
- vec[1] = a[i + 1];
- vec[2] = a[i + 2];
- fn(vec, vec, arg);
- a[i] = vec[0];
- a[i + 1] = vec[1];
- a[i + 2] = vec[2];
- }
- return a;
- };
- }();
- /**
- * 4 Dimensional Vector
- * @module vec4
- */
- /**
- * Creates a new, empty vec4
- *
- * @returns {vec4} a new 4D vector
- */
- function create$3() {
- var out = new ARRAY_TYPE(4);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- }
- return out;
- }
- /**
- * Creates a new vec4 initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @param {Number} w W component
- * @returns {vec4} a new 4D vector
- */
- function fromValues$3(x, y, z, w) {
- var out = new ARRAY_TYPE(4);
- out[0] = x;
- out[1] = y;
- out[2] = z;
- out[3] = w;
- return out;
- }
- /**
- * Copy the values from one vec4 to another
- *
- * @param {vec4} out the receiving vector
- * @param {ReadonlyVec4} a the source vector
- * @returns {vec4} out
- */
- function copy$2(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- return out;
- }
- /**
- * Normalize a vec4
- *
- * @param {vec4} out the receiving vector
- * @param {ReadonlyVec4} a vector to normalize
- * @returns {vec4} out
- */
- function normalize$1(out, a) {
- var x = a[0];
- var y = a[1];
- var z = a[2];
- var w = a[3];
- var len = x * x + y * y + z * z + w * w;
- if (len > 0) {
- len = 1 / Math.sqrt(len);
- }
- out[0] = x * len;
- out[1] = y * len;
- out[2] = z * len;
- out[3] = w * len;
- return out;
- }
- /**
- * Transforms the vec4 with a mat4.
- *
- * @param {vec4} out the receiving vector
- * @param {ReadonlyVec4} a the vector to transform
- * @param {ReadonlyMat4} m matrix to transform with
- * @returns {vec4} out
- */
- function transformMat4$1(out, a, m) {
- var x = a[0],
- y = a[1],
- z = a[2],
- w = a[3];
- out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
- out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
- out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
- out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
- return out;
- }
- /**
- * Perform some operation over an array of vec4s.
- *
- * @param {Array} a the array of vectors to iterate over
- * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
- * @param {Number} offset Number of elements to skip at the beginning of the array
- * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
- * @param {Function} fn Function to call for each vector in the array
- * @param {Object} [arg] additional argument to pass to fn
- * @returns {Array} a
- * @function
- */
- var forEach$1 = function () {
- var vec = create$3();
- return function (a, stride, offset, count, fn, arg) {
- var i, l;
- if (!stride) {
- stride = 4;
- }
- if (!offset) {
- offset = 0;
- }
- if (count) {
- l = Math.min(count * stride + offset, a.length);
- } else {
- l = a.length;
- }
- for (i = offset; i < l; i += stride) {
- vec[0] = a[i];
- vec[1] = a[i + 1];
- vec[2] = a[i + 2];
- vec[3] = a[i + 3];
- fn(vec, vec, arg);
- a[i] = vec[0];
- a[i + 1] = vec[1];
- a[i + 2] = vec[2];
- a[i + 3] = vec[3];
- }
- return a;
- };
- }();
- /**
- * Quaternion
- * @module quat
- */
- /**
- * Creates a new identity quat
- *
- * @returns {quat} a new quaternion
- */
- function create$4() {
- var out = new ARRAY_TYPE(4);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- }
- out[3] = 1;
- return out;
- }
- /**
- * Sets a quat from the given angle and rotation axis,
- * then returns it.
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyVec3} axis the axis around which to rotate
- * @param {Number} rad the angle in radians
- * @returns {quat} out
- **/
- function setAxisAngle(out, axis, rad) {
- rad = rad * 0.5;
- var s = Math.sin(rad);
- out[0] = s * axis[0];
- out[1] = s * axis[1];
- out[2] = s * axis[2];
- out[3] = Math.cos(rad);
- return out;
- }
- /**
- * Multiplies two quat's
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the first operand
- * @param {ReadonlyQuat} b the second operand
- * @returns {quat} out
- */
- function multiply$2(out, a, b) {
- var ax = a[0],
- ay = a[1],
- az = a[2],
- aw = a[3];
- var bx = b[0],
- by = b[1],
- bz = b[2],
- bw = b[3];
- out[0] = ax * bw + aw * bx + ay * bz - az * by;
- out[1] = ay * bw + aw * by + az * bx - ax * bz;
- out[2] = az * bw + aw * bz + ax * by - ay * bx;
- out[3] = aw * bw - ax * bx - ay * by - az * bz;
- return out;
- }
- /**
- * Performs a spherical linear interpolation between two quat
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the first operand
- * @param {ReadonlyQuat} b the second operand
- * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
- * @returns {quat} out
- */
- function slerp(out, a, b, t) {
- // benchmarks:
- // http://jsperf.com/quaternion-slerp-implementations
- var ax = a[0],
- ay = a[1],
- az = a[2],
- aw = a[3];
- var bx = b[0],
- by = b[1],
- bz = b[2],
- bw = b[3];
- var omega, cosom, sinom, scale0, scale1; // calc cosine
- cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
- if (cosom < 0.0) {
- cosom = -cosom;
- bx = -bx;
- by = -by;
- bz = -bz;
- bw = -bw;
- } // calculate coefficients
- if (1.0 - cosom > EPSILON) {
- // standard case (slerp)
- omega = Math.acos(cosom);
- sinom = Math.sin(omega);
- scale0 = Math.sin((1.0 - t) * omega) / sinom;
- scale1 = Math.sin(t * omega) / sinom;
- } else {
- // "from" and "to" quaternions are very close
- // ... so we can do a linear interpolation
- scale0 = 1.0 - t;
- scale1 = t;
- } // calculate final values
- out[0] = scale0 * ax + scale1 * bx;
- out[1] = scale0 * ay + scale1 * by;
- out[2] = scale0 * az + scale1 * bz;
- out[3] = scale0 * aw + scale1 * bw;
- return out;
- }
- /**
- * Calculates the inverse of a quat
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a quat to calculate inverse of
- * @returns {quat} out
- */
- function invert$1(out, a) {
- var a0 = a[0],
- a1 = a[1],
- a2 = a[2],
- a3 = a[3];
- var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
- var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
- out[0] = -a0 * invDot;
- out[1] = -a1 * invDot;
- out[2] = -a2 * invDot;
- out[3] = a3 * invDot;
- return out;
- }
- /**
- * Creates a quaternion from the given 3x3 rotation matrix.
- *
- * NOTE: The resultant quaternion is not normalized, so you should be sure
- * to renormalize the quaternion yourself where necessary.
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyMat3} m rotation matrix
- * @returns {quat} out
- * @function
- */
- function fromMat3(out, m) {
- // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
- // article "Quaternion Calculus and Fast Animation".
- var fTrace = m[0] + m[4] + m[8];
- var fRoot;
- if (fTrace > 0.0) {
- // |w| > 1/2, may as well choose w > 1/2
- fRoot = Math.sqrt(fTrace + 1.0); // 2w
- out[3] = 0.5 * fRoot;
- fRoot = 0.5 / fRoot; // 1/(4w)
- out[0] = (m[5] - m[7]) * fRoot;
- out[1] = (m[6] - m[2]) * fRoot;
- out[2] = (m[1] - m[3]) * fRoot;
- } else {
- // |w| <= 1/2
- var i = 0;
- if (m[4] > m[0]) i = 1;
- if (m[8] > m[i * 3 + i]) i = 2;
- var j = (i + 1) % 3;
- var k = (i + 2) % 3;
- fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
- out[i] = 0.5 * fRoot;
- fRoot = 0.5 / fRoot;
- out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
- out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
- out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
- }
- return out;
- }
- /**
- * Creates a quaternion from the given euler angle x, y, z.
- *
- * @param {quat} out the receiving quaternion
- * @param {x} Angle to rotate around X axis in degrees.
- * @param {y} Angle to rotate around Y axis in degrees.
- * @param {z} Angle to rotate around Z axis in degrees.
- * @returns {quat} out
- * @function
- */
- function fromEuler(out, x, y, z) {
- var halfToRad = 0.5 * Math.PI / 180.0;
- x *= halfToRad;
- y *= halfToRad;
- z *= halfToRad;
- var sx = Math.sin(x);
- var cx = Math.cos(x);
- var sy = Math.sin(y);
- var cy = Math.cos(y);
- var sz = Math.sin(z);
- var cz = Math.cos(z);
- out[0] = sx * cy * cz - cx * sy * sz;
- out[1] = cx * sy * cz + sx * cy * sz;
- out[2] = cx * cy * sz - sx * sy * cz;
- out[3] = cx * cy * cz + sx * sy * sz;
- return out;
- }
- /**
- * Creates a new quat initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @param {Number} w W component
- * @returns {quat} a new quaternion
- * @function
- */
- var fromValues$4 = fromValues$3;
- /**
- * Copy the values from one quat to another
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the source quaternion
- * @returns {quat} out
- * @function
- */
- var copy$3 = copy$2;
- /**
- * Alias for {@link quat.multiply}
- * @function
- */
- var mul$1 = multiply$2;
- /**
- * Normalize a quat
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a quaternion to normalize
- * @returns {quat} out
- * @function
- */
- var normalize$2 = normalize$1;
- /**
- * Sets a quaternion to represent the shortest rotation from one
- * vector to another.
- *
- * Both vectors are assumed to be unit length.
- *
- * @param {quat} out the receiving quaternion.
- * @param {ReadonlyVec3} a the initial vector
- * @param {ReadonlyVec3} b the destination vector
- * @returns {quat} out
- */
- var rotationTo = function () {
- var tmpvec3 = create$2();
- var xUnitVec3 = fromValues$2(1, 0, 0);
- var yUnitVec3 = fromValues$2(0, 1, 0);
- return function (out, a, b) {
- var dot$1 = dot(a, b);
- if (dot$1 < -0.999999) {
- cross(tmpvec3, xUnitVec3, a);
- if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
- normalize(tmpvec3, tmpvec3);
- setAxisAngle(out, tmpvec3, Math.PI);
- return out;
- } else if (dot$1 > 0.999999) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- out[3] = 1;
- return out;
- } else {
- cross(tmpvec3, a, b);
- out[0] = tmpvec3[0];
- out[1] = tmpvec3[1];
- out[2] = tmpvec3[2];
- out[3] = 1 + dot$1;
- return normalize$2(out, out);
- }
- };
- }();
- /**
- * Performs a spherical linear interpolation with two control points
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the first operand
- * @param {ReadonlyQuat} b the second operand
- * @param {ReadonlyQuat} c the third operand
- * @param {ReadonlyQuat} d the fourth operand
- * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
- * @returns {quat} out
- */
- var sqlerp = function () {
- var temp1 = create$4();
- var temp2 = create$4();
- return function (out, a, b, c, d, t) {
- slerp(temp1, a, d, t);
- slerp(temp2, b, c, t);
- slerp(out, temp1, temp2, 2 * t * (1 - t));
- return out;
- };
- }();
- /**
- * Sets the specified quaternion with values corresponding to the given
- * axes. Each axis is a vec3 and is expected to be unit length and
- * perpendicular to all other specified axes.
- *
- * @param {ReadonlyVec3} view the vector representing the viewing direction
- * @param {ReadonlyVec3} right the vector representing the local "right" direction
- * @param {ReadonlyVec3} up the vector representing the local "up" direction
- * @returns {quat} out
- */
- var setAxes = function () {
- var matr = create();
- return function (out, view, right, up) {
- matr[0] = right[0];
- matr[3] = right[1];
- matr[6] = right[2];
- matr[1] = up[0];
- matr[4] = up[1];
- matr[7] = up[2];
- matr[2] = -view[0];
- matr[5] = -view[1];
- matr[8] = -view[2];
- return normalize$2(out, fromMat3(out, matr));
- };
- }();
- /**
- * 2 Dimensional Vector
- * @module vec2
- */
- /**
- * Creates a new, empty vec2
- *
- * @returns {vec2} a new 2D vector
- */
- function create$5() {
- var out = new ARRAY_TYPE(2);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- }
- return out;
- }
- /**
- * Creates a new vec2 initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @returns {vec2} a new 2D vector
- */
- function fromValues$5(x, y) {
- var out = new ARRAY_TYPE(2);
- out[0] = x;
- out[1] = y;
- return out;
- }
- /**
- * Copy the values from one vec2 to another
- *
- * @param {vec2} out the receiving vector
- * @param {ReadonlyVec2} a the source vector
- * @returns {vec2} out
- */
- function copy$4(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- return out;
- }
- /**
- * Normalize a vec2
- *
- * @param {vec2} out the receiving vector
- * @param {ReadonlyVec2} a vector to normalize
- * @returns {vec2} out
- */
- function normalize$3(out, a) {
- var x = a[0],
- y = a[1];
- var len = x * x + y * y;
- if (len > 0) {
- //TODO: evaluate use of glm_invsqrt here?
- len = 1 / Math.sqrt(len);
- }
- out[0] = a[0] * len;
- out[1] = a[1] * len;
- return out;
- }
- /**
- * Calculates the dot product of two vec2's
- *
- * @param {ReadonlyVec2} a the first operand
- * @param {ReadonlyVec2} b the second operand
- * @returns {Number} dot product of a and b
- */
- function dot$1(a, b) {
- return a[0] * b[0] + a[1] * b[1];
- }
- /**
- * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
- *
- * @param {ReadonlyVec2} a The first vector.
- * @param {ReadonlyVec2} b The second vector.
- * @returns {Boolean} True if the vectors are equal, false otherwise.
- */
- function exactEquals$1(a, b) {
- return a[0] === b[0] && a[1] === b[1];
- }
- /**
- * Perform some operation over an array of vec2s.
- *
- * @param {Array} a the array of vectors to iterate over
- * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
- * @param {Number} offset Number of elements to skip at the beginning of the array
- * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
- * @param {Function} fn Function to call for each vector in the array
- * @param {Object} [arg] additional argument to pass to fn
- * @returns {Array} a
- * @function
- */
- var forEach$2 = function () {
- var vec = create$5();
- return function (a, stride, offset, count, fn, arg) {
- var i, l;
- if (!stride) {
- stride = 2;
- }
- if (!offset) {
- offset = 0;
- }
- if (count) {
- l = Math.min(count * stride + offset, a.length);
- } else {
- l = a.length;
- }
- for (i = offset; i < l; i += stride) {
- vec[0] = a[i];
- vec[1] = a[i + 1];
- fn(vec, vec, arg);
- a[i] = vec[0];
- a[i + 1] = vec[1];
- }
- return a;
- };
- }();
- function clonePath(path) {
- return path.map(function (x) { return (Array.isArray(x) ? [].concat(x) : x); });
- }
- /******************************************************************************
- Copyright (c) Microsoft Corporation.
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
- var paramsParser = {
- x1: 0,
- y1: 0,
- x2: 0,
- y2: 0,
- x: 0,
- y: 0,
- qx: null,
- qy: null,
- };
- function fixArc(pathArray, allPathCommands, i) {
- if (pathArray[i].length > 7) {
- pathArray[i].shift();
- var pi = pathArray[i];
- // const ni = i + 1;
- var ni = i;
- while (pi.length) {
- // if created multiple C:s, their original seg is saved
- allPathCommands[i] = 'A';
- // @ts-ignore
- pathArray.splice((ni += 1), 0, ['C'].concat(pi.splice(0, 6)));
- }
- pathArray.splice(i, 1);
- }
- }
- var paramsCount = {
- a: 7,
- c: 6,
- h: 1,
- l: 2,
- m: 2,
- r: 4,
- q: 4,
- s: 4,
- t: 2,
- v: 1,
- z: 0,
- };
- /**
- * Iterates an array to check if it's an actual `PathArray`.
- */
- function isPathArray(path) {
- return (Array.isArray(path) &&
- path.every(function (seg) {
- var lk = seg[0].toLowerCase();
- return paramsCount[lk] === seg.length - 1 && 'achlmqstvz'.includes(lk);
- }));
- }
- /**
- * Iterates an array to check if it's a `PathArray`
- * with all absolute values.
- */
- function isAbsoluteArray(path) {
- return (isPathArray(path) &&
- // @ts-ignore -- `isPathArray` also checks if it's `Array`
- path.every(function (_a) {
- var x = _a[0];
- return x === x.toUpperCase();
- }));
- }
- /**
- * Iterates an array to check if it's a `PathArray`
- * with all segments are in non-shorthand notation
- * with absolute values.
- */
- function isNormalizedArray(path) {
- return isAbsoluteArray(path) && path.every(function (_a) {
- var pc = _a[0];
- return 'ACLMQZ'.includes(pc);
- });
- }
- /**
- * Breaks the parsing of a pathString once a segment is finalized.
- */
- function finalizeSegment(path) {
- var pathCommand = path.pathValue[path.segmentStart];
- var LK = pathCommand.toLowerCase();
- var data = path.data;
- while (data.length >= paramsCount[LK]) {
- // overloaded `moveTo`
- // https://github.com/rveciana/svg-path-properties/blob/master/src/parse.ts
- if (LK === 'm' && data.length > 2) {
- // @ts-ignore
- path.segments.push([pathCommand].concat(data.splice(0, 2)));
- LK = 'l';
- pathCommand = pathCommand === 'm' ? 'l' : 'L';
- }
- else {
- // @ts-ignore
- path.segments.push([pathCommand].concat(data.splice(0, paramsCount[LK])));
- }
- if (!paramsCount[LK]) {
- break;
- }
- }
- }
- /**
- * Validates an A (arc-to) specific path command value.
- * Usually a `large-arc-flag` or `sweep-flag`.
- */
- function scanFlag(path) {
- var index = path.index, pathValue = path.pathValue;
- var code = pathValue.charCodeAt(index);
- if (code === 0x30 /* 0 */) {
- path.param = 0;
- path.index += 1;
- return;
- }
- if (code === 0x31 /* 1 */) {
- path.param = 1;
- path.index += 1;
- return;
- }
- path.err = "[path-util]: invalid Arc flag \"" + pathValue[index] + "\", expecting 0 or 1 at index " + index;
- }
- /**
- * Checks if the character is or belongs to a number.
- * [0-9]|+|-|.
- */
- function isDigitStart(code) {
- return ((code >= 48 && code <= 57) /* 0..9 */ || code === 0x2b /* + */ || code === 0x2d /* - */ || code === 0x2e); /* . */
- }
- function isDigit(code) {
- return code >= 48 && code <= 57; // 0..9
- }
- /**
- * Validates every character of the path string,
- * every path command, negative numbers or floating point numbers.
- */
- function scanParam(path) {
- var max = path.max, pathValue = path.pathValue, start = path.index;
- var index = start;
- var zeroFirst = false;
- var hasCeiling = false;
- var hasDecimal = false;
- var hasDot = false;
- var ch;
- if (index >= max) {
- // path.err = 'SvgPath: missed param (at pos ' + index + ')';
- path.err = "[path-util]: Invalid path value at index " + index + ", \"pathValue\" is missing param";
- return;
- }
- ch = pathValue.charCodeAt(index);
- if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
- index += 1;
- // ch = (index < max) ? pathValue.charCodeAt(index) : 0;
- ch = pathValue.charCodeAt(index);
- }
- // This logic is shamelessly borrowed from Esprima
- // https://github.com/ariya/esprimas
- if (!isDigit(ch) && ch !== 0x2e /* . */) {
- // path.err = 'SvgPath: param should start with 0..9 or `.` (at pos ' + index + ')';
- path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" is not a number";
- return;
- }
- if (ch !== 0x2e /* . */) {
- zeroFirst = ch === 0x30 /* 0 */;
- index += 1;
- ch = pathValue.charCodeAt(index);
- if (zeroFirst && index < max) {
- // decimal number starts with '0' such as '09' is illegal.
- if (ch && isDigit(ch)) {
- // path.err = 'SvgPath: numbers started with `0` such as `09`
- // are illegal (at pos ' + start + ')';
- path.err = "[path-util]: Invalid path value at index " + start + ", \"" + pathValue[start] + "\" illegal number";
- return;
- }
- }
- while (index < max && isDigit(pathValue.charCodeAt(index))) {
- index += 1;
- hasCeiling = true;
- }
- ch = pathValue.charCodeAt(index);
- }
- if (ch === 0x2e /* . */) {
- hasDot = true;
- index += 1;
- while (isDigit(pathValue.charCodeAt(index))) {
- index += 1;
- hasDecimal = true;
- }
- ch = pathValue.charCodeAt(index);
- }
- if (ch === 0x65 /* e */ || ch === 0x45 /* E */) {
- if (hasDot && !hasCeiling && !hasDecimal) {
- path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" invalid float exponent";
- return;
- }
- index += 1;
- ch = pathValue.charCodeAt(index);
- if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
- index += 1;
- }
- if (index < max && isDigit(pathValue.charCodeAt(index))) {
- while (index < max && isDigit(pathValue.charCodeAt(index))) {
- index += 1;
- }
- }
- else {
- path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" invalid integer exponent";
- return;
- }
- }
- path.index = index;
- path.param = +path.pathValue.slice(start, index);
- }
- /**
- * Checks if the character is a space.
- */
- function isSpace(ch) {
- var specialSpaces = [
- 0x1680, 0x180e, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x202f,
- 0x205f, 0x3000, 0xfeff,
- ];
- /* istanbul ignore next */
- return (ch === 0x0a ||
- ch === 0x0d ||
- ch === 0x2028 ||
- ch === 0x2029 || // Line terminators
- // White spaces
- ch === 0x20 ||
- ch === 0x09 ||
- ch === 0x0b ||
- ch === 0x0c ||
- ch === 0xa0 ||
- (ch >= 0x1680 && specialSpaces.includes(ch)));
- }
- /**
- * Points the parser to the next character in the
- * path string every time it encounters any kind of
- * space character.
- */
- function skipSpaces(path) {
- var pathValue = path.pathValue, max = path.max;
- while (path.index < max && isSpace(pathValue.charCodeAt(path.index))) {
- path.index += 1;
- }
- }
- /**
- * Checks if the character is a path command.
- */
- function isPathCommand(code) {
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy
- switch (code | 0x20) {
- case 0x6d /* m */:
- case 0x7a /* z */:
- case 0x6c /* l */:
- case 0x68 /* h */:
- case 0x76 /* v */:
- case 0x63 /* c */:
- case 0x73 /* s */:
- case 0x71 /* q */:
- case 0x74 /* t */:
- case 0x61 /* a */:
- // case 0x72/* r */:
- return true;
- default:
- return false;
- }
- }
- /**
- * Checks if the character is an A (arc-to) path command.
- */
- function isArcCommand(code) {
- return (code | 0x20) === 0x61;
- }
- /**
- * Scans every character in the path string to determine
- * where a segment starts and where it ends.
- */
- function scanSegment(path) {
- var max = path.max, pathValue = path.pathValue, index = path.index;
- var cmdCode = pathValue.charCodeAt(index);
- var reqParams = paramsCount[pathValue[index].toLowerCase()];
- path.segmentStart = index;
- if (!isPathCommand(cmdCode)) {
- path.err = "[path-util]: Invalid path value \"" + pathValue[index] + "\" is not a path command";
- return;
- }
- path.index += 1;
- skipSpaces(path);
- path.data = [];
- if (!reqParams) {
- // Z
- finalizeSegment(path);
- return;
- }
- for (;;) {
- for (var i = reqParams; i > 0; i -= 1) {
- if (isArcCommand(cmdCode) && (i === 3 || i === 4))
- scanFlag(path);
- else
- scanParam(path);
- if (path.err.length) {
- return;
- }
- path.data.push(path.param);
- skipSpaces(path);
- // after ',' param is mandatory
- if (path.index < max && pathValue.charCodeAt(path.index) === 0x2c /* , */) {
- path.index += 1;
- skipSpaces(path);
- }
- }
- if (path.index >= path.max) {
- break;
- }
- // Stop on next segment
- if (!isDigitStart(pathValue.charCodeAt(path.index))) {
- break;
- }
- }
- finalizeSegment(path);
- }
- /**
- * The `PathParser` is used by the `parsePathString` static method
- * to generate a `pathArray`.
- */
- var PathParser = /** @class */ (function () {
- function PathParser(pathString) {
- this.pathValue = pathString;
- // @ts-ignore
- this.segments = [];
- this.max = pathString.length;
- this.index = 0;
- this.param = 0.0;
- this.segmentStart = 0;
- this.data = [];
- this.err = '';
- }
- return PathParser;
- }());
- /**
- * Parses a path string value and returns an array
- * of segments we like to call `pathArray`.
- */
- function parsePathString(pathInput) {
- if (isPathArray(pathInput)) {
- return clonePath(pathInput);
- }
- var path = new PathParser(pathInput);
- skipSpaces(path);
- while (path.index < path.max && !path.err.length) {
- scanSegment(path);
- }
- return path.err ? path.err : path.segments;
- }
- function path2Absolute(pathInput) {
- if (isAbsoluteArray(pathInput)) {
- return clonePath(pathInput);
- }
- var path = parsePathString(pathInput);
- // if (!path || !path.length) {
- // return [['M', 0, 0]];
- // }
- var x = 0;
- var y = 0;
- var mx = 0;
- var my = 0;
- // @ts-ignore
- return path.map(function (segment) {
- var values = segment.slice(1).map(Number);
- var pathCommand = segment[0];
- var absCommand = pathCommand.toUpperCase();
- if (pathCommand === 'M') {
- x = values[0], y = values[1];
- mx = x;
- my = y;
- return ['M', x, y];
- }
- var absoluteSegment;
- if (pathCommand !== absCommand) {
- switch (absCommand) {
- case 'A':
- absoluteSegment = [
- absCommand,
- values[0],
- values[1],
- values[2],
- values[3],
- values[4],
- values[5] + x,
- values[6] + y,
- ];
- break;
- case 'V':
- absoluteSegment = [absCommand, values[0] + y];
- break;
- case 'H':
- absoluteSegment = [absCommand, values[0] + x];
- break;
- default: {
- // use brakets for `eslint: no-case-declaration`
- // https://stackoverflow.com/a/50753272/803358
- var absValues = values.map(function (n, j) { return n + (j % 2 ? y : x); });
- // for n, l, c, s, q, t
- // @ts-ignore
- absoluteSegment = [absCommand].concat(absValues);
- }
- }
- }
- else {
- // @ts-ignore
- absoluteSegment = [absCommand].concat(values);
- }
- var segLength = absoluteSegment.length;
- switch (absCommand) {
- case 'Z':
- x = mx;
- y = my;
- break;
- case 'H':
- x = absoluteSegment[1];
- break;
- case 'V':
- y = absoluteSegment[1];
- break;
- default:
- x = absoluteSegment[segLength - 2];
- y = absoluteSegment[segLength - 1];
- if (absCommand === 'M') {
- mx = x;
- my = y;
- }
- }
- return absoluteSegment;
- });
- }
- /**
- * Normalizes a single segment of a `PathArray` object.
- * eg. H/V -> L, T -> Q
- */
- function normalizeSegment(segment, params) {
- var pathCommand = segment[0];
- var px1 = params.x1, py1 = params.y1, px2 = params.x2, py2 = params.y2;
- var values = segment.slice(1).map(Number);
- var result = segment;
- if (!'TQ'.includes(pathCommand)) {
- // optional but good to be cautious
- params.qx = null;
- params.qy = null;
- }
- if (pathCommand === 'H') {
- result = ['L', segment[1], py1];
- }
- else if (pathCommand === 'V') {
- result = ['L', px1, segment[1]];
- }
- else if (pathCommand === 'S') {
- var x1 = px1 * 2 - px2;
- var y1 = py1 * 2 - py2;
- params.x1 = x1;
- params.y1 = y1;
- result = ['C', x1, y1].concat(values);
- }
- else if (pathCommand === 'T') {
- var qx = px1 * 2 - params.qx;
- var qy = py1 * 2 - params.qy;
- params.qx = qx;
- params.qy = qy;
- result = ['Q', qx, qy].concat(values);
- }
- else if (pathCommand === 'Q') {
- var nqx = values[0], nqy = values[1];
- params.qx = nqx;
- params.qy = nqy;
- }
- return result;
- }
- /**
- * @example
- * const path = 'M0 0 H50';
- * const normalizedPath = SVGPathCommander.normalizePath(path);
- * // result => [['M', 0, 0], ['L', 50, 0]]
- */
- function normalizePath(pathInput) {
- if (isNormalizedArray(pathInput)) {
- return clonePath(pathInput);
- }
- var path = path2Absolute(pathInput);
- var params = __assign({}, paramsParser);
- for (var i = 0; i < path.length; i += 1) {
- // Save current path command
- path[i] = normalizeSegment(path[i], params);
- var segment = path[i];
- var seglen = segment.length;
- params.x1 = +segment[seglen - 2];
- params.y1 = +segment[seglen - 1];
- params.x2 = +segment[seglen - 4] || params.x1;
- params.y2 = +segment[seglen - 3] || params.y1;
- }
- return path;
- }
- /**
- * Iterates an array to check if it's a `PathArray`
- * with all C (cubic bezier) segments.
- *
- * @param {string | PathArray} path the `Array` to be checked
- * @returns {boolean} iteration result
- */
- function isCurveArray(path) {
- return isNormalizedArray(path) && path.every(function (_a) {
- var pc = _a[0];
- return 'MC'.includes(pc);
- });
- }
- function rotateVector(x, y, rad) {
- var X = x * Math.cos(rad) - y * Math.sin(rad);
- var Y = x * Math.sin(rad) + y * Math.cos(rad);
- return { x: X, y: Y };
- }
- /**
- * Converts A (arc-to) segments to C (cubic-bezier-to).
- *
- * For more information of where this math came from visit:
- * http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
- */
- function arcToCubic(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, recursive) {
- var x1 = X1;
- var y1 = Y1;
- var rx = RX;
- var ry = RY;
- var x2 = X2;
- var y2 = Y2;
- // for more information of where this Math came from visit:
- // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
- var d120 = (Math.PI * 120) / 180;
- var rad = (Math.PI / 180) * (+angle || 0);
- /** @type {number[]} */
- var res = [];
- var xy;
- var f1;
- var f2;
- var cx;
- var cy;
- if (!recursive) {
- xy = rotateVector(x1, y1, -rad);
- x1 = xy.x;
- y1 = xy.y;
- xy = rotateVector(x2, y2, -rad);
- x2 = xy.x;
- y2 = xy.y;
- var x = (x1 - x2) / 2;
- var y = (y1 - y2) / 2;
- var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
- if (h > 1) {
- h = Math.sqrt(h);
- rx *= h;
- ry *= h;
- }
- var rx2 = rx * rx;
- var ry2 = ry * ry;
- var k = (LAF === SF ? -1 : 1) *
- Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)));
- cx = (k * rx * y) / ry + (x1 + x2) / 2;
- cy = (k * -ry * x) / rx + (y1 + y2) / 2;
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
- f1 = Math.asin(((((y1 - cy) / ry) * Math.pow(10, 9)) >> 0) / Math.pow(10, 9));
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
- f2 = Math.asin(((((y2 - cy) / ry) * Math.pow(10, 9)) >> 0) / Math.pow(10, 9));
- f1 = x1 < cx ? Math.PI - f1 : f1;
- f2 = x2 < cx ? Math.PI - f2 : f2;
- if (f1 < 0)
- f1 = Math.PI * 2 + f1;
- if (f2 < 0)
- f2 = Math.PI * 2 + f2;
- if (SF && f1 > f2) {
- f1 -= Math.PI * 2;
- }
- if (!SF && f2 > f1) {
- f2 -= Math.PI * 2;
- }
- }
- else {
- f1 = recursive[0], f2 = recursive[1], cx = recursive[2], cy = recursive[3];
- }
- var df = f2 - f1;
- if (Math.abs(df) > d120) {
- var f2old = f2;
- var x2old = x2;
- var y2old = y2;
- f2 = f1 + d120 * (SF && f2 > f1 ? 1 : -1);
- x2 = cx + rx * Math.cos(f2);
- y2 = cy + ry * Math.sin(f2);
- res = arcToCubic(x2, y2, rx, ry, angle, 0, SF, x2old, y2old, [f2, f2old, cx, cy]);
- }
- df = f2 - f1;
- var c1 = Math.cos(f1);
- var s1 = Math.sin(f1);
- var c2 = Math.cos(f2);
- var s2 = Math.sin(f2);
- var t = Math.tan(df / 4);
- var hx = (4 / 3) * rx * t;
- var hy = (4 / 3) * ry * t;
- var m1 = [x1, y1];
- var m2 = [x1 + hx * s1, y1 - hy * c1];
- var m3 = [x2 + hx * s2, y2 - hy * c2];
- var m4 = [x2, y2];
- m2[0] = 2 * m1[0] - m2[0];
- m2[1] = 2 * m1[1] - m2[1];
- if (recursive) {
- return m2.concat(m3, m4, res);
- // return [...m2, ...m3, ...m4, ...res];
- }
- res = m2.concat(m3, m4, res);
- // res = [...m2, ...m3, ...m4, ...res];
- var newres = [];
- for (var i = 0, ii = res.length; i < ii; i += 1) {
- newres[i] = i % 2 ? rotateVector(res[i - 1], res[i], rad).y : rotateVector(res[i], res[i + 1], rad).x;
- }
- return newres;
- }
- // const TAU = Math.PI * 2;
- // const mapToEllipse = (
- // { x, y }: { x: number; y: number },
- // rx: number,
- // ry: number,
- // cosphi: number,
- // sinphi: number,
- // centerx: number,
- // centery: number,
- // ) => {
- // x *= rx;
- // y *= ry;
- // const xp = cosphi * x - sinphi * y;
- // const yp = sinphi * x + cosphi * y;
- // return {
- // x: xp + centerx,
- // y: yp + centery,
- // };
- // };
- // const approxUnitArc = (ang1: number, ang2: number) => {
- // // If 90 degree circular arc, use a constant
- // // as derived from http://spencermortensen.com/articles/bezier-circle
- // const a =
- // ang2 === 1.5707963267948966
- // ? 0.551915024494
- // : ang2 === -1.5707963267948966
- // ? -0.551915024494
- // : (4 / 3) * Math.tan(ang2 / 4);
- // const x1 = Math.cos(ang1);
- // const y1 = Math.sin(ang1);
- // const x2 = Math.cos(ang1 + ang2);
- // const y2 = Math.sin(ang1 + ang2);
- // return [
- // {
- // x: x1 - y1 * a,
- // y: y1 + x1 * a,
- // },
- // {
- // x: x2 + y2 * a,
- // y: y2 - x2 * a,
- // },
- // {
- // x: x2,
- // y: y2,
- // },
- // ];
- // };
- // const vectorAngle = (ux: number, uy: number, vx: number, vy: number) => {
- // const sign = ux * vy - uy * vx < 0 ? -1 : 1;
- // let dot = ux * vx + uy * vy;
- // if (dot > 1) {
- // dot = 1;
- // }
- // if (dot < -1) {
- // dot = -1;
- // }
- // return sign * Math.acos(dot);
- // };
- // const getArcCenter = (
- // px: any,
- // py: any,
- // cx: any,
- // cy: any,
- // rx: number,
- // ry: number,
- // largeArcFlag: number,
- // sweepFlag: number,
- // sinphi: number,
- // cosphi: number,
- // pxp: number,
- // pyp: number,
- // ) => {
- // const rxsq = Math.pow(rx, 2);
- // const rysq = Math.pow(ry, 2);
- // const pxpsq = Math.pow(pxp, 2);
- // const pypsq = Math.pow(pyp, 2);
- // let radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;
- // if (radicant < 0) {
- // radicant = 0;
- // }
- // radicant /= rxsq * pypsq + rysq * pxpsq;
- // radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
- // const centerxp = ((radicant * rx) / ry) * pyp;
- // const centeryp = ((radicant * -ry) / rx) * pxp;
- // const centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
- // const centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;
- // const vx1 = (pxp - centerxp) / rx;
- // const vy1 = (pyp - centeryp) / ry;
- // const vx2 = (-pxp - centerxp) / rx;
- // const vy2 = (-pyp - centeryp) / ry;
- // const ang1 = vectorAngle(1, 0, vx1, vy1);
- // let ang2 = vectorAngle(vx1, vy1, vx2, vy2);
- // if (sweepFlag === 0 && ang2 > 0) {
- // ang2 -= TAU;
- // }
- // if (sweepFlag === 1 && ang2 < 0) {
- // ang2 += TAU;
- // }
- // return [centerx, centery, ang1, ang2];
- // };
- // const arcToBezier = ({ px, py, cx, cy, rx, ry, xAxisRotation = 0, largeArcFlag = 0, sweepFlag = 0 }) => {
- // const curves = [];
- // if (rx === 0 || ry === 0) {
- // return [{ x1: 0, y1: 0, x2: 0, y2: 0, x: cx, y: cy }];
- // }
- // const sinphi = Math.sin((xAxisRotation * TAU) / 360);
- // const cosphi = Math.cos((xAxisRotation * TAU) / 360);
- // const pxp = (cosphi * (px - cx)) / 2 + (sinphi * (py - cy)) / 2;
- // const pyp = (-sinphi * (px - cx)) / 2 + (cosphi * (py - cy)) / 2;
- // if (pxp === 0 && pyp === 0) {
- // return [{ x1: 0, y1: 0, x2: 0, y2: 0, x: cx, y: cy }];
- // }
- // rx = Math.abs(rx);
- // ry = Math.abs(ry);
- // const lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);
- // if (lambda > 1) {
- // rx *= Math.sqrt(lambda);
- // ry *= Math.sqrt(lambda);
- // }
- // let [centerx, centery, ang1, ang2] = getArcCenter(
- // px,
- // py,
- // cx,
- // cy,
- // rx,
- // ry,
- // largeArcFlag,
- // sweepFlag,
- // sinphi,
- // cosphi,
- // pxp,
- // pyp,
- // );
- // // If 'ang2' == 90.0000000001, then `ratio` will evaluate to
- // // 1.0000000001. This causes `segments` to be greater than one, which is an
- // // unecessary split, and adds extra points to the bezier curve. To alleviate
- // // this issue, we round to 1.0 when the ratio is close to 1.0.
- // let ratio = Math.abs(ang2) / (TAU / 4);
- // if (Math.abs(1.0 - ratio) < 0.0000001) {
- // ratio = 1.0;
- // }
- // const segments = Math.max(Math.ceil(ratio), 1);
- // ang2 /= segments;
- // for (let i = 0; i < segments; i++) {
- // curves.push(approxUnitArc(ang1, ang2));
- // ang1 += ang2;
- // }
- // return curves.map((curve) => {
- // const { x: x1, y: y1 } = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery);
- // const { x: x2, y: y2 } = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery);
- // const { x, y } = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery);
- // return { x1, y1, x2, y2, x, y };
- // });
- // };
- // export function arcToCubic(
- // x1: number,
- // y1: number,
- // rx: number,
- // ry: number,
- // angle: number,
- // LAF: number,
- // SF: number,
- // x2: number,
- // y2: number,
- // ) {
- // const curves = arcToBezier({
- // px: x1,
- // py: y1,
- // cx: x2,
- // cy: y2,
- // rx,
- // ry,
- // xAxisRotation: angle,
- // largeArcFlag: LAF,
- // sweepFlag: SF,
- // });
- // return curves.reduce((prev, cur) => {
- // const { x1, y1, x2, y2, x, y } = cur;
- // prev.push(x1, y1, x2, y2, x, y);
- // return prev;
- // }, [] as number[]);
- // }
- function quadToCubic(x1, y1, qx, qy, x2, y2) {
- var r13 = 1 / 3;
- var r23 = 2 / 3;
- return [
- r13 * x1 + r23 * qx,
- r13 * y1 + r23 * qy,
- r13 * x2 + r23 * qx,
- r13 * y2 + r23 * qy,
- x2,
- y2, // x,y
- ];
- }
- function midPoint(a, b, t) {
- var ax = a[0];
- var ay = a[1];
- var bx = b[0];
- var by = b[1];
- return [ax + (bx - ax) * t, ay + (by - ay) * t];
- }
- function distanceSquareRoot(a, b) {
- return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a line (L,V,H,Z) segment.
- */
- function segmentLineFactory(x1, y1, x2, y2, distance) {
- var length = distanceSquareRoot([x1, y1], [x2, y2]);
- var point = { x: 0, y: 0 };
- if (typeof distance === 'number') {
- if (distance <= 0) {
- point = { x: x1, y: y1 };
- }
- else if (distance >= length) {
- point = { x: x2, y: y2 };
- }
- else {
- var _a = midPoint([x1, y1], [x2, y2], distance / length), x = _a[0], y = _a[1];
- point = { x: x, y: y };
- }
- }
- return {
- length: length,
- point: point,
- min: {
- x: Math.min(x1, x2),
- y: Math.min(y1, y2),
- },
- max: {
- x: Math.max(x1, x2),
- y: Math.max(y1, y2),
- },
- };
- }
- function lineToCubic(x1, y1, x2, y2) {
- var t = 0.5;
- var p0 = [x1, y1];
- var p1 = [x2, y2];
- var p2 = midPoint(p0, p1, t);
- var p3 = midPoint(p1, p2, t);
- var p4 = midPoint(p2, p3, t);
- var p5 = midPoint(p3, p4, t);
- var p6 = midPoint(p4, p5, t);
- // const seg1 = [...p0, ...p2, ...p4, ...p6, t];
- // @ts-ignore
- var cp1 = segmentLineFactory(p0[0], p0[1], p2[0], p2[1], p4[0]).point;
- // const seg2 = [...p6, ...p5, ...p3, ...p1, 0];
- // @ts-ignore
- var cp2 = segmentLineFactory(p6[0], p6[1], p5[0], p5[1], p3[0]).point;
- return [cp1.x, cp1.y, cp2.x, cp2.y, x2, y2];
- }
- function segmentToCubic(segment, params) {
- var pathCommand = segment[0];
- var values = segment.slice(1).map(Number);
- var x = values[0], y = values[1];
- var args;
- var px1 = params.x1, py1 = params.y1, px = params.x, py = params.y;
- if (!'TQ'.includes(pathCommand)) {
- params.qx = null;
- params.qy = null;
- }
- switch (pathCommand) {
- case 'M':
- params.x = x;
- params.y = y;
- return segment;
- case 'A':
- args = [px1, py1].concat(values);
- // @ts-ignore
- return ['C'].concat(arcToCubic(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]));
- case 'Q':
- params.qx = x;
- params.qy = y;
- args = [px1, py1].concat(values);
- // @ts-ignore
- return ['C'].concat(quadToCubic(args[0], args[1], args[2], args[3], args[4], args[5]));
- case 'L':
- // @ts-ignore
- return ['C'].concat(lineToCubic(px1, py1, x, y));
- case 'Z':
- // prevent NaN from divide 0
- if (px1 === px && py1 === py) {
- return ['C', px1, py1, px, py, px, py];
- }
- // @ts-ignore
- return ['C'].concat(lineToCubic(px1, py1, px, py));
- }
- return segment;
- }
- // import { fixPath } from '../process/fix-path';
- function path2Curve(pathInput, needZCommandIndexes) {
- if (needZCommandIndexes === void 0) { needZCommandIndexes = false; }
- if (isCurveArray(pathInput)) {
- var cloned = clonePath(pathInput);
- if (needZCommandIndexes) {
- return [cloned, []];
- }
- else {
- return cloned;
- }
- }
- // fixPath will remove 'Z' command
- // const path = fixPath(normalizePath(pathInput));
- var path = normalizePath(pathInput);
- var params = __assign({}, paramsParser);
- var allPathCommands = [];
- var pathCommand = '';
- var ii = path.length;
- var segment;
- var seglen;
- var zCommandIndexes = [];
- for (var i = 0; i < ii; i += 1) {
- if (path[i])
- pathCommand = path[i][0];
- allPathCommands[i] = pathCommand;
- var curveSegment = segmentToCubic(path[i], params);
- path[i] = curveSegment;
- fixArc(path, allPathCommands, i);
- ii = path.length; // solves curveArrays ending in Z
- // keep Z command account for lineJoin
- // @see https://github.com/antvis/util/issues/68
- if (pathCommand === 'Z') {
- zCommandIndexes.push(i);
- }
- segment = path[i];
- seglen = segment.length;
- params.x1 = +segment[seglen - 2];
- params.y1 = +segment[seglen - 1];
- params.x2 = +segment[seglen - 4] || params.x1;
- params.y2 = +segment[seglen - 3] || params.y1;
- }
- // validate
- if (needZCommandIndexes) {
- return [path, zCommandIndexes];
- }
- else {
- return path;
- }
- }
- // reverse CURVE based pathArray segments only
- function reverseCurve(pathArray) {
- var rotatedCurve = pathArray
- .slice(1)
- .map(function (x, i, curveOnly) {
- // @ts-ignore
- return !i ? pathArray[0].slice(1).concat(x.slice(1)) : curveOnly[i - 1].slice(-2).concat(x.slice(1));
- })
- // @ts-ignore
- .map(function (x) { return x.map(function (y, i) { return x[x.length - i - 2 * (1 - (i % 2))]; }); })
- .reverse();
- return [['M'].concat(rotatedCurve[0].slice(0, 2))].concat(rotatedCurve.map(function (x) { return ['C'].concat(x.slice(2)); }));
- }
- function angleBetween(v0, v1) {
- var v0x = v0.x, v0y = v0.y;
- var v1x = v1.x, v1y = v1.y;
- var p = v0x * v1x + v0y * v1y;
- var n = Math.sqrt((Math.pow(v0x, 2) + Math.pow(v0y, 2)) * (Math.pow(v1x, 2) + Math.pow(v1y, 2)));
- var sign = v0x * v1y - v0y * v1x < 0 ? -1 : 1;
- var angle = sign * Math.acos(p / n);
- return angle;
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
- * @see https://github.com/MadLittleMods/svg-curve-lib/blob/master/src/js/svg-curve-lib.js
- */
- function getPointAtArcSegmentLength(x1, y1, RX, RY, angle, LAF, SF, x, y, t) {
- var abs = Math.abs, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, PI = Math.PI;
- var rx = abs(RX);
- var ry = abs(RY);
- var xRot = ((angle % 360) + 360) % 360;
- var xRotRad = xRot * (PI / 180);
- if (x1 === x && y1 === y) {
- return { x: x1, y: y1 };
- }
- if (rx === 0 || ry === 0) {
- return segmentLineFactory(x1, y1, x, y, t).point;
- }
- var dx = (x1 - x) / 2;
- var dy = (y1 - y) / 2;
- var transformedPoint = {
- x: cos(xRotRad) * dx + sin(xRotRad) * dy,
- y: -sin(xRotRad) * dx + cos(xRotRad) * dy,
- };
- var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
- if (radiiCheck > 1) {
- rx *= sqrt(radiiCheck);
- ry *= sqrt(radiiCheck);
- }
- var cSquareNumerator = Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) - Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cRadicand = cSquareNumerator / cSquareRootDenom;
- cRadicand = cRadicand < 0 ? 0 : cRadicand;
- var cCoef = (LAF !== SF ? 1 : -1) * sqrt(cRadicand);
- var transformedCenter = {
- x: cCoef * ((rx * transformedPoint.y) / ry),
- y: cCoef * (-(ry * transformedPoint.x) / rx),
- };
- var center = {
- x: cos(xRotRad) * transformedCenter.x - sin(xRotRad) * transformedCenter.y + (x1 + x) / 2,
- y: sin(xRotRad) * transformedCenter.x + cos(xRotRad) * transformedCenter.y + (y1 + y) / 2,
- };
- var startVector = {
- x: (transformedPoint.x - transformedCenter.x) / rx,
- y: (transformedPoint.y - transformedCenter.y) / ry,
- };
- var startAngle = angleBetween({ x: 1, y: 0 }, startVector);
- var endVector = {
- x: (-transformedPoint.x - transformedCenter.x) / rx,
- y: (-transformedPoint.y - transformedCenter.y) / ry,
- };
- var sweepAngle = angleBetween(startVector, endVector);
- if (!SF && sweepAngle > 0) {
- sweepAngle -= 2 * PI;
- }
- else if (SF && sweepAngle < 0) {
- sweepAngle += 2 * PI;
- }
- sweepAngle %= 2 * PI;
- var alpha = startAngle + sweepAngle * t;
- var ellipseComponentX = rx * cos(alpha);
- var ellipseComponentY = ry * sin(alpha);
- var point = {
- x: cos(xRotRad) * ellipseComponentX - sin(xRotRad) * ellipseComponentY + center.x,
- y: sin(xRotRad) * ellipseComponentX + cos(xRotRad) * ellipseComponentY + center.y,
- };
- // to be used later
- // point.ellipticalArcStartAngle = startAngle;
- // point.ellipticalArcEndAngle = startAngle + sweepAngle;
- // point.ellipticalArcAngle = alpha;
- // point.ellipticalArcCenter = center;
- // point.resultantRx = rx;
- // point.resultantRy = ry;
- return point;
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the shape minimum and maximum {x,y} coordinates of an A (arc-to) segment.
- *
- * For better performance, it can skip calculate bbox or length in some scenario.
- */
- function segmentArcFactory(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, distance, options) {
- var _a;
- var _b = options.bbox, bbox = _b === void 0 ? true : _b, _c = options.length, length = _c === void 0 ? true : _c, _d = options.sampleSize, sampleSize = _d === void 0 ? 30 : _d;
- var distanceIsNumber = typeof distance === 'number';
- var x = X1;
- var y = Y1;
- var LENGTH = 0;
- var prev = [x, y, LENGTH];
- var cur = [x, y];
- var t = 0;
- var POINT = { x: 0, y: 0 };
- var POINTS = [{ x: x, y: y }];
- if (distanceIsNumber && distance <= 0) {
- POINT = { x: x, y: y };
- }
- // bad perf when size > 100
- for (var j = 0; j <= sampleSize; j += 1) {
- t = j / sampleSize;
- (_a = getPointAtArcSegmentLength(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, t), x = _a.x, y = _a.y);
- if (bbox) {
- POINTS.push({ x: x, y: y });
- }
- if (length) {
- LENGTH += distanceSquareRoot(cur, [x, y]);
- }
- cur = [x, y];
- if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
- var dv = (LENGTH - distance) / (LENGTH - prev[2]);
- POINT = {
- x: cur[0] * (1 - dv) + prev[0] * dv,
- y: cur[1] * (1 - dv) + prev[1] * dv,
- };
- }
- prev = [x, y, LENGTH];
- }
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: X2, y: Y2 };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
- */
- function getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t) {
- var t1 = 1 - t;
- return {
- x: Math.pow(t1, 3) * x1 + 3 * Math.pow(t1, 2) * t * c1x + 3 * t1 * Math.pow(t, 2) * c2x + Math.pow(t, 3) * x2,
- y: Math.pow(t1, 3) * y1 + 3 * Math.pow(t1, 2) * t * c1y + 3 * t1 * Math.pow(t, 2) * c2y + Math.pow(t, 3) * y2,
- };
- }
- /**
- * Returns the length of a C (cubic-bezier) segment
- * or an {x,y} point at a given length.
- */
- function segmentCubicFactory(x1, y1, c1x, c1y, c2x, c2y, x2, y2, distance, options) {
- var _a;
- var _b = options.bbox, bbox = _b === void 0 ? true : _b, _c = options.length, length = _c === void 0 ? true : _c, _d = options.sampleSize, sampleSize = _d === void 0 ? 10 : _d;
- var distanceIsNumber = typeof distance === 'number';
- var x = x1;
- var y = y1;
- var LENGTH = 0;
- var prev = [x, y, LENGTH];
- var cur = [x, y];
- var t = 0;
- var POINT = { x: 0, y: 0 };
- var POINTS = [{ x: x, y: y }];
- if (distanceIsNumber && distance <= 0) {
- POINT = { x: x, y: y };
- }
- // bad perf when size = 300
- for (var j = 0; j <= sampleSize; j += 1) {
- t = j / sampleSize;
- (_a = getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t), x = _a.x, y = _a.y);
- if (bbox) {
- POINTS.push({ x: x, y: y });
- }
- if (length) {
- LENGTH += distanceSquareRoot(cur, [x, y]);
- }
- cur = [x, y];
- if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
- var dv = (LENGTH - distance) / (LENGTH - prev[2]);
- POINT = {
- x: cur[0] * (1 - dv) + prev[0] * dv,
- y: cur[1] * (1 - dv) + prev[1] * dv,
- };
- }
- prev = [x, y, LENGTH];
- }
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: x2, y: y2 };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns the {x,y} coordinates of a point at a
- * given length of a quadratic-bezier segment.
- *
- * @see https://github.com/substack/point-at-length
- */
- function getPointAtQuadSegmentLength(x1, y1, cx, cy, x2, y2, t) {
- var t1 = 1 - t;
- return {
- x: Math.pow(t1, 2) * x1 + 2 * t1 * t * cx + Math.pow(t, 2) * x2,
- y: Math.pow(t1, 2) * y1 + 2 * t1 * t * cy + Math.pow(t, 2) * y2,
- };
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a Q (quadratic-bezier) segment.
- */
- function segmentQuadFactory(x1, y1, qx, qy, x2, y2, distance, options) {
- var _a;
- var _b = options.bbox, bbox = _b === void 0 ? true : _b, _c = options.length, length = _c === void 0 ? true : _c, _d = options.sampleSize, sampleSize = _d === void 0 ? 10 : _d;
- var distanceIsNumber = typeof distance === 'number';
- var x = x1;
- var y = y1;
- var LENGTH = 0;
- var prev = [x, y, LENGTH];
- var cur = [x, y];
- var t = 0;
- var POINT = { x: 0, y: 0 };
- var POINTS = [{ x: x, y: y }];
- if (distanceIsNumber && distance <= 0) {
- POINT = { x: x, y: y };
- }
- for (var j = 0; j <= sampleSize; j += 1) {
- t = j / sampleSize;
- (_a = getPointAtQuadSegmentLength(x1, y1, qx, qy, x2, y2, t), x = _a.x, y = _a.y);
- if (bbox) {
- POINTS.push({ x: x, y: y });
- }
- if (length) {
- LENGTH += distanceSquareRoot(cur, [x, y]);
- }
- cur = [x, y];
- if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
- var dv = (LENGTH - distance) / (LENGTH - prev[2]);
- POINT = {
- x: cur[0] * (1 - dv) + prev[0] * dv,
- y: cur[1] * (1 - dv) + prev[1] * dv,
- };
- }
- prev = [x, y, LENGTH];
- }
- /* istanbul ignore else */
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: x2, y: y2 };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns a {x,y} point at a given length
- * of a shape, the shape total length and
- * the shape minimum and maximum {x,y} coordinates.
- */
- function pathLengthFactory(pathInput, distance, options) {
- var _a, _b, _c, _d, _e, _f;
- var path = normalizePath(pathInput);
- var distanceIsNumber = typeof distance === 'number';
- var isM;
- var data = [];
- var pathCommand;
- var x = 0;
- var y = 0;
- var mx = 0;
- var my = 0;
- var seg;
- var MIN = [];
- var MAX = [];
- var length = 0;
- var min = { x: 0, y: 0 };
- var max = min;
- var point = min;
- var POINT = min;
- var LENGTH = 0;
- for (var i = 0, ll = path.length; i < ll; i += 1) {
- seg = path[i];
- pathCommand = seg[0];
- isM = pathCommand === 'M';
- data = !isM ? [x, y].concat(seg.slice(1)) : data;
- // this segment is always ZERO
- /* istanbul ignore else */
- if (isM) {
- // remember mx, my for Z
- mx = seg[1], my = seg[2];
- min = { x: mx, y: my };
- max = min;
- length = 0;
- if (distanceIsNumber && distance < 0.001) {
- POINT = min;
- }
- }
- else if (pathCommand === 'L') {
- (_a = segmentLineFactory(data[0], data[1], data[2], data[3], (distance || 0) - LENGTH), length = _a.length, min = _a.min, max = _a.max, point = _a.point);
- }
- else if (pathCommand === 'A') {
- (_b = segmentArcFactory(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], (distance || 0) - LENGTH, options || {}), length = _b.length, min = _b.min, max = _b.max, point = _b.point);
- }
- else if (pathCommand === 'C') {
- (_c = segmentCubicFactory(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], (distance || 0) - LENGTH, options || {}), length = _c.length, min = _c.min, max = _c.max, point = _c.point);
- }
- else if (pathCommand === 'Q') {
- (_d = segmentQuadFactory(data[0], data[1], data[2], data[3], data[4], data[5], (distance || 0) - LENGTH, options || {}), length = _d.length, min = _d.min, max = _d.max, point = _d.point);
- }
- else if (pathCommand === 'Z') {
- data = [x, y, mx, my];
- (_e = segmentLineFactory(data[0], data[1], data[2], data[3], (distance || 0) - LENGTH), length = _e.length, min = _e.min, max = _e.max, point = _e.point);
- }
- if (distanceIsNumber && LENGTH < distance && LENGTH + length >= distance) {
- POINT = point;
- }
- MAX.push(max);
- MIN.push(min);
- LENGTH += length;
- _f = pathCommand !== 'Z' ? seg.slice(-2) : [mx, my], x = _f[0], y = _f[1];
- }
- // native `getPointAtLength` behavior when the given distance
- // is higher than total length
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: x, y: y };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, MIN.map(function (n) { return n.x; })),
- y: Math.min.apply(null, MIN.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, MAX.map(function (n) { return n.x; })),
- y: Math.max.apply(null, MAX.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns the shape total length, or the equivalent to `shape.getTotalLength()`.
- *
- * The `normalizePath` version is lighter, faster, more efficient and more accurate
- * with paths that are not `curveArray`.
- */
- function getTotalLength(pathInput, options) {
- return pathLengthFactory(pathInput, undefined, __assign(__assign({}, options), { bbox: false, length: true })).length;
- }
- function getRotations(a) {
- var segCount = a.length;
- var pointCount = segCount - 1;
- return a.map(function (f, idx) {
- return a.map(function (p, i) {
- var oldSegIdx = idx + i;
- var seg;
- if (i === 0 || (a[oldSegIdx] && a[oldSegIdx][0] === 'M')) {
- seg = a[oldSegIdx];
- return ['M'].concat(seg.slice(-2));
- }
- if (oldSegIdx >= segCount)
- oldSegIdx -= pointCount;
- return a[oldSegIdx];
- });
- });
- }
- function getRotatedCurve(a, b) {
- var segCount = a.length - 1;
- var lineLengths = [];
- var computedIndex = 0;
- var sumLensSqrd = 0;
- var rotations = getRotations(a);
- rotations.forEach(function (r, i) {
- a.slice(1).forEach(function (s, j) {
- // @ts-ignore
- sumLensSqrd += distanceSquareRoot(a[(i + j) % segCount].slice(-2), b[j % segCount].slice(-2));
- });
- lineLengths[i] = sumLensSqrd;
- sumLensSqrd = 0;
- });
- computedIndex = lineLengths.indexOf(Math.min.apply(null, lineLengths));
- return rotations[computedIndex];
- }
- /**
- * Returns the area of a single cubic-bezier segment.
- *
- * http://objectmix.com/graphics/133553-area-closed-bezier-curve.html
- */
- function getCubicSegArea(x1, y1, c1x, c1y, c2x, c2y, x2, y2) {
- // https://stackoverflow.com/a/15845996
- return ((3 *
- ((y2 - y1) * (c1x + c2x) -
- (x2 - x1) * (c1y + c2y) +
- c1y * (x1 - c2x) -
- c1x * (y1 - c2y) +
- y2 * (c2x + x1 / 3) -
- x2 * (c2y + y1 / 3))) /
- 20);
- }
- /**
- * Returns the area of a shape.
- * @author Jürg Lehni & Jonathan Puckey
- *
- * @see https://github.com/paperjs/paper.js/blob/develop/src/path/Path.js
- */
- function getPathArea(path) {
- var x = 0;
- var y = 0;
- var len = 0;
- return path2Curve(path)
- .map(function (seg) {
- var _a;
- switch (seg[0]) {
- case 'M':
- x = seg[1], y = seg[2];
- return 0;
- default:
- // @ts-ignore
- var _b = seg.slice(1), c1x = _b[0], c1y = _b[1], c2x = _b[2], c2y = _b[3], x2 = _b[4], y2 = _b[5];
- len = getCubicSegArea(x, y, c1x, c1y, c2x, c2y, x2, y2);
- _a = seg.slice(-2), x = _a[0], y = _a[1];
- return len;
- }
- })
- .reduce(function (a, b) { return a + b; }, 0);
- }
- // export function getPathArea(pathArray: AbsoluteArray) {
- // let x = 0;
- // let y = 0;
- // let mx = 0;
- // let my = 0;
- // let len = 0;
- // return pathArray
- // .map((seg) => {
- // switch (seg[0]) {
- // case 'M':
- // case 'Z':
- // mx = seg[0] === 'M' ? seg[1] : mx;
- // my = seg[0] === 'M' ? seg[2] : my;
- // x = mx;
- // y = my;
- // return 0;
- // default:
- // // @ts-ignore
- // len = getCubicSegArea.apply(0, [x, y].concat(seg.slice(1)));
- // [x, y] = seg.slice(-2) as [number, number];
- // return len;
- // }
- // })
- // .reduce((a, b) => a + b, 0);
- // }
- function getDrawDirection(pathArray) {
- return getPathArea(pathArray) >= 0;
- }
- /**
- * Returns [x,y] coordinates of a point at a given length of a shape.
- */
- function getPointAtLength(pathInput, distance, options) {
- return pathLengthFactory(pathInput, distance, __assign(__assign({}, options), { bbox: false, length: true })).point;
- }
- function splitCubic(pts, t) {
- if (t === void 0) { t = 0.5; }
- var p0 = pts.slice(0, 2);
- var p1 = pts.slice(2, 4);
- var p2 = pts.slice(4, 6);
- var p3 = pts.slice(6, 8);
- var p4 = midPoint(p0, p1, t);
- var p5 = midPoint(p1, p2, t);
- var p6 = midPoint(p2, p3, t);
- var p7 = midPoint(p4, p5, t);
- var p8 = midPoint(p5, p6, t);
- var p9 = midPoint(p7, p8, t);
- return [
- // @ts-ignore
- ['C'].concat(p4, p7, p9),
- // @ts-ignore
- ['C'].concat(p8, p6, p3),
- ];
- }
- function getCurveArray(segments) {
- return segments.map(function (segment, i, pathArray) {
- // @ts-ignore
- var segmentData = i && pathArray[i - 1].slice(-2).concat(segment.slice(1));
- // @ts-ignore
- var curveLength = i
- ? segmentCubicFactory(segmentData[0], segmentData[1], segmentData[2], segmentData[3], segmentData[4], segmentData[5], segmentData[6], segmentData[7], segmentData[8], { bbox: false }).length
- : 0;
- var subsegs;
- if (i) {
- // must be [segment,segment]
- subsegs = curveLength ? splitCubic(segmentData) : [segment, segment];
- }
- else {
- subsegs = [segment];
- }
- return {
- s: segment,
- ss: subsegs,
- l: curveLength,
- };
- });
- }
- function equalizeSegments(path1, path2, TL) {
- var c1 = getCurveArray(path1);
- var c2 = getCurveArray(path2);
- var L1 = c1.length;
- var L2 = c2.length;
- var l1 = c1.filter(function (x) { return x.l; }).length;
- var l2 = c2.filter(function (x) { return x.l; }).length;
- var m1 = c1.filter(function (x) { return x.l; }).reduce(function (a, _a) {
- var l = _a.l;
- return a + l;
- }, 0) / l1 || 0;
- var m2 = c2.filter(function (x) { return x.l; }).reduce(function (a, _a) {
- var l = _a.l;
- return a + l;
- }, 0) / l2 || 0;
- var tl = TL || Math.max(L1, L2);
- var mm = [m1, m2];
- var dif = [tl - L1, tl - L2];
- var canSplit = 0;
- var result = [c1, c2].map(function (x, i) {
- // @ts-ignore
- return x.l === tl
- ? x.map(function (y) { return y.s; })
- : x
- .map(function (y, j) {
- canSplit = j && dif[i] && y.l >= mm[i];
- dif[i] -= canSplit ? 1 : 0;
- return canSplit ? y.ss : [y.s];
- })
- .flat();
- });
- return result[0].length === result[1].length ? result : equalizeSegments(result[0], result[1], tl);
- }
- // isFinite,
- var isNil = function (value) {
- /**
- * isNil(null) => true
- * isNil() => true
- */
- return value === null || value === undefined;
- };
- var toString = {}.toString;
- var isType = function (value, type) { return toString.call(value) === '[object ' + type + ']'; };
- var isArray = (function (value) {
- return Array.isArray ? Array.isArray(value) : isType(value, 'Array');
- });
- var isObject = (function (value) {
- /**
- * isObject({}) => true
- * isObject([1, 2, 3]) => true
- * isObject(Function) => true
- * isObject(null) => false
- */
- var type = typeof value;
- return (value !== null && type === 'object') || type === 'function';
- });
- /**
- * @param {Array} arr The array to iterate over.
- * @return {*} Returns the maximum value.
- * @example
- *
- * max([1, 2]);
- * // => 2
- *
- * max([]);
- * // => undefined
- *
- * const data = new Array(1250010).fill(1).map((d,idx) => idx);
- *
- * max(data);
- * // => 1250010
- * // Math.max(...data) will encounter "Maximum call stack size exceeded" error
- */
- var max = (function (arr) {
- if (!isArray(arr)) {
- return undefined;
- }
- return arr.reduce(function (prev, curr) {
- return Math.max(prev, curr);
- }, arr[0]);
- });
- /**
- * @param {Array} arr The array to iterate over.
- * @return {*} Returns the minimum value.
- * @example
- *
- * min([1, 2]);
- * // => 1
- *
- * min([]);
- * // => undefined
- *
- * const data = new Array(1250010).fill(1).map((d,idx) => idx);
- *
- * min(data);
- * // => 1250010
- * // Math.min(...data) will encounter "Maximum call stack size exceeded" error
- */
- var min = (function (arr) {
- if (!isArray(arr)) {
- return undefined;
- }
- return arr.reduce(function (prev, curr) {
- return Math.min(prev, curr);
- }, arr[0]);
- });
- var isString = (function (str) {
- return isType(str, 'String');
- });
- var clamp = function (a, min, max) {
- if (a < min) {
- return min;
- }
- else if (a > max) {
- return max;
- }
- return a;
- };
- /**
- * 判断是否数字
- * @return {Boolean} 是否数字
- */
- var isNumber = function (value) {
- return isType(value, 'Number');
- };
- var PRECISION = 0.00001; // numbers less than this is considered as 0
- function isNumberEqual(a, b, precision) {
- if (precision === void 0) { precision = PRECISION; }
- return Math.abs(a - b) < precision;
- }
- var mod = function (n, m) {
- return ((n % m) + m) % m;
- };
- /**
- * 是否是布尔类型
- *
- * @param {Object} value 测试的值
- * @return {Boolean}
- */
- var isBoolean = function (value) {
- return isType(value, 'Boolean');
- };
- var isUndefined = function (value) {
- return value === undefined;
- };
- function define(constructor, factory, prototype) {
- constructor.prototype = factory.prototype = prototype;
- prototype.constructor = constructor;
- }
- function extend(parent, definition) {
- var prototype = Object.create(parent.prototype);
- for (var key in definition) prototype[key] = definition[key];
- return prototype;
- }
- function Color() {}
- var darker = 0.7;
- var brighter = 1 / darker;
- var reI = "\\s*([+-]?\\d+)\\s*",
- reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
- reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
- reHex = /^#([0-9a-f]{3,8})$/,
- reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
- reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
- reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
- reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
- reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
- reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
- var named = {
- aliceblue: 0xf0f8ff,
- antiquewhite: 0xfaebd7,
- aqua: 0x00ffff,
- aquamarine: 0x7fffd4,
- azure: 0xf0ffff,
- beige: 0xf5f5dc,
- bisque: 0xffe4c4,
- black: 0x000000,
- blanchedalmond: 0xffebcd,
- blue: 0x0000ff,
- blueviolet: 0x8a2be2,
- brown: 0xa52a2a,
- burlywood: 0xdeb887,
- cadetblue: 0x5f9ea0,
- chartreuse: 0x7fff00,
- chocolate: 0xd2691e,
- coral: 0xff7f50,
- cornflowerblue: 0x6495ed,
- cornsilk: 0xfff8dc,
- crimson: 0xdc143c,
- cyan: 0x00ffff,
- darkblue: 0x00008b,
- darkcyan: 0x008b8b,
- darkgoldenrod: 0xb8860b,
- darkgray: 0xa9a9a9,
- darkgreen: 0x006400,
- darkgrey: 0xa9a9a9,
- darkkhaki: 0xbdb76b,
- darkmagenta: 0x8b008b,
- darkolivegreen: 0x556b2f,
- darkorange: 0xff8c00,
- darkorchid: 0x9932cc,
- darkred: 0x8b0000,
- darksalmon: 0xe9967a,
- darkseagreen: 0x8fbc8f,
- darkslateblue: 0x483d8b,
- darkslategray: 0x2f4f4f,
- darkslategrey: 0x2f4f4f,
- darkturquoise: 0x00ced1,
- darkviolet: 0x9400d3,
- deeppink: 0xff1493,
- deepskyblue: 0x00bfff,
- dimgray: 0x696969,
- dimgrey: 0x696969,
- dodgerblue: 0x1e90ff,
- firebrick: 0xb22222,
- floralwhite: 0xfffaf0,
- forestgreen: 0x228b22,
- fuchsia: 0xff00ff,
- gainsboro: 0xdcdcdc,
- ghostwhite: 0xf8f8ff,
- gold: 0xffd700,
- goldenrod: 0xdaa520,
- gray: 0x808080,
- green: 0x008000,
- greenyellow: 0xadff2f,
- grey: 0x808080,
- honeydew: 0xf0fff0,
- hotpink: 0xff69b4,
- indianred: 0xcd5c5c,
- indigo: 0x4b0082,
- ivory: 0xfffff0,
- khaki: 0xf0e68c,
- lavender: 0xe6e6fa,
- lavenderblush: 0xfff0f5,
- lawngreen: 0x7cfc00,
- lemonchiffon: 0xfffacd,
- lightblue: 0xadd8e6,
- lightcoral: 0xf08080,
- lightcyan: 0xe0ffff,
- lightgoldenrodyellow: 0xfafad2,
- lightgray: 0xd3d3d3,
- lightgreen: 0x90ee90,
- lightgrey: 0xd3d3d3,
- lightpink: 0xffb6c1,
- lightsalmon: 0xffa07a,
- lightseagreen: 0x20b2aa,
- lightskyblue: 0x87cefa,
- lightslategray: 0x778899,
- lightslategrey: 0x778899,
- lightsteelblue: 0xb0c4de,
- lightyellow: 0xffffe0,
- lime: 0x00ff00,
- limegreen: 0x32cd32,
- linen: 0xfaf0e6,
- magenta: 0xff00ff,
- maroon: 0x800000,
- mediumaquamarine: 0x66cdaa,
- mediumblue: 0x0000cd,
- mediumorchid: 0xba55d3,
- mediumpurple: 0x9370db,
- mediumseagreen: 0x3cb371,
- mediumslateblue: 0x7b68ee,
- mediumspringgreen: 0x00fa9a,
- mediumturquoise: 0x48d1cc,
- mediumvioletred: 0xc71585,
- midnightblue: 0x191970,
- mintcream: 0xf5fffa,
- mistyrose: 0xffe4e1,
- moccasin: 0xffe4b5,
- navajowhite: 0xffdead,
- navy: 0x000080,
- oldlace: 0xfdf5e6,
- olive: 0x808000,
- olivedrab: 0x6b8e23,
- orange: 0xffa500,
- orangered: 0xff4500,
- orchid: 0xda70d6,
- palegoldenrod: 0xeee8aa,
- palegreen: 0x98fb98,
- paleturquoise: 0xafeeee,
- palevioletred: 0xdb7093,
- papayawhip: 0xffefd5,
- peachpuff: 0xffdab9,
- peru: 0xcd853f,
- pink: 0xffc0cb,
- plum: 0xdda0dd,
- powderblue: 0xb0e0e6,
- purple: 0x800080,
- rebeccapurple: 0x663399,
- red: 0xff0000,
- rosybrown: 0xbc8f8f,
- royalblue: 0x4169e1,
- saddlebrown: 0x8b4513,
- salmon: 0xfa8072,
- sandybrown: 0xf4a460,
- seagreen: 0x2e8b57,
- seashell: 0xfff5ee,
- sienna: 0xa0522d,
- silver: 0xc0c0c0,
- skyblue: 0x87ceeb,
- slateblue: 0x6a5acd,
- slategray: 0x708090,
- slategrey: 0x708090,
- snow: 0xfffafa,
- springgreen: 0x00ff7f,
- steelblue: 0x4682b4,
- tan: 0xd2b48c,
- teal: 0x008080,
- thistle: 0xd8bfd8,
- tomato: 0xff6347,
- turquoise: 0x40e0d0,
- violet: 0xee82ee,
- wheat: 0xf5deb3,
- white: 0xffffff,
- whitesmoke: 0xf5f5f5,
- yellow: 0xffff00,
- yellowgreen: 0x9acd32
- };
- define(Color, color, {
- copy: function(channels) {
- return Object.assign(new this.constructor, this, channels);
- },
- displayable: function() {
- return this.rgb().displayable();
- },
- hex: color_formatHex, // Deprecated! Use color.formatHex.
- formatHex: color_formatHex,
- formatHsl: color_formatHsl,
- formatRgb: color_formatRgb,
- toString: color_formatRgb
- });
- function color_formatHex() {
- return this.rgb().formatHex();
- }
- function color_formatHsl() {
- return hslConvert(this).formatHsl();
- }
- function color_formatRgb() {
- return this.rgb().formatRgb();
- }
- function color(format) {
- var m, l;
- format = (format + "").trim().toLowerCase();
- return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
- : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
- : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
- : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
- : null) // invalid hex
- : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
- : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
- : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
- : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
- : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
- : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
- : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
- : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
- : null;
- }
- function rgbn(n) {
- return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
- }
- function rgba(r, g, b, a) {
- if (a <= 0) r = g = b = NaN;
- return new Rgb(r, g, b, a);
- }
- function rgbConvert(o) {
- if (!(o instanceof Color)) o = color(o);
- if (!o) return new Rgb;
- o = o.rgb();
- return new Rgb(o.r, o.g, o.b, o.opacity);
- }
- function rgb(r, g, b, opacity) {
- return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
- }
- function Rgb(r, g, b, opacity) {
- this.r = +r;
- this.g = +g;
- this.b = +b;
- this.opacity = +opacity;
- }
- define(Rgb, rgb, extend(Color, {
- brighter: function(k) {
- k = k == null ? brighter : Math.pow(brighter, k);
- return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
- },
- darker: function(k) {
- k = k == null ? darker : Math.pow(darker, k);
- return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
- },
- rgb: function() {
- return this;
- },
- displayable: function() {
- return (-0.5 <= this.r && this.r < 255.5)
- && (-0.5 <= this.g && this.g < 255.5)
- && (-0.5 <= this.b && this.b < 255.5)
- && (0 <= this.opacity && this.opacity <= 1);
- },
- hex: rgb_formatHex, // Deprecated! Use color.formatHex.
- formatHex: rgb_formatHex,
- formatRgb: rgb_formatRgb,
- toString: rgb_formatRgb
- }));
- function rgb_formatHex() {
- return "#" + hex(this.r) + hex(this.g) + hex(this.b);
- }
- function rgb_formatRgb() {
- var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
- return (a === 1 ? "rgb(" : "rgba(")
- + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
- + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
- + Math.max(0, Math.min(255, Math.round(this.b) || 0))
- + (a === 1 ? ")" : ", " + a + ")");
- }
- function hex(value) {
- value = Math.max(0, Math.min(255, Math.round(value) || 0));
- return (value < 16 ? "0" : "") + value.toString(16);
- }
- function hsla(h, s, l, a) {
- if (a <= 0) h = s = l = NaN;
- else if (l <= 0 || l >= 1) h = s = NaN;
- else if (s <= 0) h = NaN;
- return new Hsl(h, s, l, a);
- }
- function hslConvert(o) {
- if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
- if (!(o instanceof Color)) o = color(o);
- if (!o) return new Hsl;
- if (o instanceof Hsl) return o;
- o = o.rgb();
- var r = o.r / 255,
- g = o.g / 255,
- b = o.b / 255,
- min = Math.min(r, g, b),
- max = Math.max(r, g, b),
- h = NaN,
- s = max - min,
- l = (max + min) / 2;
- if (s) {
- if (r === max) h = (g - b) / s + (g < b) * 6;
- else if (g === max) h = (b - r) / s + 2;
- else h = (r - g) / s + 4;
- s /= l < 0.5 ? max + min : 2 - max - min;
- h *= 60;
- } else {
- s = l > 0 && l < 1 ? 0 : h;
- }
- return new Hsl(h, s, l, o.opacity);
- }
- function hsl(h, s, l, opacity) {
- return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
- }
- function Hsl(h, s, l, opacity) {
- this.h = +h;
- this.s = +s;
- this.l = +l;
- this.opacity = +opacity;
- }
- define(Hsl, hsl, extend(Color, {
- brighter: function(k) {
- k = k == null ? brighter : Math.pow(brighter, k);
- return new Hsl(this.h, this.s, this.l * k, this.opacity);
- },
- darker: function(k) {
- k = k == null ? darker : Math.pow(darker, k);
- return new Hsl(this.h, this.s, this.l * k, this.opacity);
- },
- rgb: function() {
- var h = this.h % 360 + (this.h < 0) * 360,
- s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
- l = this.l,
- m2 = l + (l < 0.5 ? l : 1 - l) * s,
- m1 = 2 * l - m2;
- return new Rgb(
- hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
- hsl2rgb(h, m1, m2),
- hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
- this.opacity
- );
- },
- displayable: function() {
- return (0 <= this.s && this.s <= 1 || isNaN(this.s))
- && (0 <= this.l && this.l <= 1)
- && (0 <= this.opacity && this.opacity <= 1);
- },
- formatHsl: function() {
- var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
- return (a === 1 ? "hsl(" : "hsla(")
- + (this.h || 0) + ", "
- + (this.s || 0) * 100 + "%, "
- + (this.l || 0) * 100 + "%"
- + (a === 1 ? ")" : ", " + a + ")");
- }
- }));
- /* From FvD 13.37, CSS Color Module Level 3 */
- function hsl2rgb(h, m1, m2) {
- return (h < 60 ? m1 + (m2 - m1) * h / 60
- : h < 180 ? m2
- : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
- : m1) * 255;
- }
- /**
- * 两点之间的距离
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {number} 距离
- */
- function distance$1(x1, y1, x2, y2) {
- var dx = x1 - x2;
- var dy = y1 - y2;
- return Math.sqrt(dx * dx + dy * dy);
- }
- function isNumberEqual$1(v1, v2) {
- return Math.abs(v1 - v2) < 0.001;
- }
- function getBBoxByArray(xArr, yArr) {
- var minX = Math.min.apply(Math, xArr);
- var minY = Math.min.apply(Math, yArr);
- var maxX = Math.max.apply(Math, xArr);
- var maxY = Math.max.apply(Math, yArr);
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- }
- function piMod(angle) {
- return (angle + Math.PI * 2) % (Math.PI * 2);
- }
- var line = {
- /**
- * 计算线段的包围盒
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {object} 包围盒对象
- */
- box: function box(x1, y1, x2, y2) {
- return getBBoxByArray([x1, x2], [y1, y2]);
- },
- /**
- * 线段的长度
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {number} 距离
- */
- length: function length(x1, y1, x2, y2) {
- return distance$1(x1, y1, x2, y2);
- },
- /**
- * 根据比例获取点
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @param {number} t 指定比例
- * @return {object} 包含 x, y 的点
- */
- pointAt: function pointAt(x1, y1, x2, y2, t) {
- return {
- x: (1 - t) * x1 + t * x2,
- y: (1 - t) * y1 + t * y2
- };
- },
- /**
- * 点到线段的距离
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @param {number} x 测试点 x
- * @param {number} y 测试点 y
- * @return {number} 距离
- */
- pointDistance: function pointDistance(x1, y1, x2, y2, x, y) {
- // 投影距离 x1, y1 的向量,假设 p, p1, p2 三个点,投影点为 a
- // p1a = p1p.p1p2/|p1p2| * (p1p 的单位向量)
- var cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
- if (cross < 0) {
- return distance$1(x1, y1, x, y);
- }
- var lengthSquare = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
- if (cross > lengthSquare) {
- return distance$1(x2, y2, x, y);
- }
- return this.pointToLine(x1, y1, x2, y2, x, y);
- },
- /**
- * 点到直线的距离,而不是点到线段的距离
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @param {number} x 测试点 x
- * @param {number} y 测试点 y
- * @return {number} 距离
- */
- pointToLine: function pointToLine(x1, y1, x2, y2, x, y) {
- var d = [x2 - x1, y2 - y1];
- // 如果端点相等,则判定点到点的距离
- if (exactEquals$1(d, [0, 0])) {
- return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
- }
- var u = [-d[1], d[0]];
- normalize$3(u, u);
- var a = [x - x1, y - y1];
- return Math.abs(dot$1(a, u));
- },
- /**
- * 线段的角度
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {number} 导数
- */
- tangentAngle: function tangentAngle(x1, y1, x2, y2) {
- return Math.atan2(y2 - y1, x2 - x1);
- }
- };
- var EPSILON$1 = 0.0001;
- /**
- * 使用牛顿切割法求最近的点
- * @param {number[]} xArr 点的 x 数组
- * @param {number[]} yArr 点的 y 数组
- * @param {number} x 指定的点 x
- * @param {number} y 指定的点 y
- * @param {Function} tCallback 差值函数
- */
- function nearestPoint(xArr, yArr, x, y, tCallback, length) {
- var t = -1;
- var d = Infinity;
- var v0 = [x, y];
- var segNum = 20;
- if (length && length > 200) {
- segNum = length / 10;
- }
- var increaseRate = 1 / segNum;
- var interval = increaseRate / 10;
- for (var i = 0; i <= segNum; i++) {
- var _t = i * increaseRate;
- var v1 = [tCallback.apply(void 0, xArr.concat([_t])), tCallback.apply(void 0, yArr.concat([_t]))];
- var d1 = distance$1(v0[0], v0[1], v1[0], v1[1]);
- if (d1 < d) {
- t = _t;
- d = d1;
- }
- }
- // 提前终止
- if (t === 0) {
- return {
- x: xArr[0],
- y: yArr[0]
- };
- }
- if (t === 1) {
- var count = xArr.length;
- return {
- x: xArr[count - 1],
- y: yArr[count - 1]
- };
- }
- d = Infinity;
- for (var _i = 0; _i < 32; _i++) {
- if (interval < EPSILON$1) {
- break;
- }
- var prev = t - interval;
- var next = t + interval;
- var _v = [tCallback.apply(void 0, xArr.concat([prev])), tCallback.apply(void 0, yArr.concat([prev]))];
- var _d = distance$1(v0[0], v0[1], _v[0], _v[1]);
- if (prev >= 0 && _d < d) {
- t = prev;
- d = _d;
- } else {
- var v2 = [tCallback.apply(void 0, xArr.concat([next])), tCallback.apply(void 0, yArr.concat([next]))];
- var d2 = distance$1(v0[0], v0[1], v2[0], v2[1]);
- if (next <= 1 && d2 < d) {
- t = next;
- d = d2;
- } else {
- interval *= 0.5;
- }
- }
- }
- return {
- x: tCallback.apply(void 0, xArr.concat([t])),
- y: tCallback.apply(void 0, yArr.concat([t]))
- };
- }
- // 近似求解 https://community.khronos.org/t/3d-cubic-bezier-segment-length/62363/2
- function snapLength(xArr, yArr) {
- var totalLength = 0;
- var count = xArr.length;
- for (var i = 0; i < count; i++) {
- var x = xArr[i];
- var y = yArr[i];
- var nextX = xArr[(i + 1) % count];
- var nextY = yArr[(i + 1) % count];
- totalLength += distance$1(x, y, nextX, nextY);
- }
- return totalLength / 2;
- }
- // 差值公式
- function quadraticAt(p0, p1, p2, t) {
- var onet = 1 - t;
- return onet * onet * p0 + 2 * t * onet * p1 + t * t * p2;
- }
- // 求极值
- function extrema(p0, p1, p2) {
- var a = p0 + p2 - 2 * p1;
- if (isNumberEqual$1(a, 0)) {
- return [0.5];
- }
- var rst = (p0 - p1) / a;
- if (rst <= 1 && rst >= 0) {
- return [rst];
- }
- return [];
- }
- function derivativeAt(p0, p1, p2, t) {
- return 2 * (1 - t) * (p1 - p0) + 2 * t * (p2 - p1);
- }
- // 分割贝塞尔曲线
- function divideQuadratic(x1, y1, x2, y2, x3, y3, t) {
- // 划分点
- var xt = quadraticAt(x1, x2, x3, t);
- var yt = quadraticAt(y1, y2, y3, t);
- // 分割的第一条曲线的控制点
- var controlPoint1 = line.pointAt(x1, y1, x2, y2, t);
- // 分割的第二条曲线的控制点
- var controlPoint2 = line.pointAt(x2, y2, x3, y3, t);
- return [[x1, y1, controlPoint1.x, controlPoint1.y, xt, yt], [xt, yt, controlPoint2.x, controlPoint2.y, x3, y3]];
- }
- // 使用迭代法取贝塞尔曲线的长度
- function quadraticLength(x1, y1, x2, y2, x3, y3, iterationCount) {
- if (iterationCount === 0) {
- return (distance$1(x1, y1, x2, y2) + distance$1(x2, y2, x3, y3) + distance$1(x1, y1, x3, y3)) / 2;
- }
- var quadratics = divideQuadratic(x1, y1, x2, y2, x3, y3, 0.5);
- var left = quadratics[0];
- var right = quadratics[1];
- left.push(iterationCount - 1);
- right.push(iterationCount - 1);
- return quadraticLength.apply(void 0, left) + quadraticLength.apply(void 0, right);
- }
- var quadratic = {
- box: function box(x1, y1, x2, y2, x3, y3) {
- var xExtrema = extrema(x1, x2, x3)[0];
- var yExtrema = extrema(y1, y2, y3)[0];
- // 控制点不加入 box 的计算
- var xArr = [x1, x3];
- var yArr = [y1, y3];
- if (xExtrema !== undefined) {
- xArr.push(quadraticAt(x1, x2, x3, xExtrema));
- }
- if (yExtrema !== undefined) {
- yArr.push(quadraticAt(y1, y2, y3, yExtrema));
- }
- return getBBoxByArray(xArr, yArr);
- },
- length: function length(x1, y1, x2, y2, x3, y3) {
- return quadraticLength(x1, y1, x2, y2, x3, y3, 3);
- },
- nearestPoint: function nearestPoint$1(x1, y1, x2, y2, x3, y3, x0, y0) {
- return nearestPoint([x1, x2, x3], [y1, y2, y3], x0, y0, quadraticAt);
- },
- pointDistance: function pointDistance(x1, y1, x2, y2, x3, y3, x0, y0) {
- var point = this.nearestPoint(x1, y1, x2, y2, x3, y3, x0, y0);
- return distance$1(point.x, point.y, x0, y0);
- },
- interpolationAt: quadraticAt,
- pointAt: function pointAt(x1, y1, x2, y2, x3, y3, t) {
- return {
- x: quadraticAt(x1, x2, x3, t),
- y: quadraticAt(y1, y2, y3, t)
- };
- },
- divide: function divide(x1, y1, x2, y2, x3, y3, t) {
- return divideQuadratic(x1, y1, x2, y2, x3, y3, t);
- },
- tangentAngle: function tangentAngle(x1, y1, x2, y2, x3, y3, t) {
- var dx = derivativeAt(x1, x2, x3, t);
- var dy = derivativeAt(y1, y2, y3, t);
- var angle = Math.atan2(dy, dx);
- return piMod(angle);
- }
- };
- function cubicAt(p0, p1, p2, p3, t) {
- var onet = 1 - t; // t * t * t 的性能大概是 Math.pow(t, 3) 的三倍
- return onet * onet * onet * p0 + 3 * p1 * t * onet * onet + 3 * p2 * t * t * onet + p3 * t * t * t;
- }
- function derivativeAt$1(p0, p1, p2, p3, t) {
- var onet = 1 - t;
- return 3 * (onet * onet * (p1 - p0) + 2 * onet * t * (p2 - p1) + t * t * (p3 - p2));
- }
- function extrema$1(p0, p1, p2, p3) {
- var a = -3 * p0 + 9 * p1 - 9 * p2 + 3 * p3;
- var b = 6 * p0 - 12 * p1 + 6 * p2;
- var c = 3 * p1 - 3 * p0;
- var extremas = [];
- var t1;
- var t2;
- var discSqrt;
- if (isNumberEqual$1(a, 0)) {
- if (!isNumberEqual$1(b, 0)) {
- t1 = -c / b;
- if (t1 >= 0 && t1 <= 1) {
- extremas.push(t1);
- }
- }
- } else {
- var disc = b * b - 4 * a * c;
- if (isNumberEqual$1(disc, 0)) {
- extremas.push(-b / (2 * a));
- } else if (disc > 0) {
- discSqrt = Math.sqrt(disc);
- t1 = (-b + discSqrt) / (2 * a);
- t2 = (-b - discSqrt) / (2 * a);
- if (t1 >= 0 && t1 <= 1) {
- extremas.push(t1);
- }
- if (t2 >= 0 && t2 <= 1) {
- extremas.push(t2);
- }
- }
- }
- return extremas;
- }
- // 分割贝塞尔曲线
- function divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- // 划分点
- var xt = cubicAt(x1, x2, x3, x4, t);
- var yt = cubicAt(y1, y2, y3, y4, t);
- // 计算两点之间的差值点
- var c1 = line.pointAt(x1, y1, x2, y2, t);
- var c2 = line.pointAt(x2, y2, x3, y3, t);
- var c3 = line.pointAt(x3, y3, x4, y4, t);
- var c12 = line.pointAt(c1.x, c1.y, c2.x, c2.y, t);
- var c23 = line.pointAt(c2.x, c2.y, c3.x, c3.y, t);
- return [[x1, y1, c1.x, c1.y, c12.x, c12.y, xt, yt], [xt, yt, c23.x, c23.y, c3.x, c3.y, x4, y4]];
- }
- // 使用迭代法取贝塞尔曲线的长度,二阶和三阶分开写,更清晰和便于调试
- function cubicLength(x1, y1, x2, y2, x3, y3, x4, y4, iterationCount) {
- if (iterationCount === 0) {
- return snapLength([x1, x2, x3, x4], [y1, y2, y3, y4]);
- }
- var cubics = divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, 0.5);
- var left = [].concat(cubics[0], [iterationCount - 1]);
- var right = [].concat(cubics[1], [iterationCount - 1]);
- return cubicLength.apply(void 0, left) + cubicLength.apply(void 0, right);
- }
- var cubic = {
- extrema: extrema$1,
- box: function box(x1, y1, x2, y2, x3, y3, x4, y4) {
- var xArr = [x1, x4];
- var yArr = [y1, y4];
- var xExtrema = extrema$1(x1, x2, x3, x4);
- var yExtrema = extrema$1(y1, y2, y3, y4);
- for (var i = 0; i < xExtrema.length; i++) {
- xArr.push(cubicAt(x1, x2, x3, x4, xExtrema[i]));
- }
- for (var _i = 0; _i < yExtrema.length; _i++) {
- yArr.push(cubicAt(y1, y2, y3, y4, yExtrema[_i]));
- }
- return getBBoxByArray(xArr, yArr);
- },
- length: function length(x1, y1, x2, y2, x3, y3, x4, y4) {
- // 迭代三次,划分成 8 段求长度
- return cubicLength(x1, y1, x2, y2, x3, y3, x4, y4, 3);
- },
- nearestPoint: function nearestPoint$1(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length) {
- return nearestPoint([x1, x2, x3, x4], [y1, y2, y3, y4], x0, y0, cubicAt, length);
- },
- pointDistance: function pointDistance(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length) {
- var point = this.nearestPoint(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length);
- return distance$1(point.x, point.y, x0, y0);
- },
- interpolationAt: cubicAt,
- pointAt: function pointAt(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- return {
- x: cubicAt(x1, x2, x3, x4, t),
- y: cubicAt(y1, y2, y3, y4, t)
- };
- },
- divide: function divide(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- return divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, t);
- },
- tangentAngle: function tangentAngle(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- var dx = derivativeAt$1(x1, x2, x3, x4, t);
- var dy = derivativeAt$1(y1, y2, y3, y4, t);
- return piMod(Math.atan2(dy, dx));
- }
- };
- /**
- * @fileoverview 椭圆的一些计算,
- * - 周长计算参考:https://www.mathsisfun.com/geometry/ellipse-perimeter.html
- * - 距离计算参考:https://wet-robots.ghost.io/simple-method-for-distance-to-ellipse/
- * @author dxq613@gmail.com
- */
- function copysign(v1, v2) {
- var absv = Math.abs(v1);
- return v2 > 0 ? absv : absv * -1;
- }
- var ellipse = {
- /**
- * 包围盒计算
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @return {object} 包围盒
- */
- box: function box(x, y, rx, ry) {
- return {
- x: x - rx,
- y: y - ry,
- width: rx * 2,
- height: ry * 2
- };
- },
- /**
- * 计算周长,使用近似法
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @return {number} 椭圆周长
- */
- length: function length(x, y, rx, ry) {
- return Math.PI * (3 * (rx + ry) - Math.sqrt((3 * rx + ry) * (rx + 3 * ry)));
- },
- /**
- * 距离椭圆最近的点
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} x0 指定的点 x
- * @param {number} y0 指定的点 y
- * @return {object} 椭圆上距离指定点最近的点
- */
- nearestPoint: function nearestPoint(x, y, rx, ry, x0, y0) {
- var a = rx;
- var b = ry;
- // 假如椭圆半径为0则返回圆心
- if (a === 0 || b === 0) {
- return {
- x: x,
- y: y
- };
- }
- // 转换成 0, 0 为中心的椭圆计算
- var relativeX = x0 - x;
- var relativeY = y0 - y;
- var px = Math.abs(relativeX);
- var py = Math.abs(relativeY);
- var squareA = a * a;
- var squareB = b * b;
- // const angle0 = Math.atan2(relativeY, relativeX);
- var t = Math.PI / 4;
- var nearestX = 0; // 椭圆上的任一点
- var nearestY = 0;
- // 迭代 4 次
- for (var i = 0; i < 4; i++) {
- nearestX = a * Math.cos(t);
- nearestY = b * Math.sin(t);
- var ex = (squareA - squareB) * Math.pow(Math.cos(t), 3) / a;
- var ey = (squareB - squareA) * Math.pow(Math.sin(t), 3) / b;
- var rx1 = nearestX - ex;
- var ry1 = nearestY - ey;
- var qx = px - ex;
- var qy = py - ey;
- var r = Math.hypot(ry1, rx1);
- var q = Math.hypot(qy, qx);
- var delta_c = r * Math.asin((rx1 * qy - ry1 * qx) / (r * q));
- var delta_t = delta_c / Math.sqrt(squareA + squareB - nearestX * nearestX - nearestY * nearestY);
- t += delta_t;
- t = Math.min(Math.PI / 2, Math.max(0, t));
- }
- return {
- x: x + copysign(nearestX, relativeX),
- y: y + copysign(nearestY, relativeY)
- };
- },
- /**
- * 点到椭圆最近的距离
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} x0 指定的点 x
- * @param {number} y0 指定的点 y
- * @return {number} 点到椭圆的距离
- */
- pointDistance: function pointDistance(x, y, rx, ry, x0, y0) {
- var nearestPoint = this.nearestPoint(x, y, rx, ry, x0, y0);
- return distance$1(nearestPoint.x, nearestPoint.y, x0, y0);
- },
- /**
- * 根据比例获取点
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} t 指定比例,x轴方向为 0
- * @return {object} 点
- */
- pointAt: function pointAt(x, y, rx, ry, t) {
- var angle = 2 * Math.PI * t; // 按照角度进行计算,而不按照周长计算
- return {
- x: x + rx * Math.cos(angle),
- y: y + ry * Math.sin(angle)
- };
- },
- /**
- * 根据比例计算切线角度
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} t 指定比例 0 - 1 之间,x轴方向为 0。在 0-1 范围之外是循环还是返回 null,还需要调整
- * @return {number} 角度,在 0 - 2PI 之间
- */
- tangentAngle: function tangentAngle(x, y, rx, ry, t) {
- var angle = 2 * Math.PI * t; // 按照角度进行计算,而不按照周长计算
- // 直接使用 x,y 的导数计算, x' = -rx * sin(t); y' = ry * cos(t);
- var tangentAngle = Math.atan2(ry * Math.cos(angle), -rx * Math.sin(angle));
- // 也可以使用指定点的切线方程计算,成本有些高
- // const point = this.pointAt(0, 0, rx, ry, t); // 椭圆的切线同椭圆的中心不相关
- // let tangentAngle = -1 * Math.atan((ry * ry * point.x) / (rx * rx * point.y));
- // if (angle >= 0 && angle <= Math.PI) {
- // tangentAngle += Math.PI;
- // }
- return piMod(tangentAngle);
- }
- };
- // 偏导数 x
- function derivativeXAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle) {
- return -1 * rx * Math.cos(xRotation) * Math.sin(angle) - ry * Math.sin(xRotation) * Math.cos(angle);
- }
- // 偏导数 y
- function derivativeYAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle) {
- return -1 * rx * Math.sin(xRotation) * Math.sin(angle) + ry * Math.cos(xRotation) * Math.cos(angle);
- }
- // x 的极值
- function xExtrema(rx, ry, xRotation) {
- return Math.atan(-ry / rx * Math.tan(xRotation));
- }
- // y 的极值
- function yExtrema(rx, ry, xRotation) {
- return Math.atan(ry / (rx * Math.tan(xRotation)));
- }
- // 根据角度求 x 坐标
- function xAt(cx, cy, rx, ry, xRotation, angle) {
- return rx * Math.cos(xRotation) * Math.cos(angle) - ry * Math.sin(xRotation) * Math.sin(angle) + cx;
- }
- // 根据角度求 y 坐标
- function yAt(cx, cy, rx, ry, xRotation, angle) {
- return rx * Math.sin(xRotation) * Math.cos(angle) + ry * Math.cos(xRotation) * Math.sin(angle) + cy;
- }
- // 获取点在椭圆上的角度
- function getAngle(rx, ry, x0, y0) {
- var angle = Math.atan2(y0 * rx, x0 * ry);
- // 转换到 0 - 2PI 内
- return (angle + Math.PI * 2) % (Math.PI * 2);
- }
- // 根据角度获取,x,y
- function getPoint(rx, ry, angle) {
- return {
- x: rx * Math.cos(angle),
- y: ry * Math.sin(angle)
- };
- }
- // 旋转
- function rotate$1(x, y, angle) {
- var cos = Math.cos(angle);
- var sin = Math.sin(angle);
- return [x * cos - y * sin, x * sin + y * cos];
- }
- var arc = {
- /**
- * 计算包围盒
- * @param {number} cx 圆心 x
- * @param {number} cy 圆心 y
- * @param {number} rx x 轴方向的半径
- * @param {number} ry y 轴方向的半径
- * @param {number} xRotation 旋转角度
- * @param {number} startAngle 起始角度
- * @param {number} endAngle 结束角度
- * @return {object} 包围盒对象
- */
- box: function box(cx, cy, rx, ry, xRotation, startAngle, endAngle) {
- var xDim = xExtrema(rx, ry, xRotation);
- var minX = Infinity;
- var maxX = -Infinity;
- var xs = [startAngle, endAngle];
- for (var i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) {
- var xAngle = xDim + i;
- if (startAngle < endAngle) {
- if (startAngle < xAngle && xAngle < endAngle) {
- xs.push(xAngle);
- }
- } else {
- if (endAngle < xAngle && xAngle < startAngle) {
- xs.push(xAngle);
- }
- }
- }
- for (var _i = 0; _i < xs.length; _i++) {
- var x = xAt(cx, cy, rx, ry, xRotation, xs[_i]);
- if (x < minX) {
- minX = x;
- }
- if (x > maxX) {
- maxX = x;
- }
- }
- var yDim = yExtrema(rx, ry, xRotation);
- var minY = Infinity;
- var maxY = -Infinity;
- var ys = [startAngle, endAngle];
- for (var _i2 = -Math.PI * 2; _i2 <= Math.PI * 2; _i2 += Math.PI) {
- var yAngle = yDim + _i2;
- if (startAngle < endAngle) {
- if (startAngle < yAngle && yAngle < endAngle) {
- ys.push(yAngle);
- }
- } else {
- if (endAngle < yAngle && yAngle < startAngle) {
- ys.push(yAngle);
- }
- }
- }
- for (var _i3 = 0; _i3 < ys.length; _i3++) {
- var y = yAt(cx, cy, rx, ry, xRotation, ys[_i3]);
- if (y < minY) {
- minY = y;
- }
- if (y > maxY) {
- maxY = y;
- }
- }
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- },
- /**
- * 获取圆弧的长度,计算圆弧长度时不考虑旋转角度,
- * 仅跟 rx, ry, startAngle, endAngle 相关
- * @param {number} cx 圆心 x
- * @param {number} cy 圆心 y
- * @param {number} rx x 轴方向的半径
- * @param {number} ry y 轴方向的半径
- * @param {number} xRotation 旋转角度
- * @param {number} startAngle 起始角度
- * @param {number} endAngle 结束角度
- */
- length: function length(cx, cy, rx, ry, xRotation, startAngle, endAngle) {},
- /**
- * 获取指定点到圆弧的最近距离的点
- * @param {number} cx 圆心 x
- * @param {number} cy 圆心 y
- * @param {number} rx x 轴方向的半径
- * @param {number} ry y 轴方向的半径
- * @param {number} xRotation 旋转角度
- * @param {number} startAngle 起始角度
- * @param {number} endAngle 结束角度
- * @param {number} x0 指定点的 x
- * @param {number} y0 指定点的 y
- * @return {object} 到指定点最近距离的点
- */
- nearestPoint: function nearestPoint(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0) {
- // 将最近距离问题转换成到椭圆中心 0,0 没有旋转的椭圆问题
- var relativeVector = rotate$1(x0 - cx, y0 - cy, -xRotation);
- var x1 = relativeVector[0],
- y1 = relativeVector[1];
- // 计算点到椭圆的最近的点
- var relativePoint = ellipse.nearestPoint(0, 0, rx, ry, x1, y1);
- // 获取点在椭圆上的角度
- var angle = getAngle(rx, ry, relativePoint.x, relativePoint.y);
- // 点没有在圆弧上
- if (angle < startAngle) {
- // 小于起始圆弧
- relativePoint = getPoint(rx, ry, startAngle);
- } else if (angle > endAngle) {
- // 大于结束圆弧
- relativePoint = getPoint(rx, ry, endAngle);
- }
- // 旋转到 xRotation 的角度
- var vector = rotate$1(relativePoint.x, relativePoint.y, xRotation);
- return {
- x: vector[0] + cx,
- y: vector[1] + cy
- };
- },
- pointDistance: function pointDistance(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0) {
- var nearestPoint = this.nearestPoint(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0);
- return distance$1(nearestPoint.x, nearestPoint.y, x0, y0);
- },
- pointAt: function pointAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, t) {
- var angle = (endAngle - startAngle) * t + startAngle;
- return {
- x: xAt(cx, cy, rx, ry, xRotation, angle),
- y: yAt(cx, cy, rx, ry, xRotation, angle)
- };
- },
- tangentAngle: function tangentAngle(cx, cy, rx, ry, xRotation, startAngle, endAngle, t) {
- var angle = (endAngle - startAngle) * t + startAngle;
- var dx = derivativeXAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle);
- var dy = derivativeYAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle);
- return piMod(Math.atan2(dy, dx));
- }
- };
- function analyzePoints(points) {
- // 计算每段的长度和总的长度
- var totalLength = 0;
- var segments = [];
- for (var i = 0; i < points.length - 1; i++) {
- var from = points[i];
- var to = points[i + 1];
- var length = distance$1(from[0], from[1], to[0], to[1]);
- var seg = {
- from: from,
- to: to,
- length: length
- };
- segments.push(seg);
- totalLength += length;
- }
- return {
- segments: segments,
- totalLength: totalLength
- };
- }
- function lengthOfSegment(points) {
- if (points.length < 2) {
- return 0;
- }
- var totalLength = 0;
- for (var i = 0; i < points.length - 1; i++) {
- var from = points[i];
- var to = points[i + 1];
- totalLength += distance$1(from[0], from[1], to[0], to[1]);
- }
- return totalLength;
- }
- /**
- * 按照比例在数据片段中获取点
- * @param {array} points 点的集合
- * @param {number} t 百分比 0-1
- * @return {object} 点的坐标
- */
- function pointAtSegments(points, t) {
- // 边界判断
- if (t > 1 || t < 0 || points.length < 2) {
- return null;
- }
- var _analyzePoints = analyzePoints(points),
- segments = _analyzePoints.segments,
- totalLength = _analyzePoints.totalLength;
- // 多个点有可能重合
- if (totalLength === 0) {
- return {
- x: points[0][0],
- y: points[0][1]
- };
- }
- // 计算比例
- var startRatio = 0;
- var point = null;
- for (var i = 0; i < segments.length; i++) {
- var seg = segments[i];
- var from = seg.from,
- to = seg.to;
- var currentRatio = seg.length / totalLength;
- if (t >= startRatio && t <= startRatio + currentRatio) {
- var localRatio = (t - startRatio) / currentRatio;
- point = line.pointAt(from[0], from[1], to[0], to[1], localRatio);
- break;
- }
- startRatio += currentRatio;
- }
- return point;
- }
- /**
- * 按照比例在数据片段中获取切线的角度
- * @param {array} points 点的集合
- * @param {number} t 百分比 0-1
- */
- function angleAtSegments(points, t) {
- // 边界判断
- if (t > 1 || t < 0 || points.length < 2) {
- return 0;
- }
- var _analyzePoints2 = analyzePoints(points),
- segments = _analyzePoints2.segments,
- totalLength = _analyzePoints2.totalLength;
- // 计算比例
- var startRatio = 0;
- var angle = 0;
- for (var i = 0; i < segments.length; i++) {
- var seg = segments[i];
- var from = seg.from,
- to = seg.to;
- var currentRatio = seg.length / totalLength;
- if (t >= startRatio && t <= startRatio + currentRatio) {
- angle = Math.atan2(to[1] - from[1], to[0] - from[0]);
- break;
- }
- startRatio += currentRatio;
- }
- return angle;
- }
- function distanceAtSegment(points, x, y) {
- var minDistance = Infinity;
- for (var i = 0; i < points.length - 1; i++) {
- var point = points[i];
- var nextPoint = points[i + 1];
- var _distance = line.pointDistance(point[0], point[1], nextPoint[0], nextPoint[1], x, y);
- if (_distance < minDistance) {
- minDistance = _distance;
- }
- }
- return minDistance;
- }
- var polyline = {
- /**
- * 计算多折线的包围盒
- * @param {array} points 点的集合 [x,y] 的形式
- * @return {object} 包围盒
- */
- box: function box(points) {
- var xArr = [];
- var yArr = [];
- for (var i = 0; i < points.length; i++) {
- var point = points[i];
- xArr.push(point[0]);
- yArr.push(point[1]);
- }
- return getBBoxByArray(xArr, yArr);
- },
- /**
- * 计算多折线的长度
- * @param {array} points 点的集合 [x,y] 的形式
- * @return {object} 多条边的长度
- */
- length: function length(points) {
- return lengthOfSegment(points);
- },
- /**
- * 根据比例获取多折线的点
- * @param {array} points 点的集合 [x,y] 的形式
- * @param {number} t 在多折线的长度上的比例
- * @return {object} 根据比例值计算出来的点
- */
- pointAt: function pointAt(points, t) {
- return pointAtSegments(points, t);
- },
- /**
- * 指定点到多折线的距离
- * @param {array} points 点的集合 [x,y] 的形式
- * @param {number} x 指定点的 x
- * @param {number} y 指定点的 y
- * @return {number} 点到多折线的距离
- */
- pointDistance: function pointDistance(points, x, y) {
- return distanceAtSegment(points, x, y);
- },
- /**
- * 根据比例获取多折线的切线角度
- * @param {array} points 点的集合 [x,y] 的形式
- * @param {number} t 在多折线的长度上的比例
- * @return {object} 根据比例值计算出来的角度
- */
- tangentAngle: function tangentAngle(points, t) {
- return angleAtSegments(points, t);
- }
- };
- var eventemitter3 = createCommonjsModule(function (module) {
- var has = Object.prototype.hasOwnProperty
- , prefix = '~';
- /**
- * Constructor to create a storage for our `EE` objects.
- * An `Events` instance is a plain object whose properties are event names.
- *
- * @constructor
- * @private
- */
- function Events() {}
- //
- // We try to not inherit from `Object.prototype`. In some engines creating an
- // instance in this way is faster than calling `Object.create(null)` directly.
- // If `Object.create(null)` is not supported we prefix the event names with a
- // character to make sure that the built-in object properties are not
- // overridden or used as an attack vector.
- //
- if (Object.create) {
- Events.prototype = Object.create(null);
- //
- // This hack is needed because the `__proto__` property is still inherited in
- // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
- //
- if (!new Events().__proto__) prefix = false;
- }
- /**
- * Representation of a single event listener.
- *
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
- * @constructor
- * @private
- */
- function EE(fn, context, once) {
- this.fn = fn;
- this.context = context;
- this.once = once || false;
- }
- /**
- * Add a listener for a given event.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} once Specify if the listener is a one-time listener.
- * @returns {EventEmitter}
- * @private
- */
- function addListener(emitter, event, fn, context, once) {
- if (typeof fn !== 'function') {
- throw new TypeError('The listener must be a function');
- }
- var listener = new EE(fn, context || emitter, once)
- , evt = prefix ? prefix + event : event;
- if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
- else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
- else emitter._events[evt] = [emitter._events[evt], listener];
- return emitter;
- }
- /**
- * Clear event by name.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} evt The Event name.
- * @private
- */
- function clearEvent(emitter, evt) {
- if (--emitter._eventsCount === 0) emitter._events = new Events();
- else delete emitter._events[evt];
- }
- /**
- * Minimal `EventEmitter` interface that is molded against the Node.js
- * `EventEmitter` interface.
- *
- * @constructor
- * @public
- */
- function EventEmitter() {
- this._events = new Events();
- this._eventsCount = 0;
- }
- /**
- * Return an array listing the events for which the emitter has registered
- * listeners.
- *
- * @returns {Array}
- * @public
- */
- EventEmitter.prototype.eventNames = function eventNames() {
- var names = []
- , events
- , name;
- if (this._eventsCount === 0) return names;
- for (name in (events = this._events)) {
- if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
- }
- if (Object.getOwnPropertySymbols) {
- return names.concat(Object.getOwnPropertySymbols(events));
- }
- return names;
- };
- /**
- * Return the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Array} The registered listeners.
- * @public
- */
- EventEmitter.prototype.listeners = function listeners(event) {
- var evt = prefix ? prefix + event : event
- , handlers = this._events[evt];
- if (!handlers) return [];
- if (handlers.fn) return [handlers.fn];
- for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
- ee[i] = handlers[i].fn;
- }
- return ee;
- };
- /**
- * Return the number of listeners listening to a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Number} The number of listeners.
- * @public
- */
- EventEmitter.prototype.listenerCount = function listenerCount(event) {
- var evt = prefix ? prefix + event : event
- , listeners = this._events[evt];
- if (!listeners) return 0;
- if (listeners.fn) return 1;
- return listeners.length;
- };
- /**
- * Calls each of the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Boolean} `true` if the event had listeners, else `false`.
- * @public
- */
- EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
- var evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return false;
- var listeners = this._events[evt]
- , len = arguments.length
- , args
- , i;
- if (listeners.fn) {
- if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
- switch (len) {
- case 1: return listeners.fn.call(listeners.context), true;
- case 2: return listeners.fn.call(listeners.context, a1), true;
- case 3: return listeners.fn.call(listeners.context, a1, a2), true;
- case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
- case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
- case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
- }
- for (i = 1, args = new Array(len -1); i < len; i++) {
- args[i - 1] = arguments[i];
- }
- listeners.fn.apply(listeners.context, args);
- } else {
- var length = listeners.length
- , j;
- for (i = 0; i < length; i++) {
- if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
- switch (len) {
- case 1: listeners[i].fn.call(listeners[i].context); break;
- case 2: listeners[i].fn.call(listeners[i].context, a1); break;
- case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
- case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
- default:
- if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
- args[j - 1] = arguments[j];
- }
- listeners[i].fn.apply(listeners[i].context, args);
- }
- }
- }
- return true;
- };
- /**
- * Add a listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.on = function on(event, fn, context) {
- return addListener(this, event, fn, context, false);
- };
- /**
- * Add a one-time listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.once = function once(event, fn, context) {
- return addListener(this, event, fn, context, true);
- };
- /**
- * Remove the listeners of a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn Only remove the listeners that match this function.
- * @param {*} context Only remove the listeners that have this context.
- * @param {Boolean} once Only remove one-time listeners.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
- var evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return this;
- if (!fn) {
- clearEvent(this, evt);
- return this;
- }
- var listeners = this._events[evt];
- if (listeners.fn) {
- if (
- listeners.fn === fn &&
- (!once || listeners.once) &&
- (!context || listeners.context === context)
- ) {
- clearEvent(this, evt);
- }
- } else {
- for (var i = 0, events = [], length = listeners.length; i < length; i++) {
- if (
- listeners[i].fn !== fn ||
- (once && !listeners[i].once) ||
- (context && listeners[i].context !== context)
- ) {
- events.push(listeners[i]);
- }
- }
- //
- // Reset the array, or remove it completely if we have no more listeners.
- //
- if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
- else clearEvent(this, evt);
- }
- return this;
- };
- /**
- * Remove all listeners, or those of the specified event.
- *
- * @param {(String|Symbol)} [event] The event name.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
- var evt;
- if (event) {
- evt = prefix ? prefix + event : event;
- if (this._events[evt]) clearEvent(this, evt);
- } else {
- this._events = new Events();
- this._eventsCount = 0;
- }
- return this;
- };
- //
- // Alias methods names because people roll like that.
- //
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
- EventEmitter.prototype.addListener = EventEmitter.prototype.on;
- //
- // Expose the prefix.
- //
- EventEmitter.prefixed = prefix;
- //
- // Allow `EventEmitter` to be imported as module namespace.
- //
- EventEmitter.EventEmitter = EventEmitter;
- //
- // Expose the module.
- //
- {
- module.exports = EventEmitter;
- }
- });
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type
- */(function(PropertySyntax){/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#coordinate
- */PropertySyntax["COORDINATE"]="<coordinate>";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#color
- */PropertySyntax["COLOR"]="<color>";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#paint
- */PropertySyntax["PAINT"]="<paint>";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number
- */PropertySyntax["NUMBER"]="<number>";/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/angle
- */PropertySyntax["ANGLE"]="<angle>";/**
- * <number> with range 0..1
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#opacity_value
- */PropertySyntax["OPACITY_VALUE"]="<opacity-value>";/**
- * <number> with range 0..Infinity
- */PropertySyntax["SHADOW_BLUR"]="<shadow-blur>";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#length
- */PropertySyntax["LENGTH"]="<length>";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage
- */PropertySyntax["PERCENTAGE"]="<percentage>";PropertySyntax["LENGTH_PERCENTAGE"]="<length> | <percentage>";PropertySyntax["LENGTH_PERCENTAGE_12"]="[<length> | <percentage>]{1,2}";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin#formal_syntax
- */PropertySyntax["LENGTH_PERCENTAGE_14"]="[<length> | <percentage>]{1,4}";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts
- */PropertySyntax["LIST_OF_POINTS"]="<list-of-points>";PropertySyntax["PATH"]="<path>";/**
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter#formal_syntax
- */PropertySyntax["FILTER"]="<filter>";PropertySyntax["Z_INDEX"]="<z-index>";PropertySyntax["OFFSET_DISTANCE"]="<offset-distance>";PropertySyntax["DEFINED_PATH"]="<defined-path>";PropertySyntax["MARKER"]="<marker>";PropertySyntax["TRANSFORM"]="<transform>";PropertySyntax["TRANSFORM_ORIGIN"]="<transform-origin>";PropertySyntax["TEXT"]="<text>";PropertySyntax["TEXT_TRANSFORM"]="<text-transform>";})(exports.PropertySyntax||(exports.PropertySyntax={}));function _regeneratorRuntime(){_regeneratorRuntime=function _regeneratorRuntime(){return exports;};var exports={},Op=Object.prototype,hasOwn=Op.hasOwnProperty,defineProperty=Object.defineProperty||function(obj,key,desc){obj[key]=desc.value;},$Symbol="function"==typeof Symbol?Symbol:{},iteratorSymbol=$Symbol.iterator||"@@iterator",asyncIteratorSymbol=$Symbol.asyncIterator||"@@asyncIterator",toStringTagSymbol=$Symbol.toStringTag||"@@toStringTag";function define(obj,key,value){return Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}),obj[key];}try{define({},"");}catch(err){define=function define(obj,key,value){return obj[key]=value;};}function wrap(innerFn,outerFn,self,tryLocsList){var protoGenerator=outerFn&&outerFn.prototype instanceof Generator?outerFn:Generator,generator=Object.create(protoGenerator.prototype),context=new Context(tryLocsList||[]);return defineProperty(generator,"_invoke",{value:makeInvokeMethod(innerFn,self,context)}),generator;}function tryCatch(fn,obj,arg){try{return {type:"normal",arg:fn.call(obj,arg)};}catch(err){return {type:"throw",arg:err};}}exports.wrap=wrap;var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var IteratorPrototype={};define(IteratorPrototype,iteratorSymbol,function(){return this;});var getProto=Object.getPrototypeOf,NativeIteratorPrototype=getProto&&getProto(getProto(values([])));NativeIteratorPrototype&&NativeIteratorPrototype!==Op&&hasOwn.call(NativeIteratorPrototype,iteratorSymbol)&&(IteratorPrototype=NativeIteratorPrototype);var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(IteratorPrototype);function defineIteratorMethods(prototype){["next","throw","return"].forEach(function(method){define(prototype,method,function(arg){return this._invoke(method,arg);});});}function AsyncIterator(generator,PromiseImpl){function invoke(method,arg,resolve,reject){var record=tryCatch(generator[method],generator,arg);if("throw"!==record.type){var result=record.arg,value=result.value;return value&&"object"==typeof value&&hasOwn.call(value,"__await")?PromiseImpl.resolve(value.__await).then(function(value){invoke("next",value,resolve,reject);},function(err){invoke("throw",err,resolve,reject);}):PromiseImpl.resolve(value).then(function(unwrapped){result.value=unwrapped,resolve(result);},function(error){return invoke("throw",error,resolve,reject);});}reject(record.arg);}var previousPromise;defineProperty(this,"_invoke",{value:function value(method,arg){function callInvokeWithMethodAndArg(){return new PromiseImpl(function(resolve,reject){invoke(method,arg,resolve,reject);});}return previousPromise=previousPromise?previousPromise.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg();}});}function makeInvokeMethod(innerFn,self,context){var state="suspendedStart";return function(method,arg){if("executing"===state)throw new Error("Generator is already running");if("completed"===state){if("throw"===method)throw arg;return doneResult();}for(context.method=method,context.arg=arg;;){var delegate=context.delegate;if(delegate){var delegateResult=maybeInvokeDelegate(delegate,context);if(delegateResult){if(delegateResult===ContinueSentinel)continue;return delegateResult;}}if("next"===context.method)context.sent=context._sent=context.arg;else if("throw"===context.method){if("suspendedStart"===state)throw state="completed",context.arg;context.dispatchException(context.arg);}else "return"===context.method&&context.abrupt("return",context.arg);state="executing";var record=tryCatch(innerFn,self,context);if("normal"===record.type){if(state=context.done?"completed":"suspendedYield",record.arg===ContinueSentinel)continue;return {value:record.arg,done:context.done};}"throw"===record.type&&(state="completed",context.method="throw",context.arg=record.arg);}};}function maybeInvokeDelegate(delegate,context){var methodName=context.method,method=delegate.iterator[methodName];if(undefined===method)return context.delegate=null,"throw"===methodName&&delegate.iterator.return&&(context.method="return",context.arg=undefined,maybeInvokeDelegate(delegate,context),"throw"===context.method)||"return"!==methodName&&(context.method="throw",context.arg=new TypeError("The iterator does not provide a '"+methodName+"' method")),ContinueSentinel;var record=tryCatch(method,delegate.iterator,context.arg);if("throw"===record.type)return context.method="throw",context.arg=record.arg,context.delegate=null,ContinueSentinel;var info=record.arg;return info?info.done?(context[delegate.resultName]=info.value,context.next=delegate.nextLoc,"return"!==context.method&&(context.method="next",context.arg=undefined),context.delegate=null,ContinueSentinel):info:(context.method="throw",context.arg=new TypeError("iterator result is not an object"),context.delegate=null,ContinueSentinel);}function pushTryEntry(locs){var entry={tryLoc:locs[0]};1 in locs&&(entry.catchLoc=locs[1]),2 in locs&&(entry.finallyLoc=locs[2],entry.afterLoc=locs[3]),this.tryEntries.push(entry);}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal",delete record.arg,entry.completion=record;}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}],tryLocsList.forEach(pushTryEntry,this),this.reset(!0);}function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod)return iteratorMethod.call(iterable);if("function"==typeof iterable.next)return iterable;if(!isNaN(iterable.length)){var i=-1,next=function next(){for(;++i<iterable.length;)if(hasOwn.call(iterable,i))return next.value=iterable[i],next.done=!1,next;return next.value=undefined,next.done=!0,next;};return next.next=next;}}return {next:doneResult};}function doneResult(){return {value:undefined,done:!0};}return GeneratorFunction.prototype=GeneratorFunctionPrototype,defineProperty(Gp,"constructor",{value:GeneratorFunctionPrototype,configurable:!0}),defineProperty(GeneratorFunctionPrototype,"constructor",{value:GeneratorFunction,configurable:!0}),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,toStringTagSymbol,"GeneratorFunction"),exports.isGeneratorFunction=function(genFun){var ctor="function"==typeof genFun&&genFun.constructor;return !!ctor&&(ctor===GeneratorFunction||"GeneratorFunction"===(ctor.displayName||ctor.name));},exports.mark=function(genFun){return Object.setPrototypeOf?Object.setPrototypeOf(genFun,GeneratorFunctionPrototype):(genFun.__proto__=GeneratorFunctionPrototype,define(genFun,toStringTagSymbol,"GeneratorFunction")),genFun.prototype=Object.create(Gp),genFun;},exports.awrap=function(arg){return {__await:arg};},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,asyncIteratorSymbol,function(){return this;}),exports.AsyncIterator=AsyncIterator,exports.async=function(innerFn,outerFn,self,tryLocsList,PromiseImpl){void 0===PromiseImpl&&(PromiseImpl=Promise);var iter=new AsyncIterator(wrap(innerFn,outerFn,self,tryLocsList),PromiseImpl);return exports.isGeneratorFunction(outerFn)?iter:iter.next().then(function(result){return result.done?result.value:iter.next();});},defineIteratorMethods(Gp),define(Gp,toStringTagSymbol,"Generator"),define(Gp,iteratorSymbol,function(){return this;}),define(Gp,"toString",function(){return "[object Generator]";}),exports.keys=function(val){var object=Object(val),keys=[];for(var key in object)keys.push(key);return keys.reverse(),function next(){for(;keys.length;){var key=keys.pop();if(key in object)return next.value=key,next.done=!1,next;}return next.done=!0,next;};},exports.values=values,Context.prototype={constructor:Context,reset:function reset(skipTempReset){if(this.prev=0,this.next=0,this.sent=this._sent=undefined,this.done=!1,this.delegate=null,this.method="next",this.arg=undefined,this.tryEntries.forEach(resetTryEntry),!skipTempReset)for(var name in this)"t"===name.charAt(0)&&hasOwn.call(this,name)&&!isNaN(+name.slice(1))&&(this[name]=undefined);},stop:function stop(){this.done=!0;var rootRecord=this.tryEntries[0].completion;if("throw"===rootRecord.type)throw rootRecord.arg;return this.rval;},dispatchException:function dispatchException(exception){if(this.done)throw exception;var context=this;function handle(loc,caught){return record.type="throw",record.arg=exception,context.next=loc,caught&&(context.method="next",context.arg=undefined),!!caught;}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i],record=entry.completion;if("root"===entry.tryLoc)return handle("end");if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc"),hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc)return handle(entry.catchLoc,!0);if(this.prev<entry.finallyLoc)return handle(entry.finallyLoc);}else if(hasCatch){if(this.prev<entry.catchLoc)return handle(entry.catchLoc,!0);}else {if(!hasFinally)throw new Error("try statement without catch or finally");if(this.prev<entry.finallyLoc)return handle(entry.finallyLoc);}}}},abrupt:function abrupt(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break;}}finallyEntry&&("break"===type||"continue"===type)&&finallyEntry.tryLoc<=arg&&arg<=finallyEntry.finallyLoc&&(finallyEntry=null);var record=finallyEntry?finallyEntry.completion:{};return record.type=type,record.arg=arg,finallyEntry?(this.method="next",this.next=finallyEntry.finallyLoc,ContinueSentinel):this.complete(record);},complete:function complete(record,afterLoc){if("throw"===record.type)throw record.arg;return "break"===record.type||"continue"===record.type?this.next=record.arg:"return"===record.type?(this.rval=this.arg=record.arg,this.method="return",this.next="end"):"normal"===record.type&&afterLoc&&(this.next=afterLoc),ContinueSentinel;},finish:function finish(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc)return this.complete(entry.completion,entry.afterLoc),resetTryEntry(entry),ContinueSentinel;}},catch:function _catch(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if("throw"===record.type){var thrown=record.arg;resetTryEntry(entry);}return thrown;}}throw new Error("illegal catch attempt");},delegateYield:function delegateYield(iterable,resultName,nextLoc){return this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc},"next"===this.method&&(this.arg=undefined),ContinueSentinel;}},exports;}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else {Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,_toPropertyKey(descriptor.key),descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);Object.defineProperty(Constructor,"prototype",{writable:false});return Constructor;}function _extends(){_extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return {};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2;}function _createForOfIteratorHelperLoose(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(it)return (it=it.call(o)).next.bind(it);if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;return function(){if(i>=o.length)return {done:true};return {done:false,value:o[i++]};};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _toPrimitive(input,hint){if(typeof input!=="object"||input===null)return input;var prim=input[Symbol.toPrimitive];if(prim!==undefined){var res=prim.call(input,hint||"default");if(typeof res!=="object")return res;throw new TypeError("@@toPrimitive must return a primitive value.");}return (hint==="string"?String:Number)(input);}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return typeof key==="symbol"?key:String(key);}// These units are iterated through, so be careful when adding or changing the
- // order.
- (function(UnitType){UnitType[UnitType["kUnknown"]=0]="kUnknown";UnitType[UnitType["kNumber"]=1]="kNumber";UnitType[UnitType["kPercentage"]=2]="kPercentage";// Length units
- UnitType[UnitType["kEms"]=3]="kEms";// kExs,
- UnitType[UnitType["kPixels"]=4]="kPixels";// kCentimeters,
- // kMillimeters,
- // kInches,
- // kPoints,
- // kPicas,
- // kQuarterMillimeters,
- // https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
- //
- // See also IsViewportPercentageLength.
- // kViewportWidth,
- // kViewportHeight,
- // kViewportInlineSize,
- // kViewportBlockSize,
- // kViewportMin,
- // kViewportMax,
- // kSmallViewportWidth,
- // kSmallViewportHeight,
- // kSmallViewportInlineSize,
- // kSmallViewportBlockSize,
- // kSmallViewportMin,
- // kSmallViewportMax,
- // kLargeViewportWidth,
- // kLargeViewportHeight,
- // kLargeViewportInlineSize,
- // kLargeViewportBlockSize,
- // kLargeViewportMin,
- // kLargeViewportMax,
- // kDynamicViewportWidth,
- // kDynamicViewportHeight,
- // kDynamicViewportInlineSize,
- // kDynamicViewportBlockSize,
- // kDynamicViewportMin,
- // kDynamicViewportMax,
- // https://drafts.csswg.org/css-contain-3/#container-lengths
- //
- // See also IsContainerPercentageLength.
- // kContainerWidth,
- // kContainerHeight,
- // kContainerInlineSize,
- // kContainerBlockSize,
- // kContainerMin,
- // kContainerMax,
- UnitType[UnitType["kRems"]=5]="kRems";// kChs,
- // kUserUnits, // The SVG term for unitless lengths
- // Angle units
- UnitType[UnitType["kDegrees"]=6]="kDegrees";UnitType[UnitType["kRadians"]=7]="kRadians";UnitType[UnitType["kGradians"]=8]="kGradians";UnitType[UnitType["kTurns"]=9]="kTurns";// Time units
- UnitType[UnitType["kMilliseconds"]=10]="kMilliseconds";UnitType[UnitType["kSeconds"]=11]="kSeconds";// kHertz,
- // kKilohertz,
- // Resolution
- // kDotsPerPixel,
- // kDotsPerInch,
- // kDotsPerCentimeter,
- // Other units
- // kFraction,
- UnitType[UnitType["kInteger"]=12]="kInteger";// This value is used to handle quirky margins in reflow roots (body, td,
- // and th) like WinIE. The basic idea is that a stylesheet can use the value
- // __qem (for quirky em) instead of em. When the quirky value is used, if
- // you're in quirks mode, the margin will collapse away inside a table cell.
- // This quirk is specified in the HTML spec but our impl is different.
- // TODO: Remove this. crbug.com/443952
- // kQuirkyEms,
- })(exports.UnitType||(exports.UnitType={}));var UnitCategory;(function(UnitCategory){UnitCategory[UnitCategory["kUNumber"]=0]="kUNumber";UnitCategory[UnitCategory["kUPercent"]=1]="kUPercent";UnitCategory[UnitCategory["kULength"]=2]="kULength";UnitCategory[UnitCategory["kUAngle"]=3]="kUAngle";UnitCategory[UnitCategory["kUTime"]=4]="kUTime";// kUFrequency,
- // kUResolution,
- UnitCategory[UnitCategory["kUOther"]=5]="kUOther";})(UnitCategory||(UnitCategory={}));var ValueRange;(function(ValueRange){ValueRange[ValueRange["kAll"]=0]="kAll";ValueRange[ValueRange["kNonNegative"]=1]="kNonNegative";ValueRange[ValueRange["kInteger"]=2]="kInteger";ValueRange[ValueRange["kNonNegativeInteger"]=3]="kNonNegativeInteger";ValueRange[ValueRange["kPositiveInteger"]=4]="kPositiveInteger";})(ValueRange||(ValueRange={}));var Nested;(function(Nested){Nested[Nested["kYes"]=0]="kYes";Nested[Nested["kNo"]=1]="kNo";})(Nested||(Nested={}));var ParenLess;(function(ParenLess){ParenLess[ParenLess["kYes"]=0]="kYes";ParenLess[ParenLess["kNo"]=1]="kNo";})(ParenLess||(ParenLess={}));// This file specifies the unit strings used in CSSPrimitiveValues.
- var data=[{name:'em',unit_type:exports.UnitType.kEms},// {
- // name: 'ex',
- // unit_type: UnitType.kExs,
- // },
- {name:'px',unit_type:exports.UnitType.kPixels},// {
- // name: "cm",
- // unit_type: UnitType.kCentimeters,
- // },
- // {
- // name: "mm",
- // unit_type: UnitType.kMillimeters,
- // },
- // {
- // name: "q",
- // unit_type: UnitType.kQuarterMillimeters,
- // },
- // {
- // name: "in",
- // unit_type: UnitType.kInches,
- // },
- // {
- // name: "pt",
- // unit_type: UnitType.kPoints,
- // },
- // {
- // name: "pc",
- // unit_type: UnitType.kPicas,
- // },
- {name:'deg',unit_type:exports.UnitType.kDegrees},{name:'rad',unit_type:exports.UnitType.kRadians},{name:'grad',unit_type:exports.UnitType.kGradians},{name:'ms',unit_type:exports.UnitType.kMilliseconds},{name:'s',unit_type:exports.UnitType.kSeconds},// {
- // name: "hz",
- // unit_type: UnitType.kHertz,
- // },
- // {
- // name: "khz",
- // unit_type: UnitType.kKilohertz,
- // },
- // {
- // name: "dpi",
- // unit_type: "kDotsPerInch",
- // },
- // {
- // name: "dpcm",
- // unit_type: "kDotsPerCentimeter",
- // },
- // {
- // name: "dppx",
- // unit_type: "kDotsPerPixel",
- // },
- // {
- // name: "x",
- // unit_type: "kDotsPerPixel",
- // },
- // {
- // name: "vw",
- // unit_type: "kViewportWidth",
- // },
- // {
- // name: "vh",
- // unit_type: "kViewportHeight",
- // },
- // {
- // name: "vi",
- // unit_type: "kViewportInlineSize",
- // },
- // {
- // name: "vb",
- // unit_type: "kViewportBlockSize",
- // },
- // {
- // name: "vmin",
- // unit_type: UnitType.kViewportMin,
- // },
- // {
- // name: "vmax",
- // unit_type: UnitType.kViewportMax,
- // },
- // {
- // name: "svw",
- // unit_type: "kSmallViewportWidth",
- // },
- // {
- // name: "svh",
- // unit_type: "kSmallViewportHeight",
- // },
- // {
- // name: "svi",
- // unit_type: "kSmallViewportInlineSize",
- // },
- // {
- // name: "svb",
- // unit_type: "kSmallViewportBlockSize",
- // },
- // {
- // name: "svmin",
- // unit_type: "kSmallViewportMin",
- // },
- // {
- // name: "svmax",
- // unit_type: "kSmallViewportMax",
- // },
- // {
- // name: "lvw",
- // unit_type: "kLargeViewportWidth",
- // },
- // {
- // name: "lvh",
- // unit_type: "kLargeViewportHeight",
- // },
- // {
- // name: "lvi",
- // unit_type: "kLargeViewportInlineSize",
- // },
- // {
- // name: "lvb",
- // unit_type: "kLargeViewportBlockSize",
- // },
- // {
- // name: "lvmin",
- // unit_type: UnitType.kLargeViewportMin,
- // },
- // {
- // name: "lvmax",
- // unit_type: UnitType.kLargeViewportMax,
- // },
- // {
- // name: "dvw",
- // unit_type: UnitType.kDynamicViewportWidth,
- // },
- // {
- // name: "dvh",
- // unit_type: UnitType.kDynamicViewportHeight,
- // },
- // {
- // name: "dvi",
- // unit_type: UnitType.kDynamicViewportInlineSize,
- // },
- // {
- // name: "dvb",
- // unit_type: UnitType.kDynamicViewportBlockSize,
- // },
- // {
- // name: "dvmin",
- // unit_type: UnitType.kDynamicViewportMin,
- // },
- // {
- // name: "dvmax",
- // unit_type: UnitType.kDynamicViewportMax,
- // },
- // {
- // name: "cqw",
- // unit_type: UnitType.kContainerWidth,
- // },
- // {
- // name: "cqh",
- // unit_type: UnitType.kContainerHeight,
- // },
- // {
- // name: "cqi",
- // unit_type: UnitType.kContainerInlineSize,
- // },
- // {
- // name: "cqb",
- // unit_type: UnitType.kContainerBlockSize,
- // },
- // {
- // name: "cqmin",
- // unit_type: UnitType.kContainerMin,
- // },
- // {
- // name: "cqmax",
- // unit_type: UnitType.kContainerMax,
- // },
- {name:'rem',unit_type:exports.UnitType.kRems},// {
- // name: 'fr',
- // unit_type: UnitType.kFraction,
- // },
- {name:'turn',unit_type:exports.UnitType.kTurns}// {
- // name: 'ch',
- // unit_type: UnitType.kChs,
- // },
- // {
- // name: '__qem',
- // unit_type: UnitType.kQuirkyEms,
- // },
- ];var CSSStyleValueType;(function(CSSStyleValueType){CSSStyleValueType[CSSStyleValueType["kUnknownType"]=0]="kUnknownType";CSSStyleValueType[CSSStyleValueType["kUnparsedType"]=1]="kUnparsedType";CSSStyleValueType[CSSStyleValueType["kKeywordType"]=2]="kKeywordType";// Start of CSSNumericValue subclasses
- CSSStyleValueType[CSSStyleValueType["kUnitType"]=3]="kUnitType";CSSStyleValueType[CSSStyleValueType["kSumType"]=4]="kSumType";CSSStyleValueType[CSSStyleValueType["kProductType"]=5]="kProductType";CSSStyleValueType[CSSStyleValueType["kNegateType"]=6]="kNegateType";CSSStyleValueType[CSSStyleValueType["kInvertType"]=7]="kInvertType";CSSStyleValueType[CSSStyleValueType["kMinType"]=8]="kMinType";CSSStyleValueType[CSSStyleValueType["kMaxType"]=9]="kMaxType";CSSStyleValueType[CSSStyleValueType["kClampType"]=10]="kClampType";// End of CSSNumericValue subclasses
- CSSStyleValueType[CSSStyleValueType["kTransformType"]=11]="kTransformType";CSSStyleValueType[CSSStyleValueType["kPositionType"]=12]="kPositionType";CSSStyleValueType[CSSStyleValueType["kURLImageType"]=13]="kURLImageType";CSSStyleValueType[CSSStyleValueType["kColorType"]=14]="kColorType";CSSStyleValueType[CSSStyleValueType["kUnsupportedColorType"]=15]="kUnsupportedColorType";})(CSSStyleValueType||(CSSStyleValueType={}));// function parseCSSStyleValue(propertyName: string, value: string): CSSStyleValue[] {
- // // const propertyId = cssPropertyID(propertyName);
- // // if (propertyId === CSSPropertyID.kInvalid) {
- // // return [];
- // // }
- // // const customPropertyName = propertyId === CSSPropertyID.kVariable ? propertyName : null;
- // // return fromString(propertyId, customPropertyName, value);
- // return [];
- // }
- var stringToUnitType=function stringToUnitType(name){return data.find(function(item){return item.name===name;}).unit_type;};var unitFromName=function unitFromName(name){if(!name){return exports.UnitType.kUnknown;}if(name==='number'){return exports.UnitType.kNumber;}if(name==='percent'||name==='%'){return exports.UnitType.kPercentage;}return stringToUnitType(name);};var unitTypeToUnitCategory=function unitTypeToUnitCategory(type){switch(type){case exports.UnitType.kNumber:case exports.UnitType.kInteger:return UnitCategory.kUNumber;case exports.UnitType.kPercentage:return UnitCategory.kUPercent;case exports.UnitType.kPixels:// case UnitType.kCentimeters:
- // case UnitType.kMillimeters:
- // case UnitType.kQuarterMillimeters:
- // case UnitType.kInches:
- // case UnitType.kPoints:
- // case UnitType.kPicas:
- // case UnitType.kUserUnits:
- return UnitCategory.kULength;case exports.UnitType.kMilliseconds:case exports.UnitType.kSeconds:return UnitCategory.kUTime;case exports.UnitType.kDegrees:case exports.UnitType.kRadians:case exports.UnitType.kGradians:case exports.UnitType.kTurns:return UnitCategory.kUAngle;// case UnitType.kHertz:
- // case UnitType.kKilohertz:
- // return UnitCategory.kUFrequency;
- // case UnitType.kDotsPerPixel:
- // case UnitType.kDotsPerInch:
- // case UnitType.kDotsPerCentimeter:
- // return UnitCategory.kUResolution;
- default:return UnitCategory.kUOther;}};var canonicalUnitTypeForCategory=function canonicalUnitTypeForCategory(category){// The canonical unit type is chosen according to the way
- // CSSPropertyParser.ValidUnit() chooses the default unit in each category
- // (based on unitflags).
- switch(category){case UnitCategory.kUNumber:return exports.UnitType.kNumber;case UnitCategory.kULength:return exports.UnitType.kPixels;case UnitCategory.kUPercent:return exports.UnitType.kPercentage;// return UnitType.kUnknown; // Cannot convert between numbers and percent.
- case UnitCategory.kUTime:return exports.UnitType.kSeconds;case UnitCategory.kUAngle:return exports.UnitType.kDegrees;// case UnitCategory.kUFrequency:
- // return UnitType.kHertz;
- // case UnitCategory.kUResolution:
- // return UnitType.kDotsPerPixel;
- default:return exports.UnitType.kUnknown;}};/**
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/css_primitive_value.cc#353
- */var conversionToCanonicalUnitsScaleFactor=function conversionToCanonicalUnitsScaleFactor(unit_type){var factor=1.0;// FIXME: the switch can be replaced by an array of scale factors.
- switch(unit_type){// These are "canonical" units in their respective categories.
- case exports.UnitType.kPixels:// case UnitType.kUserUnits:
- case exports.UnitType.kDegrees:case exports.UnitType.kSeconds:// case UnitType.kHertz:
- break;case exports.UnitType.kMilliseconds:factor=0.001;break;// case UnitType.kCentimeters:
- // // factor = kCssPixelsPerCentimeter;
- // break;
- // case UnitType.kDotsPerCentimeter:
- // // factor = 1 / kCssPixelsPerCentimeter;
- // break;
- // case UnitType.kMillimeters:
- // // factor = kCssPixelsPerMillimeter;
- // break;
- // case UnitType.kQuarterMillimeters:
- // // factor = kCssPixelsPerQuarterMillimeter;
- // break;
- // case UnitType.kInches:
- // // factor = kCssPixelsPerInch;
- // break;
- // case UnitType.kDotsPerInch:
- // // factor = 1 / kCssPixelsPerInch;
- // break;
- // case UnitType.kPoints:
- // // factor = kCssPixelsPerPoint;
- // break;
- // case UnitType.kPicas:
- // // factor = kCssPixelsPerPica;
- // break;
- case exports.UnitType.kRadians:factor=180/Math.PI;break;case exports.UnitType.kGradians:factor=0.9;break;case exports.UnitType.kTurns:factor=360;break;}return factor;};var unitTypeToString=function unitTypeToString(type){switch(type){case exports.UnitType.kNumber:case exports.UnitType.kInteger:// case UnitType.kUserUnits:
- return '';case exports.UnitType.kPercentage:return '%';case exports.UnitType.kEms:// case UnitType.kQuirkyEms:
- return 'em';// case UnitType.kExs:
- // return 'ex';
- case exports.UnitType.kRems:return 'rem';// case UnitType.kChs:
- // return 'ch';
- case exports.UnitType.kPixels:return 'px';// case UnitType.kCentimeters:
- // return 'cm';
- // case UnitType.kDotsPerPixel:
- // return 'dppx';
- // case UnitType.kDotsPerInch:
- // return 'dpi';
- // case UnitType.kDotsPerCentimeter:
- // return 'dpcm';
- // case UnitType.kMillimeters:
- // return 'mm';
- // case UnitType.kQuarterMillimeters:
- // return 'q';
- // case UnitType.kInches:
- // return 'in';
- // case UnitType.kPoints:
- // return 'pt';
- // case UnitType.kPicas:
- // return 'pc';
- case exports.UnitType.kDegrees:return 'deg';case exports.UnitType.kRadians:return 'rad';case exports.UnitType.kGradians:return 'grad';case exports.UnitType.kMilliseconds:return 'ms';case exports.UnitType.kSeconds:return 's';// case UnitType.kHertz:
- // return 'hz';
- // case UnitType.kKilohertz:
- // return 'khz';
- case exports.UnitType.kTurns:return 'turn';}return '';};/**
- * CSSStyleValue is the base class for all CSS values accessible from Typed OM.
- * Values that are not yet supported as specific types are also returned as base CSSStyleValues.
- *
- * Spec @see https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects
- * Docs @see https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue
- */var CSSStyleValue=/*#__PURE__*/function(){function CSSStyleValue(){}// static parse(propertyName: string, value: string): CSSStyleValue {
- // return parseCSSStyleValue(propertyName, value)[0];
- // }
- // static parseAll(propertyName: string, value: string): CSSStyleValue[] {
- // return parseCSSStyleValue(propertyName, value);
- // }
- CSSStyleValue.isAngle=function isAngle(unit){return unit===exports.UnitType.kDegrees||unit===exports.UnitType.kRadians||unit===exports.UnitType.kGradians||unit===exports.UnitType.kTurns;}// static isViewportPercentageLength(type: UnitType) {
- // return type >= UnitType.kViewportWidth && type <= UnitType.kDynamicViewportMax;
- // }
- // static isContainerPercentageLength(type: UnitType) {
- // return type >= UnitType.kContainerWidth && type <= UnitType.kContainerMax;
- // }
- ;CSSStyleValue.isLength=function isLength(type){// return (type >= UnitType.kEms && type <= UnitType.kUserUnits) || type == UnitType.kQuirkyEms;
- return type>=exports.UnitType.kEms&&type<exports.UnitType.kDegrees;};CSSStyleValue.isRelativeUnit=function isRelativeUnit(type){return type===exports.UnitType.kPercentage||type===exports.UnitType.kEms||// type === UnitType.kExs ||
- type===exports.UnitType.kRems// type === UnitType.kChs ||
- // this.isViewportPercentageLength(type) ||
- // this.isContainerPercentageLength(type)
- ;};CSSStyleValue.isTime=function isTime(unit){return unit===exports.UnitType.kSeconds||unit===exports.UnitType.kMilliseconds;}// protected abstract toCSSValue(): CSSValue;
- ;var _proto=CSSStyleValue.prototype;_proto.toString=function toString(){return this.buildCSSText(Nested.kNo,ParenLess.kNo,'');};_proto.isNumericValue=function isNumericValue(){return this.getType()>=CSSStyleValueType.kUnitType&&this.getType()<=CSSStyleValueType.kClampType;};return CSSStyleValue;}();/**
- * CSSColorValue is the base class used for the various CSS color interfaces.
- *
- * @see https://drafts.css-houdini.org/css-typed-om-1/#colorvalue-objects
- */var CSSColorValue=/*#__PURE__*/function(_CSSStyleValue){_inheritsLoose(CSSColorValue,_CSSStyleValue);function CSSColorValue(colorSpace){var _this;_this=_CSSStyleValue.call(this)||this;_this.colorSpace=void 0;_this.colorSpace=colorSpace;return _this;}var _proto=CSSColorValue.prototype;_proto.getType=function getType(){return CSSStyleValueType.kColorType;}// buildCSSText(n: Nested, p: ParenLess, result: string): string {
- // let text = '';
- // if (this.colorSpace === 'rgb') {
- // text = `rgba(${this.channels.join(',')},${this.alpha})`;
- // }
- // return (result += text);
- // }
- /**
- * @see https://drafts.css-houdini.org/css-typed-om-1/#dom-csscolorvalue-to
- */;_proto.to=function to(colorSpace){return this;};return CSSColorValue;}(CSSStyleValue);(function(GradientType){GradientType[GradientType["Constant"]=0]="Constant";GradientType[GradientType["LinearGradient"]=1]="LinearGradient";GradientType[GradientType["RadialGradient"]=2]="RadialGradient";})(exports.GradientType||(exports.GradientType={}));var CSSGradientValue=/*#__PURE__*/function(_CSSStyleValue){_inheritsLoose(CSSGradientValue,_CSSStyleValue);function CSSGradientValue(type,value){var _this;_this=_CSSStyleValue.call(this)||this;_this.type=void 0;_this.value=void 0;_this.type=type;_this.value=value;return _this;}var _proto=CSSGradientValue.prototype;_proto.clone=function clone(){return new CSSGradientValue(this.type,this.value);};_proto.buildCSSText=function buildCSSText(n,p,result){return result;};_proto.getType=function getType(){return CSSStyleValueType.kColorType;};return CSSGradientValue;}(CSSStyleValue);/**
- * CSSKeywordValue represents CSS Values that are specified as keywords
- * eg. 'initial'
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSKeywordValue
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_keyword_value.idl
- */var CSSKeywordValue=/*#__PURE__*/function(_CSSStyleValue){_inheritsLoose(CSSKeywordValue,_CSSStyleValue);function CSSKeywordValue(value){var _this;_this=_CSSStyleValue.call(this)||this;_this.value=void 0;_this.value=value;return _this;}var _proto=CSSKeywordValue.prototype;_proto.clone=function clone(){return new CSSKeywordValue(this.value);};_proto.getType=function getType(){return CSSStyleValueType.kKeywordType;};_proto.buildCSSText=function buildCSSText(n,p,result){return result+this.value;};return CSSKeywordValue;}(CSSStyleValue);function memoize(func,resolver){if(typeof func!=='function'||resolver!=null&&typeof resolver!=='function'){throw new TypeError('Expected a function');}var memoized=function memoized(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}var key=resolver?resolver.apply(this,args):args[0];var cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize.Cache||Map)();return memoized;}memoize.Cache=Map;var camelCase=memoize(function(str){if(str===void 0){str='';}return str.replace(/-([a-z])/g,function(g){return g[1].toUpperCase();});});var kebabize=function kebabize(str){return str.split('').map(function(letter,idx){return letter.toUpperCase()===letter?""+(idx!==0?'-':'')+letter.toLowerCase():letter;}).join('');};function DCHECK(bool){if(!bool){throw new Error();}}function isFunction(func){return typeof func==='function';}function isSymbol(value){// @see https://github.com/lodash/lodash/blob/master/isSymbol.js
- return typeof value==='symbol';}var definedProps=function definedProps(obj){return Object.fromEntries(Object.entries(obj).filter(function(_ref){var v=_ref[1];return v!==undefined;}));};var FORMAT_ATTR_MAP={d:{alias:'path'},strokeDasharray:{alias:'lineDash'},strokeWidth:{alias:'lineWidth'},textAnchor:{alias:'textAlign'},src:{alias:'img'}};var formatAttributeName=memoize(function(name){var attributeName=camelCase(name);var map=FORMAT_ATTR_MAP[attributeName];attributeName=(map===null||map===void 0?void 0:map.alias)||attributeName;return attributeName;});// type CSSNumericBaseType =
- // | 'length'
- // | 'angle'
- // | 'time'
- // | 'frequency'
- // | 'resolution'
- // | 'flex'
- // | 'percent';
- // https://drafts.css-houdini.org/css-typed-om/#dictdef-cssnumerictype
- // interface CSSNumericType {
- // length: number;
- // angle: number;
- // time: number;
- // frequency: number;
- // resolution: number;
- // flex: number;
- // percent: number;
- // percentHint: CSSNumericBaseType;
- // }
- var formatInfinityOrNaN=function formatInfinityOrNaN(number,suffix){if(suffix===void 0){suffix='';}var result='';if(!Number.isFinite(number)){if(number>0)result='infinity';else result='-infinity';}else {DCHECK(Number.isNaN(number));result='NaN';}return result+=suffix;};var toCanonicalUnit=function toCanonicalUnit(unit){return canonicalUnitTypeForCategory(unitTypeToUnitCategory(unit));};/**
- * CSSNumericValue is the base class for numeric and length typed CSS Values.
- * @see https://drafts.css-houdini.org/css-typed-om/#numeric-objects
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericValue
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_numeric_value.idl
- */ /**
- * Represents numeric values that can be expressed as a single number plus a
- * unit (or a naked number or percentage).
- * @see https://drafts.css-houdini.org/css-typed-om/#cssunitvalue
- */var CSSUnitValue=/*#__PURE__*/function(_CSSStyleValue){_inheritsLoose(CSSUnitValue,_CSSStyleValue);function CSSUnitValue(value,unitOrName){var _this;if(unitOrName===void 0){unitOrName=exports.UnitType.kNumber;}_this=_CSSStyleValue.call(this)||this;_this.unit=void 0;_this.value=void 0;var unit;if(typeof unitOrName==='string'){unit=unitFromName(unitOrName);}else {unit=unitOrName;}_this.unit=unit;_this.value=value;return _this;}var _proto=CSSUnitValue.prototype;_proto.clone=function clone(){return new CSSUnitValue(this.value,this.unit);};_proto.equals=function equals(other){var other_unit_value=other;return this.value===other_unit_value.value&&this.unit===other_unit_value.unit;};_proto.getType=function getType(){return CSSStyleValueType.kUnitType;};_proto.convertTo=function convertTo(target_unit){if(this.unit===target_unit){return new CSSUnitValue(this.value,this.unit);}// Instead of defining the scale factors for every unit to every other unit,
- // we simply convert to the canonical unit and back since we already have
- // the scale factors for canonical units.
- var canonical_unit=toCanonicalUnit(this.unit);if(canonical_unit!==toCanonicalUnit(target_unit)||canonical_unit===exports.UnitType.kUnknown){return null;}var scale_factor=conversionToCanonicalUnitsScaleFactor(this.unit)/conversionToCanonicalUnitsScaleFactor(target_unit);return new CSSUnitValue(this.value*scale_factor,target_unit);};_proto.buildCSSText=function buildCSSText(n,p,result){var text;switch(this.unit){case exports.UnitType.kUnknown:// FIXME
- break;case exports.UnitType.kInteger:text=Number(this.value).toFixed(0);break;case exports.UnitType.kNumber:case exports.UnitType.kPercentage:case exports.UnitType.kEms:// case UnitType.kQuirkyEms:
- // case UnitType.kExs:
- case exports.UnitType.kRems:// case UnitType.kChs:
- case exports.UnitType.kPixels:// case UnitType.kCentimeters:
- // case UnitType.kDotsPerPixel:
- // case UnitType.kDotsPerInch:
- // case UnitType.kDotsPerCentimeter:
- // case UnitType.kMillimeters:
- // case UnitType.kQuarterMillimeters:
- // case UnitType.kInches:
- // case UnitType.kPoints:
- // case UnitType.kPicas:
- // case UnitType.kUserUnits:
- case exports.UnitType.kDegrees:case exports.UnitType.kRadians:case exports.UnitType.kGradians:case exports.UnitType.kMilliseconds:case exports.UnitType.kSeconds:// case UnitType.kHertz:
- // case UnitType.kKilohertz:
- case exports.UnitType.kTurns:// case UnitType.kContainerMax: { // case UnitType.kContainerMin: // case UnitType.kContainerBlockSize: // case UnitType.kContainerInlineSize: // case UnitType.kContainerHeight: // case UnitType.kContainerWidth: // case UnitType.kDynamicViewportMax: // case UnitType.kDynamicViewportMin: // case UnitType.kDynamicViewportBlockSize: // case UnitType.kDynamicViewportInlineSize: // case UnitType.kDynamicViewportHeight: // case UnitType.kDynamicViewportWidth: // case UnitType.kLargeViewportMax: // case UnitType.kLargeViewportMin: // case UnitType.kLargeViewportBlockSize: // case UnitType.kLargeViewportInlineSize: // case UnitType.kLargeViewportHeight: // case UnitType.kLargeViewportWidth: // case UnitType.kSmallViewportMax: // case UnitType.kSmallViewportMin: // case UnitType.kSmallViewportBlockSize: // case UnitType.kSmallViewportInlineSize: // case UnitType.kSmallViewportHeight: // case UnitType.kSmallViewportWidth: // case UnitType.kViewportMax: // case UnitType.kViewportMin: // case UnitType.kViewportBlockSize: // case UnitType.kViewportInlineSize: // case UnitType.kViewportHeight: // case UnitType.kViewportWidth: // case UnitType.kFraction:
- {var kMinInteger=-999999;var kMaxInteger=999999;var value=this.value;var unit=unitTypeToString(this.unit);if(value<kMinInteger||value>kMaxInteger){var _unit=unitTypeToString(this.unit);if(!Number.isFinite(value)||Number.isNaN(value)){text=formatInfinityOrNaN(value,_unit);}else {text=value+(_unit||'');}}else {text=""+value+unit;}}}result+=text;return result;};return CSSUnitValue;}(CSSStyleValue);var Opx=new CSSUnitValue(0,'px');var Lpx=new CSSUnitValue(1,'px');var Odeg=new CSSUnitValue(0,'deg');/**
- * The CSSRGB class represents the CSS rgb()/rgba() functions.
- *
- * @see https://drafts.css-houdini.org/css-typed-om-1/#cssrgb
- */var CSSRGB=/*#__PURE__*/function(_CSSColorValue){_inheritsLoose(CSSRGB,_CSSColorValue);function CSSRGB(r,g,b,alpha,/**
- * 'transparent' & 'none' has the same rgba data
- */isNone){var _this;if(alpha===void 0){alpha=1;}if(isNone===void 0){isNone=false;}_this=_CSSColorValue.call(this,'rgb')||this;_this.r=void 0;_this.g=void 0;_this.b=void 0;_this.alpha=void 0;_this.isNone=void 0;_this.r=r;_this.g=g;_this.b=b;_this.alpha=alpha;_this.isNone=isNone;return _this;}var _proto=CSSRGB.prototype;_proto.clone=function clone(){return new CSSRGB(this.r,this.g,this.b,this.alpha);};_proto.buildCSSText=function buildCSSText(n,p,result){return result+("rgba("+this.r+","+this.g+","+this.b+","+this.alpha+")");};return CSSRGB;}(CSSColorValue);/**
- * holds useful CSS-related methods.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS
- *
- * * CSS Typed OM @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/factory_functions
- * * register property @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
- * * CSS Layout API
- */var CSS={/**
- * <number>
- * @see https://drafts.csswg.org/css-values-4/#number-value
- */number:function number(n){return new CSSUnitValue(n);},/**
- * <percentage>
- * @see https://drafts.csswg.org/css-values-4/#percentage-value
- */percent:function percent(n){return new CSSUnitValue(n,'%');},/**
- * <length>
- */px:function px(n){return new CSSUnitValue(n,'px');},/**
- * <length>
- */em:function em(n){return new CSSUnitValue(n,'em');},rem:function rem(n){return new CSSUnitValue(n,'rem');},/**
- * <angle>
- */deg:function deg(n){return new CSSUnitValue(n,'deg');},/**
- * <angle>
- */grad:function grad(n){return new CSSUnitValue(n,'grad');},/**
- * <angle>
- */rad:function rad(n){return new CSSUnitValue(n,'rad');},/**
- * <angle>
- */turn:function turn(n){return new CSSUnitValue(n,'turn');},/**
- * <time>
- */s:function s(n){return new CSSUnitValue(n,'s');},/**
- * <time>
- */ms:function ms(n){return new CSSUnitValue(n,'ms');},/**
- * CSS Properties & Values API
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS_Properties_and_Values_API
- * @see https://drafts.css-houdini.org/css-properties-values-api/#registering-custom-properties
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
- */registerProperty:function registerProperty(definition){var name=definition.name,inherits=definition.inherits,interpolable=definition.interpolable,initialValue=definition.initialValue,syntax=definition.syntax;runtime.styleValueRegistry.registerMetadata({n:name,inh:inherits,int:interpolable,d:initialValue,syntax:syntax});},/**
- * CSS Layout API
- * register layout
- *
- * @see https://github.com/w3c/css-houdini-drafts/blob/main/css-layout-api/EXPLAINER.md
- * @see https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini#css_layout_api
- */registerLayout:function registerLayout(name,clazz){runtime.layoutRegistry.registerLayout(name,clazz);}};/**
- * CSSKeywordValue
- */var unsetKeywordValue=new CSSKeywordValue('unset');var initialKeywordValue=new CSSKeywordValue('initial');var inheritKeywordValue=new CSSKeywordValue('inherit');var keywordCache={'':unsetKeywordValue,unset:unsetKeywordValue,initial:initialKeywordValue,inherit:inheritKeywordValue};var getOrCreateKeyword=function getOrCreateKeyword(name){if(!keywordCache[name]){keywordCache[name]=new CSSKeywordValue(name);}return keywordCache[name];};/**
- * CSSColor
- */var noneColor=new CSSRGB(0,0,0,0,true);var transparentColor=new CSSRGB(0,0,0,0);var getOrCreateRGBA=memoize(function(r,g,b,a){return new CSSRGB(r,g,b,a);},function(r,g,b,a){return "rgba("+r+","+g+","+b+","+a+")";});// export const getOrCreateUnitValue = memoize(
- // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
- // return new CSSUnitValue(value, unitOrName);
- // },
- // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
- // return `${value}${unitOrName}`;
- // },
- // );
- var getOrCreateUnitValue=function getOrCreateUnitValue(value,unitOrName){if(unitOrName===void 0){unitOrName=exports.UnitType.kNumber;}return new CSSUnitValue(value,unitOrName);};var PECENTAGE_50=new CSSUnitValue(50,'%');var canvasMap={};var defaultCanvasIdCounter=0;/**
- * destroy existed canvas with the same id
- */function cleanExistedCanvas(container,canvas){if(container){var id=typeof container==='string'?container:container.id||defaultCanvasIdCounter++;if(canvasMap[id]){canvasMap[id].destroy();}canvasMap[id]=canvas;}}var isBrowser=typeof window!=='undefined'&&typeof window.document!=='undefined';function sortedIndex(array,value){var low=0;var high=array.length;while(low<high){var mid=low+high>>>1;if(sortByZIndex(array[mid],value)<0){low=mid+1;}else {high=mid;}}return low;}function sortByZIndex(o1,o2){var zIndex1=Number(o1.parsedStyle.zIndex);var zIndex2=Number(o2.parsedStyle.zIndex);if(zIndex1===zIndex2){var parent=o1.parentNode;if(parent){var children=parent.childNodes||[];return children.indexOf(o1)-children.indexOf(o2);}}return zIndex1-zIndex2;}function findClosestClipPathTarget(object){var el=object;do{var _el$parsedStyle;var clipPath=(_el$parsedStyle=el.parsedStyle)===null||_el$parsedStyle===void 0?void 0:_el$parsedStyle.clipPath;if(clipPath)return el;el=el.parentElement;}while(el!==null);return null;}var PX_SUFFIX='px';function setDOMSize($el,width,height){if(isBrowser&&$el.style){$el.style.width=width+PX_SUFFIX;$el.style.height=height+PX_SUFFIX;}}function getStyle($el,property){if(isBrowser){return document.defaultView.getComputedStyle($el,null).getPropertyValue(property);}}function getWidth($el){var width=getStyle($el,'width');if(width==='auto'){return $el.offsetWidth;}return parseFloat(width);}function getHeight($el){var height=getStyle($el,'height');if(height==='auto'){return $el.offsetHeight;}return parseFloat(height);}var ERROR_MSG_METHOD_NOT_IMPLEMENTED='Method not implemented.';var ERROR_MSG_USE_DOCUMENT_ELEMENT='Use document.documentElement instead.';var ERROR_MSG_APPEND_DESTROYED_ELEMENT='Cannot append a destroyed element.';// borrow from hammer.js
- var MOUSE_POINTER_ID=1;var TOUCH_TO_POINTER={touchstart:'pointerdown',touchend:'pointerup',touchendoutside:'pointerupoutside',touchmove:'pointermove',touchcancel:'pointercancel'};function copyVec3(a,b){a[0]=b[0];a[1]=b[1];a[2]=b[2];return a;}function subVec3(o,a,b){o[0]=a[0]-b[0];o[1]=a[1]-b[1];o[2]=a[2]-b[2];return o;}function addVec3(o,a,b){o[0]=a[0]+b[0];o[1]=a[1]+b[1];o[2]=a[2]+b[2];return o;}function scaleVec3(o,a,b){o[0]=a[0]*b;o[1]=a[1]*b;o[2]=a[2]*b;return o;}function maxVec3(o,a,b){o[0]=Math.max(a[0],b[0]);o[1]=Math.max(a[1],b[1]);o[2]=Math.max(a[2],b[2]);return o;}function minVec3(o,a,b){o[0]=Math.min(a[0],b[0]);o[1]=Math.min(a[1],b[1]);o[2]=Math.min(a[2],b[2]);return o;}function getAngle$1(angle){if(angle===undefined){return 0;}else if(angle>360||angle<-360){return angle%360;}return angle;}function createVec3(x,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(Array.isArray(x)&&x.length===3){return clone$1(x);}if(isNumber(x)){return fromValues$2(x,y,z);}return fromValues$2(x[0],x[1]||y,x[2]||z);}function deg2rad(deg){return deg*(Math.PI/180);}function rad2deg(rad){return rad*(180/Math.PI);}function grad2deg(grads){grads=grads%400;if(grads<0){grads+=400;}return grads/400*360;}function deg2turn(deg){return deg/360;}function turn2deg(turn){return 360*turn;}function getEulerFromQuat(out,quat){var x=quat[0];var y=quat[1];var z=quat[2];var w=quat[3];var x2=x*x;var y2=y*y;var z2=z*z;var w2=w*w;var unit=x2+y2+z2+w2;var test=x*w-y*z;if(test>0.499995*unit){// TODO: Use glmatrix.EPSILON
- // singularity at the north pole
- out[0]=Math.PI/2;out[1]=2*Math.atan2(y,x);out[2]=0;}else if(test<-0.499995*unit){//TODO: Use glmatrix.EPSILON
- // singularity at the south pole
- out[0]=-Math.PI/2;out[1]=2*Math.atan2(y,x);out[2]=0;}else {out[0]=Math.asin(2*(x*z-w*y));out[1]=Math.atan2(2*(x*w+y*z),1-2*(z2+w2));out[2]=Math.atan2(2*(x*y+z*w),1-2*(y2+z2));}// TODO: Return them as degrees and not as radians
- return out;}function getEulerFromMat4(out,m){var x;var z;var halfPi=Math.PI*0.5;var _mat4$getScaling=getScaling(create$2(),m),sx=_mat4$getScaling[0],sy=_mat4$getScaling[1],sz=_mat4$getScaling[2];var y=Math.asin(-m[2]/sx);if(y<halfPi){if(y>-halfPi){x=Math.atan2(m[6]/sy,m[10]/sz);z=Math.atan2(m[1]/sx,m[0]/sx);}else {// Not a unique solution
- z=0;x=-Math.atan2(m[4]/sy,m[5]/sy);}}else {// Not a unique solution
- z=0;x=Math.atan2(m[4]/sy,m[5]/sy);}out[0]=x;out[1]=y;out[2]=z;return out;}/**
- * @see https://github.com/toji/gl-matrix/issues/329
- * @see https://doc.babylonjs.com/divingDeeper/mesh/transforms/center_origin/rotation_conventions
- */function getEuler(out,quat){if(quat.length===16){return getEulerFromMat4(out,quat);}else {return getEulerFromQuat(out,quat);}}function fromRotationTranslationScale$1(rotation,x,y,scaleX,scaleY){var cos=Math.cos(rotation);var sin=Math.sin(rotation);return fromValues(scaleX*cos,scaleY*sin,0,-scaleX*sin,scaleY*cos,0,x,y,1);}function makePerspective(out,left,right,top,bottom,near,far){var x=2*near/(right-left);var y=2*near/(top-bottom);var a=(right+left)/(right-left);var b=(top+bottom)/(top-bottom);var c=-(far+near)/(far-near);var d=-2*far*near/(far-near);out[0]=x;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=y;out[6]=0;out[7]=0;out[8]=a;out[9]=b;out[10]=c;out[11]=-1;out[12]=0;out[13]=0;out[14]=d;out[15]=0;return out;}function decompose(mat){var row0x=mat[0];var row0y=mat[1];var row1x=mat[3];var row1y=mat[4];// decompose 3x3 matrix
- // @see https://www.w3.org/TR/css-transforms-1/#decomposing-a-2d-matrix
- var scalingX=Math.sqrt(row0x*row0x+row0y*row0y);var scalingY=Math.sqrt(row1x*row1x+row1y*row1y);// If determinant is negative, one axis was flipped.
- var determinant=row0x*row1y-row0y*row1x;if(determinant<0){// Flip axis with minimum unit vector dot product.
- if(row0x<row1y){scalingX=-scalingX;}else {scalingY=-scalingY;}}// Renormalize matrix to remove scale.
- if(scalingX){row0x*=1/scalingX;row0y*=1/scalingX;}if(scalingY){row1x*=1/scalingY;row1y*=1/scalingY;}// Compute rotation and renormalize matrix.
- var rotation=Math.atan2(row0y,row0x);var angle=rad2deg(rotation);return [mat[6],mat[7],scalingX,scalingY,angle];}var tmp=create$1();var perspectiveMatrix=create$1();var tmpVec4=create$3();var row=[create$2(),create$2(),create$2()];var pdum3=create$2();/*
- Input: matrix ; a 4x4 matrix
- Output: translation ; a 3 component vector
- scale ; a 3 component vector
- skew ; skew factors XY,XZ,YZ represented as a 3 component vector
- perspective ; a 4 component vector
- quaternion ; a 4 component vector
- Returns false if the matrix cannot be decomposed, true if it can
- References:
- https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
- https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
- http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
- */function decomposeMat4(matrix,translation,scale,skew,perspective,quaternion){//normalize, if not possible then bail out early
- if(!normalize$4(tmp,matrix))return false;// perspectiveMatrix is used to solve for perspective, but it also provides
- // an easy way to test for singularity of the upper 3x3 component.
- copy(perspectiveMatrix,tmp);perspectiveMatrix[3]=0;perspectiveMatrix[7]=0;perspectiveMatrix[11]=0;perspectiveMatrix[15]=1;// If the perspectiveMatrix is not invertible, we are also unable to
- // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
- if(Math.abs(determinant(perspectiveMatrix))<1e-8)return false;var a03=tmp[3],a13=tmp[7],a23=tmp[11],a30=tmp[12],a31=tmp[13],a32=tmp[14],a33=tmp[15];// First, isolate perspective.
- if(a03!==0||a13!==0||a23!==0){tmpVec4[0]=a03;tmpVec4[1]=a13;tmpVec4[2]=a23;tmpVec4[3]=a33;// Solve the equation by inverting perspectiveMatrix and multiplying
- // rightHandSide by the inverse.
- // resuing the perspectiveMatrix here since it's no longer needed
- var ret=invert(perspectiveMatrix,perspectiveMatrix);if(!ret)return false;transpose(perspectiveMatrix,perspectiveMatrix);//multiply by transposed inverse perspective matrix, into perspective vec4
- transformMat4$1(perspective,tmpVec4,perspectiveMatrix);}else {//no perspective
- perspective[0]=perspective[1]=perspective[2]=0;perspective[3]=1;}// Next take care of translation
- translation[0]=a30;translation[1]=a31;translation[2]=a32;// Now get scale and shear. 'row' is a 3 element array of 3 component vectors
- mat3from4(row,tmp);// Compute X scale factor and normalize first row.
- scale[0]=length(row[0]);normalize(row[0],row[0]);// Compute XY shear factor and make 2nd row orthogonal to 1st.
- skew[0]=dot(row[0],row[1]);combine(row[1],row[1],row[0],1.0,-skew[0]);// Now, compute Y scale and normalize 2nd row.
- scale[1]=length(row[1]);normalize(row[1],row[1]);skew[0]/=scale[1];// Compute XZ and YZ shears, orthogonalize 3rd row
- skew[1]=dot(row[0],row[2]);combine(row[2],row[2],row[0],1.0,-skew[1]);skew[2]=dot(row[1],row[2]);combine(row[2],row[2],row[1],1.0,-skew[2]);// Next, get Z scale and normalize 3rd row.
- scale[2]=length(row[2]);normalize(row[2],row[2]);skew[1]/=scale[2];skew[2]/=scale[2];// At this point, the matrix (in rows) is orthonormal.
- // Check for a coordinate system flip. If the determinant
- // is -1, then negate the matrix and the scaling factors.
- cross(pdum3,row[1],row[2]);if(dot(row[0],pdum3)<0){for(var i=0;i<3;i++){scale[i]*=-1;row[i][0]*=-1;row[i][1]*=-1;row[i][2]*=-1;}}// Now, get the rotations out
- quaternion[0]=0.5*Math.sqrt(Math.max(1+row[0][0]-row[1][1]-row[2][2],0));quaternion[1]=0.5*Math.sqrt(Math.max(1-row[0][0]+row[1][1]-row[2][2],0));quaternion[2]=0.5*Math.sqrt(Math.max(1-row[0][0]-row[1][1]+row[2][2],0));quaternion[3]=0.5*Math.sqrt(Math.max(1+row[0][0]+row[1][1]+row[2][2],0));if(row[2][1]>row[1][2])quaternion[0]=-quaternion[0];if(row[0][2]>row[2][0])quaternion[1]=-quaternion[1];if(row[1][0]>row[0][1])quaternion[2]=-quaternion[2];return true;}function normalize$4(out,mat){var m44=mat[15];// Cannot normalize.
- if(m44===0)return false;var scale=1/m44;for(var i=0;i<16;i++)out[i]=mat[i]*scale;return true;}//gets upper-left of a 4x4 matrix into a 3x3 of vectors
- function mat3from4(out,mat4x4){out[0][0]=mat4x4[0];out[0][1]=mat4x4[1];out[0][2]=mat4x4[2];out[1][0]=mat4x4[4];out[1][1]=mat4x4[5];out[1][2]=mat4x4[6];out[2][0]=mat4x4[8];out[2][1]=mat4x4[9];out[2][2]=mat4x4[10];}function combine(out,a,b,scale1,scale2){out[0]=a[0]*scale1+b[0]*scale2;out[1]=a[1]*scale1+b[1]*scale2;out[2]=a[2]*scale1+b[2]*scale2;}var tmpMat4=create$1();function parsedTransformToMat4(transform,object){if(transform&&transform.length){var defX=0;var defY=0;if(object){defX=object.parsedStyle.defX||0;defY=object.parsedStyle.defY||0;// reset transform
- object.resetLocalTransform();object.setLocalPosition(defX,defY);}else {object=new DisplayObject({});}transform.forEach(function(parsed){var t=parsed.t,d=parsed.d;if(t==='scale'){// scale(1) scale(1, 1)
- var newScale=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[1,1];object.scaleLocal(newScale[0],newScale[1],1);}else if(t==='scalex'){var _newScale=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[1];object.scaleLocal(_newScale[0],1,1);}else if(t==='scaley'){var _newScale2=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[1];object.scaleLocal(1,_newScale2[0],1);}else if(t==='scalez'){var _newScale3=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[1];object.scaleLocal(1,1,_newScale3[0]);}else if(t==='scale3d'){var _newScale4=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[1,1,1];object.scaleLocal(_newScale4[0],_newScale4[1],_newScale4[2]);}else if(t==='translate'){var newTranslation=d||[Opx,Opx];object.translateLocal(newTranslation[0].value,newTranslation[1].value,0);}else if(t==='translatex'){var _newTranslation=d||[Opx];object.translateLocal(_newTranslation[0].value,0,0);}else if(t==='translatey'){var _newTranslation2=d||[Opx];object.translateLocal(0,_newTranslation2[0].value,0);}else if(t==='translatez'){var _newTranslation3=d||[Opx];object.translateLocal(0,0,_newTranslation3[0].value);}else if(t==='translate3d'){var _newTranslation4=d||[Opx,Opx,Opx];object.translateLocal(_newTranslation4[0].value,_newTranslation4[1].value,_newTranslation4[2].value);}else if(t==='rotate'){var newAngles=d||[Odeg];object.rotateLocal(0,0,convertAngleUnit(newAngles[0]));}else if(t==='rotatex'){var _newAngles=d||[Odeg];object.rotateLocal(convertAngleUnit(_newAngles[0]),0,0);}else if(t==='rotatey'){var _newAngles2=d||[Odeg];object.rotateLocal(0,convertAngleUnit(_newAngles2[0]),0);}else if(t==='rotatez'){var _newAngles3=d||[Odeg];object.rotateLocal(0,0,convertAngleUnit(_newAngles3[0]));}else if(t==='rotate3d');else if(t==='skew'){var newSkew=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[0,0];object.setLocalSkew(deg2rad(newSkew[0]),deg2rad(newSkew[1]));}else if(t==='skewx'){var _newSkew=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[0];object.setLocalSkew(deg2rad(_newSkew[0]),object.getLocalSkew()[1]);}else if(t==='skewy'){var _newSkew2=(d===null||d===void 0?void 0:d.map(function(s){return s.value;}))||[0];object.setLocalSkew(object.getLocalSkew()[0],deg2rad(_newSkew2[0]));}else if(t==='matrix'){var _d$map=d.map(function(s){return s.value;}),a=_d$map[0],b=_d$map[1],c=_d$map[2],dd=_d$map[3],tx=_d$map[4],ty=_d$map[5];object.setLocalTransform(set(tmpMat4,a,b,0,0,c,dd,0,0,0,0,1,0,tx+defX,ty+defY,0,1));}else if(t==='matrix3d'){// @ts-ignore
- set.apply(mat4,[tmpMat4].concat(d.map(function(s){return s.value;})));tmpMat4[12]+=defX;tmpMat4[13]+=defY;object.setLocalTransform(tmpMat4);}});}return object.getLocalTransform();}/**
- * borrow from gradient-parser, but we delete some browser compatible prefix such as `-webkit-`
- * @see https://github.com/rafaelcaricio/gradient-parser
- */function colorStopToString(colorStop){var type=colorStop.type,value=colorStop.value;if(type==='hex'){return "#"+value;}else if(type==='literal'){return value;}else if(type==='rgb'){return "rgb("+value.join(',')+")";}else {return "rgba("+value.join(',')+")";}}var parseGradient=function(){var tokens={linearGradient:/^(linear\-gradient)/i,repeatingLinearGradient:/^(repeating\-linear\-gradient)/i,radialGradient:/^(radial\-gradient)/i,repeatingRadialGradient:/^(repeating\-radial\-gradient)/i,/**
- * @see https://projects.verou.me/conic-gradient/
- */conicGradient:/^(conic\-gradient)/i,sideOrCorner:/^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,extentKeywords:/^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,positionKeywords:/^(left|center|right|top|bottom)/i,pixelValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,percentageValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,emValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,angleValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,startCall:/^\(/,endCall:/^\)/,comma:/^,/,hexColor:/^\#([0-9a-fA-F]+)/,literalColor:/^([a-zA-Z]+)/,rgbColor:/^rgb/i,rgbaColor:/^rgba/i,number:/^(([0-9]*\.[0-9]+)|([0-9]+\.?))/};var input='';function error(msg){throw new Error(input+': '+msg);}function getAST(){var ast=matchListDefinitions();if(input.length>0){error('Invalid input not EOF');}return ast;}function matchListDefinitions(){return matchListing(matchDefinition);}function matchDefinition(){return matchGradient('linear-gradient',tokens.linearGradient,matchLinearOrientation)||matchGradient('repeating-linear-gradient',tokens.repeatingLinearGradient,matchLinearOrientation)||matchGradient('radial-gradient',tokens.radialGradient,matchListRadialOrientations)||matchGradient('repeating-radial-gradient',tokens.repeatingRadialGradient,matchListRadialOrientations)||matchGradient('conic-gradient',tokens.conicGradient,matchListRadialOrientations);}function matchGradient(gradientType,pattern,orientationMatcher){return matchCall(pattern,function(captures){var orientation=orientationMatcher();if(orientation){if(!scan(tokens.comma)){error('Missing comma before color stops');}}return {type:gradientType,orientation:orientation,colorStops:matchListing(matchColorStop)};});}function matchCall(pattern,callback){var captures=scan(pattern);if(captures){if(!scan(tokens.startCall)){error('Missing (');}var result=callback(captures);if(!scan(tokens.endCall)){error('Missing )');}return result;}}function matchLinearOrientation(){return matchSideOrCorner()||matchAngle();}function matchSideOrCorner(){return match('directional',tokens.sideOrCorner,1);}function matchAngle(){return match('angular',tokens.angleValue,1);}function matchListRadialOrientations(){var radialOrientations,radialOrientation=matchRadialOrientation(),lookaheadCache;if(radialOrientation){radialOrientations=[];radialOrientations.push(radialOrientation);lookaheadCache=input;if(scan(tokens.comma)){radialOrientation=matchRadialOrientation();if(radialOrientation){radialOrientations.push(radialOrientation);}else {input=lookaheadCache;}}}return radialOrientations;}function matchRadialOrientation(){var radialType=matchCircle()||matchEllipse();if(radialType){// @ts-ignore
- radialType.at=matchAtPosition();}else {var extent=matchExtentKeyword();if(extent){radialType=extent;var positionAt=matchAtPosition();if(positionAt){// @ts-ignore
- radialType.at=positionAt;}}else {var defaultPosition=matchPositioning();if(defaultPosition){radialType={type:'default-radial',// @ts-ignore
- at:defaultPosition};}}}return radialType;}function matchCircle(){var circle=match('shape',/^(circle)/i,0);if(circle){// @ts-ignore
- circle.style=matchLength()||matchExtentKeyword();}return circle;}function matchEllipse(){var ellipse=match('shape',/^(ellipse)/i,0);if(ellipse){// @ts-ignore
- ellipse.style=matchDistance()||matchExtentKeyword();}return ellipse;}function matchExtentKeyword(){return match('extent-keyword',tokens.extentKeywords,1);}function matchAtPosition(){if(match('position',/^at/,0)){var positioning=matchPositioning();if(!positioning){error('Missing positioning value');}return positioning;}}function matchPositioning(){var location=matchCoordinates();if(location.x||location.y){return {type:'position',value:location};}}function matchCoordinates(){return {x:matchDistance(),y:matchDistance()};}function matchListing(matcher){var captures=matcher();var result=[];if(captures){result.push(captures);while(scan(tokens.comma)){captures=matcher();if(captures){result.push(captures);}else {error('One extra comma');}}}return result;}function matchColorStop(){var color=matchColor();if(!color){error('Expected color definition');}color.length=matchDistance();return color;}function matchColor(){return matchHexColor()||matchRGBAColor()||matchRGBColor()||matchLiteralColor();}function matchLiteralColor(){return match('literal',tokens.literalColor,0);}function matchHexColor(){return match('hex',tokens.hexColor,1);}function matchRGBColor(){return matchCall(tokens.rgbColor,function(){return {type:'rgb',value:matchListing(matchNumber)};});}function matchRGBAColor(){return matchCall(tokens.rgbaColor,function(){return {type:'rgba',value:matchListing(matchNumber)};});}function matchNumber(){return scan(tokens.number)[1];}function matchDistance(){return match('%',tokens.percentageValue,1)||matchPositionKeyword()||matchLength();}function matchPositionKeyword(){return match('position-keyword',tokens.positionKeywords,1);}function matchLength(){return match('px',tokens.pixelValue,1)||match('em',tokens.emValue,1);}function match(type,pattern,captureIndex){var captures=scan(pattern);if(captures){return {type:type,value:captures[captureIndex]};}}function scan(regexp){var blankCaptures=/^[\n\r\t\s]+/.exec(input);if(blankCaptures){consume(blankCaptures[0].length);}var captures=regexp.exec(input);if(captures){consume(captures[0].length);}return captures;}function consume(size){input=input.substring(size);}return function(code){input=code;return getAST();};}();function computeLinearGradient(width,height,angle){var rad=deg2rad(angle.value);var rx=0;var ry=0;var rcx=rx+width/2;var rcy=ry+height/2;// get the length of gradient line
- // @see https://observablehq.com/@danburzo/css-gradient-line
- var length=Math.abs(width*Math.cos(rad))+Math.abs(height*Math.sin(rad));var x1=rcx-Math.cos(rad)*length/2;var y1=rcy-Math.sin(rad)*length/2;var x2=rcx+Math.cos(rad)*length/2;var y2=rcy+Math.sin(rad)*length/2;return {x1:x1,y1:y1,x2:x2,y2:y2};}function computeRadialGradient(width,height,cx,cy,size){// 'px'
- var x=cx.value;var y=cy.value;// TODO: 'em'
- // '%'
- if(cx.unit===exports.UnitType.kPercentage){x=cx.value/100*width;}if(cy.unit===exports.UnitType.kPercentage){y=cy.value/100*height;}// default to farthest-side
- var r=Math.max(distanceSquareRoot([0,0],[x,y]),distanceSquareRoot([0,height],[x,y]),distanceSquareRoot([width,height],[x,y]),distanceSquareRoot([width,0],[x,y]));if(size){if(size instanceof CSSUnitValue){r=size.value;}else if(size instanceof CSSKeywordValue){// @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Images/Using_CSS_gradients#example_closest-side_for_circles
- if(size.value==='closest-side'){r=Math.min(x,width-x,y,height-y);}else if(size.value==='farthest-side'){r=Math.max(x,width-x,y,height-y);}else if(size.value==='closest-corner'){r=Math.min(distanceSquareRoot([0,0],[x,y]),distanceSquareRoot([0,height],[x,y]),distanceSquareRoot([width,height],[x,y]),distanceSquareRoot([width,0],[x,y]));}}}return {x:x,y:y,r:r};}(function(Shape){Shape["GROUP"]="g";Shape["CIRCLE"]="circle";Shape["ELLIPSE"]="ellipse";Shape["IMAGE"]="image";Shape["RECT"]="rect";Shape["LINE"]="line";Shape["POLYLINE"]="polyline";Shape["POLYGON"]="polygon";Shape["TEXT"]="text";Shape["PATH"]="path";Shape["HTML"]="html";Shape["MESH"]="mesh";})(exports.Shape||(exports.Shape={}));function getOrCalculatePathTotalLength(path){if(path.parsedStyle.path.totalLength===0){path.parsedStyle.path.totalLength=getTotalLength(path.parsedStyle.path.absolutePath);}return path.parsedStyle.path.totalLength;}function hasArcOrBezier(path){var hasArc=false;var count=path.length;for(var i=0;i<count;i++){var params=path[i];var cmd=params[0];if(cmd==='C'||cmd==='A'||cmd==='Q'){hasArc=true;break;}}return hasArc;}function extractPolygons(pathArray){var polygons=[];var polylines=[];var points=[];// 防止第一个命令不是 'M'
- for(var i=0;i<pathArray.length;i++){var params=pathArray[i];var cmd=params[0];if(cmd==='M'){// 遇到 'M' 判定是否是新数组,新数组中没有点
- if(points.length){// 如果存在点,则说明没有遇到 'Z',开始了一个新的多边形
- polylines.push(points);points=[];// 创建新的点
- }points.push([params[1],params[2]]);}else if(cmd==='Z'){if(points.length){// 存在点
- polygons.push(points);points=[];// 开始新的点集合
- }// 如果不存在点,同时 'Z',则说明是错误,不处理
- }else {points.push([params[1],params[2]]);}}// 说明 points 未放入 polygons 或者 polyline
- // 仅当只有一个 M,没有 Z 时会发生这种情况
- if(points.length>0){polylines.push(points);}return {polygons:polygons,polylines:polylines};}function isSamePoint(point1,point2){return point1[0]===point2[0]&&point1[1]===point2[1];}function getPathBBox(segments,lineWidth){var xArr=[];var yArr=[];var segmentsWithAngle=[];for(var i=0;i<segments.length;i++){var segment=segments[i];var currentPoint=segment.currentPoint,params=segment.params,prePoint=segment.prePoint;var box=void 0;switch(segment.command){case'Q':box=quadratic.box(prePoint[0],prePoint[1],params[1],params[2],params[3],params[4]);break;case'C':box=cubic.box(prePoint[0],prePoint[1],params[1],params[2],params[3],params[4],params[5],params[6]);break;case'A':var arcParams=segment.arcParams;box=arc.box(arcParams.cx,arcParams.cy,arcParams.rx,arcParams.ry,arcParams.xRotation,arcParams.startAngle,arcParams.endAngle);break;default:xArr.push(currentPoint[0]);yArr.push(currentPoint[1]);break;}if(box){segment.box=box;xArr.push(box.x,box.x+box.width);yArr.push(box.y,box.y+box.height);}if(lineWidth&&(segment.command==='L'||segment.command==='M')&&segment.prePoint&&segment.nextPoint){segmentsWithAngle.push(segment);}}// bbox calculation should ignore NaN for path attribute
- // ref: https://github.com/antvis/g/issues/210
- // ref: https://github.com/antvis/G2/issues/3109
- xArr=xArr.filter(function(item){return !Number.isNaN(item)&&item!==Infinity&&item!==-Infinity;});yArr=yArr.filter(function(item){return !Number.isNaN(item)&&item!==Infinity&&item!==-Infinity;});var minX=min(xArr);var minY=min(yArr);var maxX=max(xArr);var maxY=max(yArr);if(segmentsWithAngle.length===0){return {x:minX,y:minY,width:maxX-minX,height:maxY-minY};}for(var _i=0;_i<segmentsWithAngle.length;_i++){var _segment=segmentsWithAngle[_i];var _currentPoint=_segment.currentPoint;var extra=void 0;if(_currentPoint[0]===minX){extra=getExtraFromSegmentWithAngle(_segment,lineWidth);minX=minX-extra.xExtra;}else if(_currentPoint[0]===maxX){extra=getExtraFromSegmentWithAngle(_segment,lineWidth);maxX=maxX+extra.xExtra;}if(_currentPoint[1]===minY){extra=getExtraFromSegmentWithAngle(_segment,lineWidth);minY=minY-extra.yExtra;}else if(_currentPoint[1]===maxY){extra=getExtraFromSegmentWithAngle(_segment,lineWidth);maxY=maxY+extra.yExtra;}}return {x:minX,y:minY,width:maxX-minX,height:maxY-minY};}function getExtraFromSegmentWithAngle(segment,lineWidth){var prePoint=segment.prePoint,currentPoint=segment.currentPoint,nextPoint=segment.nextPoint;var currentAndPre=Math.pow(currentPoint[0]-prePoint[0],2)+Math.pow(currentPoint[1]-prePoint[1],2);var currentAndNext=Math.pow(currentPoint[0]-nextPoint[0],2)+Math.pow(currentPoint[1]-nextPoint[1],2);var preAndNext=Math.pow(prePoint[0]-nextPoint[0],2)+Math.pow(prePoint[1]-nextPoint[1],2);// 以 currentPoint 为顶点的夹角
- var currentAngle=Math.acos((currentAndPre+currentAndNext-preAndNext)/(2*Math.sqrt(currentAndPre)*Math.sqrt(currentAndNext)));// 夹角为空、 0 或 PI 时,不需要计算夹角处的额外宽度
- // 注意: 由于计算精度问题,夹角为 0 的情况计算出来的角度可能是一个很小的值,还需要判断其与 0 是否近似相等
- if(!currentAngle||Math.sin(currentAngle)===0||isNumberEqual(currentAngle,0)){return {xExtra:0,yExtra:0};}var xAngle=Math.abs(Math.atan2(nextPoint[1]-currentPoint[1],nextPoint[0]-currentPoint[0]));var yAngle=Math.abs(Math.atan2(nextPoint[0]-currentPoint[0],nextPoint[1]-currentPoint[1]));// 将夹角转为锐角
- xAngle=xAngle>Math.PI/2?Math.PI-xAngle:xAngle;yAngle=yAngle>Math.PI/2?Math.PI-yAngle:yAngle;// 这里不考虑在水平和垂直方向的投影,直接使用最大差值
- // 由于上层统一加减了二分之一线宽,这里需要进行弥补
- var extra={// 水平方向投影
- xExtra:Math.cos(currentAngle/2-xAngle)*(lineWidth/2*(1/Math.sin(currentAngle/2)))-lineWidth/2||0,// 垂直方向投影
- yExtra:Math.cos(yAngle-currentAngle/2)*(lineWidth/2*(1/Math.sin(currentAngle/2)))-lineWidth/2||0};return extra;}// 点对称
- function toSymmetry(point,center){return [center[0]+(center[0]-point[0]),center[1]+(center[1]-point[1])];}var angleBetween$1=function angleBetween(v0,v1){var p=v0.x*v1.x+v0.y*v1.y;var n=Math.sqrt((Math.pow(v0.x,2)+Math.pow(v0.y,2))*(Math.pow(v1.x,2)+Math.pow(v1.y,2)));var sign=v0.x*v1.y-v0.y*v1.x<0?-1:1;var angle=sign*Math.acos(p/n);return angle;};/**
- * @see https://github.com/rveciana/svg-path-properties/blob/b6bd9a322966f6ef7a311872d80c56e3718de861/src/arc.ts#L121
- */var pointOnEllipticalArc=function pointOnEllipticalArc(p0,rx,ry,xAxisRotation,largeArcFlag,sweepFlag,p1,t){// In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
- rx=Math.abs(rx);ry=Math.abs(ry);xAxisRotation=mod(xAxisRotation,360);var xAxisRotationRadians=deg2rad(xAxisRotation);// If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
- if(p0.x===p1.x&&p0.y===p1.y){return {x:p0.x,y:p0.y,ellipticalArcAngle:0};// Check if angle is correct
- }// If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
- if(rx===0||ry===0){//return this.pointOnLine(p0, p1, t);
- return {x:0,y:0,ellipticalArcAngle:0};// Check if angle is correct
- }// Following "Conversion from endpoint to center parameterization"
- // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
- // Step #1: Compute transformedPoint
- var dx=(p0.x-p1.x)/2;var dy=(p0.y-p1.y)/2;var transformedPoint={x:Math.cos(xAxisRotationRadians)*dx+Math.sin(xAxisRotationRadians)*dy,y:-Math.sin(xAxisRotationRadians)*dx+Math.cos(xAxisRotationRadians)*dy};// Ensure radii are large enough
- var radiiCheck=Math.pow(transformedPoint.x,2)/Math.pow(rx,2)+Math.pow(transformedPoint.y,2)/Math.pow(ry,2);if(radiiCheck>1){rx=Math.sqrt(radiiCheck)*rx;ry=Math.sqrt(radiiCheck)*ry;}// Step #2: Compute transformedCenter
- var cSquareNumerator=Math.pow(rx,2)*Math.pow(ry,2)-Math.pow(rx,2)*Math.pow(transformedPoint.y,2)-Math.pow(ry,2)*Math.pow(transformedPoint.x,2);var cSquareRootDenom=Math.pow(rx,2)*Math.pow(transformedPoint.y,2)+Math.pow(ry,2)*Math.pow(transformedPoint.x,2);var cRadicand=cSquareNumerator/cSquareRootDenom;// Make sure this never drops below zero because of precision
- cRadicand=cRadicand<0?0:cRadicand;var cCoef=(largeArcFlag!==sweepFlag?1:-1)*Math.sqrt(cRadicand);var transformedCenter={x:cCoef*(rx*transformedPoint.y/ry),y:cCoef*(-(ry*transformedPoint.x)/rx)};// Step #3: Compute center
- var center={x:Math.cos(xAxisRotationRadians)*transformedCenter.x-Math.sin(xAxisRotationRadians)*transformedCenter.y+(p0.x+p1.x)/2,y:Math.sin(xAxisRotationRadians)*transformedCenter.x+Math.cos(xAxisRotationRadians)*transformedCenter.y+(p0.y+p1.y)/2};// Step #4: Compute start/sweep angles
- // Start angle of the elliptical arc prior to the stretch and rotate operations.
- // Difference between the start and end angles
- var startVector={x:(transformedPoint.x-transformedCenter.x)/rx,y:(transformedPoint.y-transformedCenter.y)/ry};var startAngle=angleBetween$1({x:1,y:0},startVector);var endVector={x:(-transformedPoint.x-transformedCenter.x)/rx,y:(-transformedPoint.y-transformedCenter.y)/ry};var sweepAngle=angleBetween$1(startVector,endVector);if(!sweepFlag&&sweepAngle>0){sweepAngle-=2*Math.PI;}else if(sweepFlag&&sweepAngle<0){sweepAngle+=2*Math.PI;}// We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
- sweepAngle%=2*Math.PI;// From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
- var angle=startAngle+sweepAngle*t;var ellipseComponentX=rx*Math.cos(angle);var ellipseComponentY=ry*Math.sin(angle);var point={x:Math.cos(xAxisRotationRadians)*ellipseComponentX-Math.sin(xAxisRotationRadians)*ellipseComponentY+center.x,y:Math.sin(xAxisRotationRadians)*ellipseComponentX+Math.cos(xAxisRotationRadians)*ellipseComponentY+center.y,ellipticalArcStartAngle:startAngle,ellipticalArcEndAngle:startAngle+sweepAngle,ellipticalArcAngle:angle,ellipticalArcCenter:center,resultantRx:rx,resultantRy:ry};return point;};function path2Segments(path){var segments=[];var currentPoint=null;// 当前图形
- var nextParams=null;// 下一节点的 path 参数
- var startMovePoint=null;// 开始 M 的点,可能会有多个
- var lastStartMovePointIndex=0;// 最近一个开始点 M 的索引
- var count=path.length;for(var i=0;i<count;i++){var params=path[i];nextParams=path[i+1];var command=params[0];// 数学定义上的参数,便于后面的计算
- var segment={command:command,prePoint:currentPoint,params:params,startTangent:null,endTangent:null,currentPoint:null,nextPoint:null,arcParams:null,box:null,cubicParams:null};switch(command){case'M':startMovePoint=[params[1],params[2]];lastStartMovePointIndex=i;break;case'A':var arcParams=getArcParams(currentPoint,params);segment.arcParams=arcParams;break;}if(command==='Z'){// 有了 Z 后,当前节点从开始 M 的点开始
- currentPoint=startMovePoint;// 如果当前点的命令为 Z,相当于当前点为最近一个 M 点,则下一个点直接指向最近一个 M 点的下一个点
- nextParams=path[lastStartMovePointIndex+1];}else {var len=params.length;currentPoint=[params[len-2],params[len-1]];}if(nextParams&&nextParams[0]==='Z'){// 如果下一个点的命令为 Z,则下一个点直接指向最近一个 M 点
- nextParams=path[lastStartMovePointIndex];if(segments[lastStartMovePointIndex]){// 如果下一个点的命令为 Z,则最近一个 M 点的前一个点为当前点
- segments[lastStartMovePointIndex].prePoint=currentPoint;}}segment.currentPoint=currentPoint;// 如果当前点与最近一个 M 点相同,则最近一个 M 点的前一个点为当前点的前一个点
- if(segments[lastStartMovePointIndex]&&isSamePoint(currentPoint,segments[lastStartMovePointIndex].currentPoint)){segments[lastStartMovePointIndex].prePoint=segment.prePoint;}var nextPoint=nextParams?[nextParams[nextParams.length-2],nextParams[nextParams.length-1]]:null;segment.nextPoint=nextPoint;// Add startTangent and endTangent
- var prePoint=segment.prePoint;if(['L','H','V'].includes(command)){segment.startTangent=[prePoint[0]-currentPoint[0],prePoint[1]-currentPoint[1]];segment.endTangent=[currentPoint[0]-prePoint[0],currentPoint[1]-prePoint[1]];}else if(command==='Q'){// 二次贝塞尔曲线只有一个控制点
- var cp=[params[1],params[2]];// 二次贝塞尔曲线的终点为 currentPoint
- segment.startTangent=[prePoint[0]-cp[0],prePoint[1]-cp[1]];segment.endTangent=[currentPoint[0]-cp[0],currentPoint[1]-cp[1]];}else if(command==='T'){var preSegment=segments[i-1];var _cp=toSymmetry(preSegment.currentPoint,prePoint);if(preSegment.command==='Q'){segment.command='Q';segment.startTangent=[prePoint[0]-_cp[0],prePoint[1]-_cp[1]];segment.endTangent=[currentPoint[0]-_cp[0],currentPoint[1]-_cp[1]];}else {// @ts-ignore
- segment.command='TL';segment.startTangent=[prePoint[0]-currentPoint[0],prePoint[1]-currentPoint[1]];segment.endTangent=[currentPoint[0]-prePoint[0],currentPoint[1]-prePoint[1]];}}else if(command==='C'){// 三次贝塞尔曲线有两个控制点
- var cp1=[params[1],params[2]];var cp2=[params[3],params[4]];segment.startTangent=[prePoint[0]-cp1[0],prePoint[1]-cp1[1]];segment.endTangent=[currentPoint[0]-cp2[0],currentPoint[1]-cp2[1]];// horizontal line, eg. ['C', 100, 100, 100, 100, 200, 200]
- if(segment.startTangent[0]===0&&segment.startTangent[1]===0){segment.startTangent=[cp1[0]-cp2[0],cp1[1]-cp2[1]];}if(segment.endTangent[0]===0&&segment.endTangent[1]===0){segment.endTangent=[cp2[0]-cp1[0],cp2[1]-cp1[1]];}}else if(command==='S'){var _preSegment=segments[i-1];var _cp2=toSymmetry(_preSegment.currentPoint,prePoint);var _cp3=[params[1],params[2]];if(_preSegment.command==='C'){segment.command='C';// 将 S 命令变换为 C 命令
- segment.startTangent=[prePoint[0]-_cp2[0],prePoint[1]-_cp2[1]];segment.endTangent=[currentPoint[0]-_cp3[0],currentPoint[1]-_cp3[1]];}else {// @ts-ignore
- segment.command='SQ';// 将 S 命令变换为 SQ 命令
- segment.startTangent=[prePoint[0]-_cp3[0],prePoint[1]-_cp3[1]];segment.endTangent=[currentPoint[0]-_cp3[0],currentPoint[1]-_cp3[1]];}}else if(command==='A'){var _getTangentAtRatio=getTangentAtRatio(segment,0),dx1=_getTangentAtRatio.x,dy1=_getTangentAtRatio.y;var _getTangentAtRatio2=getTangentAtRatio(segment,1,false),dx2=_getTangentAtRatio2.x,dy2=_getTangentAtRatio2.y;segment.startTangent=[dx1,dy1];segment.endTangent=[dx2,dy2];}segments.push(segment);}return segments;}/**
- * Use length instead of ratio
- */function getTangentAtRatio(segment,ratio,sign){if(sign===void 0){sign=true;}var _segment$arcParams=segment.arcParams,_segment$arcParams$rx=_segment$arcParams.rx,rx=_segment$arcParams$rx===void 0?0:_segment$arcParams$rx,_segment$arcParams$ry=_segment$arcParams.ry,ry=_segment$arcParams$ry===void 0?0:_segment$arcParams$ry,xRotation=_segment$arcParams.xRotation,arcFlag=_segment$arcParams.arcFlag,sweepFlag=_segment$arcParams.sweepFlag;var p1=pointOnEllipticalArc({x:segment.prePoint[0],y:segment.prePoint[1]},rx,ry,xRotation,!!arcFlag,!!sweepFlag,{x:segment.currentPoint[0],y:segment.currentPoint[1]},ratio);var p2=pointOnEllipticalArc({x:segment.prePoint[0],y:segment.prePoint[1]},rx,ry,xRotation,!!arcFlag,!!sweepFlag,{x:segment.currentPoint[0],y:segment.currentPoint[1]},sign?ratio+0.005:ratio-0.005);var xDist=p2.x-p1.x;var yDist=p2.y-p1.y;var dist=Math.sqrt(xDist*xDist+yDist*yDist);return {x:-xDist/dist,y:-yDist/dist};}// 向量长度
- function vMag(v){return Math.sqrt(v[0]*v[0]+v[1]*v[1]);}// u.v/|u||v|,计算夹角的余弦值
- function vRatio(u,v){// 当存在一个向量的长度为 0 时,夹角也为 0,即夹角的余弦值为 1
- return vMag(u)*vMag(v)?(u[0]*v[0]+u[1]*v[1])/(vMag(u)*vMag(v)):1;}// 向量角度
- function vAngle(u,v){return (u[0]*v[1]<u[1]*v[0]?-1:1)*Math.acos(vRatio(u,v));}function getArcParams(startPoint,params){var rx=params[1];var ry=params[2];var xRotation=mod(deg2rad(params[3]),Math.PI*2);var arcFlag=params[4];var sweepFlag=params[5];// 弧形起点坐标
- var x1=startPoint[0];var y1=startPoint[1];// 弧形终点坐标
- var x2=params[6];var y2=params[7];var xp=Math.cos(xRotation)*(x1-x2)/2.0+Math.sin(xRotation)*(y1-y2)/2.0;var yp=-1*Math.sin(xRotation)*(x1-x2)/2.0+Math.cos(xRotation)*(y1-y2)/2.0;var lambda=xp*xp/(rx*rx)+yp*yp/(ry*ry);if(lambda>1){rx*=Math.sqrt(lambda);ry*=Math.sqrt(lambda);}var diff=rx*rx*(yp*yp)+ry*ry*(xp*xp);var f=diff?Math.sqrt((rx*rx*(ry*ry)-diff)/diff):1;if(arcFlag===sweepFlag){f*=-1;}if(isNaN(f)){f=0;}// 旋转前的起点坐标,且当长半轴和短半轴的长度为 0 时,坐标按 (0, 0) 处理
- var cxp=ry?f*rx*yp/ry:0;var cyp=rx?f*-ry*xp/rx:0;// 椭圆圆心坐标
- var cx=(x1+x2)/2.0+Math.cos(xRotation)*cxp-Math.sin(xRotation)*cyp;var cy=(y1+y2)/2.0+Math.sin(xRotation)*cxp+Math.cos(xRotation)*cyp;// 起始点的单位向量
- var u=[(xp-cxp)/rx,(yp-cyp)/ry];// 终止点的单位向量
- var v=[(-1*xp-cxp)/rx,(-1*yp-cyp)/ry];// 计算起始点和圆心的连线,与 x 轴正方向的夹角
- var theta=vAngle([1,0],u);// 计算圆弧起始点和终止点与椭圆圆心连线的夹角
- var dTheta=vAngle(u,v);if(vRatio(u,v)<=-1){dTheta=Math.PI;}if(vRatio(u,v)>=1){dTheta=0;}if(sweepFlag===0&&dTheta>0){dTheta=dTheta-2*Math.PI;}if(sweepFlag===1&&dTheta<0){dTheta=dTheta+2*Math.PI;}return {cx:cx,cy:cy,// 弧形的起点和终点相同时,长轴和短轴的长度按 0 处理
- rx:isSamePoint(startPoint,[x2,y2])?0:rx,ry:isSamePoint(startPoint,[x2,y2])?0:ry,startAngle:theta,endAngle:theta+dTheta,xRotation:xRotation,arcFlag:arcFlag,sweepFlag:sweepFlag};}function commandsToPathString(commands,object,transform){var _object$parsedStyle=object.parsedStyle,_object$parsedStyle$d=_object$parsedStyle.defX,defX=_object$parsedStyle$d===void 0?0:_object$parsedStyle$d,_object$parsedStyle$d2=_object$parsedStyle.defY,defY=_object$parsedStyle$d2===void 0?0:_object$parsedStyle$d2;return commands.reduce(function(prev,cur){var path='';if(cur[0]==='M'||cur[0]==='L'){var p=fromValues$2(cur[1]-defX,cur[2]-defY,0);if(transform){transformMat4(p,p,transform);}path=""+cur[0]+p[0]+","+p[1];}else if(cur[0]==='Z'){path=cur[0];}else if(cur[0]==='C'){var p1=fromValues$2(cur[1]-defX,cur[2]-defY,0);var p2=fromValues$2(cur[3]-defX,cur[4]-defY,0);var p3=fromValues$2(cur[5]-defX,cur[6]-defY,0);if(transform){transformMat4(p1,p1,transform);transformMat4(p2,p2,transform);transformMat4(p3,p3,transform);}path=""+cur[0]+p1[0]+","+p1[1]+","+p2[0]+","+p2[1]+","+p3[0]+","+p3[1];}else if(cur[0]==='A'){var c=fromValues$2(cur[6]-defX,cur[7]-defY,0);if(transform){transformMat4(c,c,transform);}path=""+cur[0]+cur[1]+","+cur[2]+","+cur[3]+","+cur[4]+","+cur[5]+","+c[0]+","+c[1];}else if(cur[0]==='Q'){var _p=fromValues$2(cur[1]-defX,cur[2]-defY,0);var _p2=fromValues$2(cur[3]-defX,cur[4]-defY,0);if(transform){transformMat4(_p,_p,transform);transformMat4(_p2,_p2,transform);}path=""+cur[0]+cur[1]+","+cur[2]+","+cur[3]+","+cur[4]+"}";}return prev+=path;},'');}function lineToCommands(x1,y1,x2,y2){return [['M',x1,y1],['L',x2,y2]];}function ellipseToCommands(rx,ry,cx,cy){var factor=(-1+Math.sqrt(2))/3*4;var dx=rx*factor;var dy=ry*factor;var left=cx-rx;var right=cx+rx;var top=cy-ry;var bottom=cy+ry;return [['M',left,cy],['C',left,cy-dy,cx-dx,top,cx,top],['C',cx+dx,top,right,cy-dy,right,cy],['C',right,cy+dy,cx+dx,bottom,cx,bottom],['C',cx-dx,bottom,left,cy+dy,left,cy],['Z']];}function polygonToCommands(points,closed){var result=points.map(function(point,i){return [i===0?'M':'L',point[0],point[1]];});if(closed){result.push(['Z']);}return result;}function rectToCommands(width,height,x,y,radius){// @see https://gist.github.com/danielpquinn/dd966af424030d47e476
- if(radius){var tlr=radius[0],trr=radius[1],brr=radius[2],blr=radius[3];var signX=width>0?1:-1;var signY=height>0?1:-1;// sweep-flag @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths#arcs
- var sweepFlag=signX+signY!==0?1:0;return [['M',signX*tlr+x,y],['L',width-signX*trr+x,y],trr?['A',trr,trr,0,0,sweepFlag,width+x,signY*trr+y]:null,['L',width+x,height-signY*brr+y],brr?['A',brr,brr,0,0,sweepFlag,width+x-signX*brr,height+y]:null,['L',x+signX*blr,height+y],blr?['A',blr,blr,0,0,sweepFlag,x,height+y-signY*blr]:null,['L',x,signY*tlr+y],tlr?['A',tlr,tlr,0,0,sweepFlag,signX*tlr+x,y]:null,['Z']].filter(function(command){return command;});}return [['M',x,y],['L',x+width,y],['L',x+width,y+height],['L',x,y+height],['Z']];}/**
- * convert object to path, should account for:
- * * transform & origin
- * * anchor
- * * lineWidth
- */function convertToPath(object,transform){if(transform===void 0){transform=object.getLocalTransform();}var commands=[];switch(object.nodeName){case exports.Shape.LINE:var _object$parsedStyle2=object.parsedStyle,x1=_object$parsedStyle2.x1,y1=_object$parsedStyle2.y1,x2=_object$parsedStyle2.x2,y2=_object$parsedStyle2.y2;commands=lineToCommands(x1,y1,x2,y2);break;case exports.Shape.CIRCLE:{var _object$parsedStyle3=object.parsedStyle,r=_object$parsedStyle3.r,cx=_object$parsedStyle3.cx,cy=_object$parsedStyle3.cy;commands=ellipseToCommands(r,r,cx,cy);break;}case exports.Shape.ELLIPSE:{var _object$parsedStyle4=object.parsedStyle,rx=_object$parsedStyle4.rx,ry=_object$parsedStyle4.ry,_cx=_object$parsedStyle4.cx,_cy=_object$parsedStyle4.cy;commands=ellipseToCommands(rx,ry,_cx,_cy);break;}case exports.Shape.POLYLINE:case exports.Shape.POLYGON:var points=object.parsedStyle.points;commands=polygonToCommands(points.points,object.nodeName===exports.Shape.POLYGON);break;case exports.Shape.RECT:var _object$parsedStyle5=object.parsedStyle,width=_object$parsedStyle5.width,height=_object$parsedStyle5.height,x=_object$parsedStyle5.x,y=_object$parsedStyle5.y,radius=_object$parsedStyle5.radius;var hasRadius=radius&&radius.some(function(r){return r!==0;});commands=rectToCommands(width,height,x,y,hasRadius&&radius.map(function(r){return clamp(r,0,Math.min(Math.abs(width)/2,Math.abs(height)/2));}));break;case exports.Shape.PATH:var absolutePath=object.parsedStyle.path.absolutePath;commands=[].concat(absolutePath);break;}if(commands.length){return commandsToPathString(commands,object,transform);}}function translatePathToString(absolutePath,defX,defY,startOffsetX,startOffsetY,endOffsetX,endOffsetY){if(startOffsetX===void 0){startOffsetX=0;}if(startOffsetY===void 0){startOffsetY=0;}if(endOffsetX===void 0){endOffsetX=0;}if(endOffsetY===void 0){endOffsetY=0;}var newValue=absolutePath.map(function(params,i){var command=params[0];var nextSegment=absolutePath[i+1];var useStartOffset=i===0&&(startOffsetX!==0||startOffsetY!==0);var useEndOffset=(i===absolutePath.length-1||nextSegment&&(nextSegment[0]==='M'||nextSegment[0]==='Z'))&&endOffsetX!==0&&endOffsetY!==0;switch(command){case'M':// Use start marker offset
- if(useStartOffset){return "M "+(params[1]-defX+startOffsetX)+","+(params[2]-defY+startOffsetY)+" L "+(params[1]-defX)+","+(params[2]-defY);}else {return "M "+(params[1]-defX)+","+(params[2]-defY);}case'L':return "L "+(params[1]-defX+(useEndOffset?endOffsetX:0))+","+(params[2]-defY+(useEndOffset?endOffsetY:0));case'Q':return "Q "+(params[1]-defX)+" "+(params[2]-defY)+","+(params[3]-defX)+" "+(params[4]-defY)+(useEndOffset?" L "+(params[3]-defX+endOffsetX)+","+(params[4]-defY+endOffsetY):'');case'C':return "C "+(params[1]-defX)+" "+(params[2]-defY)+","+(params[3]-defX)+" "+(params[4]-defY)+","+(params[5]-defX)+" "+(params[6]-defY)+(useEndOffset?" L "+(params[5]-defX+endOffsetX)+","+(params[6]-defY+endOffsetY):'');case'A':return "A "+params[1]+" "+params[2]+" "+params[3]+" "+params[4]+" "+params[5]+" "+(params[6]-defX)+" "+(params[7]-defY)+(useEndOffset?" L "+(params[6]-defX+endOffsetX)+","+(params[7]-defY+endOffsetY):'');case'Z':return 'Z';}}).join(' ');if(~newValue.indexOf('NaN')){return '';}return newValue;}function isFillOrStrokeAffected(pointerEvents,fill,stroke){// account for pointerEvents
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
- var hasFill=false;var hasStroke=false;var isFillOtherThanNone=!!fill&&!fill.isNone;var isStrokeOtherThanNone=!!stroke&&!stroke.isNone;if(pointerEvents==='visiblepainted'||pointerEvents==='painted'||pointerEvents==='auto'){hasFill=isFillOtherThanNone;hasStroke=isStrokeOtherThanNone;}else if(pointerEvents==='visiblefill'||pointerEvents==='fill'){hasFill=true;}else if(pointerEvents==='visiblestroke'||pointerEvents==='stroke'){hasStroke=true;}else if(pointerEvents==='visible'||pointerEvents==='all'){// The values of the fill and stroke do not affect event processing.
- hasFill=true;hasStroke=true;}return [hasFill,hasStroke];}var AsyncParallelHook=/*#__PURE__*/function(){function AsyncParallelHook(){this.callbacks=[];}var _proto=AsyncParallelHook.prototype;_proto.getCallbacksNum=function getCallbacksNum(){return this.callbacks.length;};_proto.tapPromise=function tapPromise(options,fn){this.callbacks.push(fn);};_proto.promise=function promise(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}return Promise.all(this.callbacks.map(function(callback){return callback.apply(void 0,args);}));};return AsyncParallelHook;}();var AsyncSeriesWaterfallHook=/*#__PURE__*/function(){function AsyncSeriesWaterfallHook(){this.callbacks=[];}var _proto=AsyncSeriesWaterfallHook.prototype;_proto.tapPromise=function tapPromise(options,fn){this.callbacks.push(fn);};_proto.promise=/*#__PURE__*/function(){var _promise=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(){var _this$callbacks,result,i,callback,_args=arguments;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(!this.callbacks.length){_context.next=14;break;}_context.next=3;return (_this$callbacks=this.callbacks)[0].apply(_this$callbacks,_args);case 3:result=_context.sent;i=0;case 5:if(!(i<this.callbacks.length-1)){_context.next=13;break;}callback=this.callbacks[i];// @ts-ignore
- _context.next=9;return callback(result);case 9:result=_context.sent;case 10:i++;_context.next=5;break;case 13:return _context.abrupt("return",result);case 14:return _context.abrupt("return",null);case 15:case"end":return _context.stop();}},_callee,this);}));function promise(){return _promise.apply(this,arguments);}return promise;}();return AsyncSeriesWaterfallHook;}();var SyncHook=/*#__PURE__*/function(){function SyncHook(){this.callbacks=[];}var _proto=SyncHook.prototype;_proto.tap=function tap(options,fn){this.callbacks.push(fn);};_proto.call=function call(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}this.callbacks.forEach(function(callback){callback.apply(void 0,args);});};return SyncHook;}();var SyncWaterfallHook=/*#__PURE__*/function(){function SyncWaterfallHook(){this.callbacks=[];}var _proto=SyncWaterfallHook.prototype;_proto.tap=function tap(options,fn){this.callbacks.push(fn);};_proto.call=function call(){if(this.callbacks.length){var _this$callbacks;var result=(_this$callbacks=this.callbacks)[0].apply(_this$callbacks,arguments);for(var i=0;i<this.callbacks.length-1;i++){var callback=this.callbacks[i];// @ts-ignore
- result=callback(result);}return result;}return null;};return SyncWaterfallHook;}();var genericFontFamilies=['serif','sans-serif','monospace','cursive','fantasy','system-ui'];var stringRegExp=/([\"\'])[^\'\"]+\1/;function toFontString(attributes){var fontSize=attributes.fontSize,fontFamily=attributes.fontFamily,fontStyle=attributes.fontStyle,fontVariant=attributes.fontVariant,fontWeight=attributes.fontWeight;// build canvas api font setting from individual components. Convert a numeric this.fontSize to px
- // const fontSizeString: string = isNumber(fontSize) ? `${fontSize}px` : fontSize.toString();
- var fontSizeString=isNumber(fontSize)&&fontSize+"px"||'16px';// Clean-up fontFamily property by quoting each font name
- // this will support font names with spaces
- var fontFamilies=fontFamily.split(',');for(var i=fontFamilies.length-1;i>=0;i--){// Trim any extra white-space
- var _fontFamily=fontFamilies[i].trim();// Check if font already contains strings
- if(!stringRegExp.test(_fontFamily)&&genericFontFamilies.indexOf(_fontFamily)<0){_fontFamily="\""+_fontFamily+"\"";}fontFamilies[i]=_fontFamily;}return fontStyle+" "+fontVariant+" "+fontWeight+" "+fontSizeString+" "+fontFamilies.join(',');}/**
- * Thanks for following contributor of codes
- * https://gist.github.com/1866474
- * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
- * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
- * https://github.com/Financial-Times/polyfill-library/blob/master/polyfills/requestAnimationFrame/polyfill.js
- **/var uId=1;var uniqueId=function uniqueId(){return uId++;};// We use `self` instead of `window` for `WebWorker` support.
- var root=typeof self==='object'&&self.self==self?self:// @ts-ignore
- typeof global==='object'&&global.global==global?// @ts-ignore
- global:{};var nowOffset=Date.now();// use performance api if exist, otherwise use Date.now.
- // Date.now polyfill required.
- var pnow=function pnow(){if(root.performance&&typeof root.performance.now==='function'){return root.performance.now();}// fallback
- return Date.now()-nowOffset;};var reservedCBs={};var lastTime=Date.now();var polyfillRaf=function polyfillRaf(callback){if(typeof callback!=='function'){throw new TypeError(callback+' is not a function');}var currentTime=Date.now();var gap=currentTime-lastTime;var delay=gap>16?0:16-gap;var id=uniqueId();reservedCBs[id]=callback;// keys(reservedCBs).length > 1 의미는 이미 setTimeout 이 걸려있는 경우.
- // 함께 callback 이 실행될 수 있게 reservedCBs 에만 추가해주고 return
- if(Object.keys(reservedCBs).length>1)return id;setTimeout(function(){lastTime=currentTime;var copied=reservedCBs;reservedCBs={};Object.keys(copied).forEach(function(key){return copied[key](pnow());});},delay);return id;};var polyfillCaf=function polyfillCaf(id){delete reservedCBs[id];};var vendorPrefixes=['','webkit','moz','ms','o'];var getRequestAnimationFrame=function getRequestAnimationFrame(vp){if(typeof vp!=='string')return polyfillRaf;if(vp==='')return root['requestAnimationFrame'];return root[vp+'RequestAnimationFrame'];};var getCancelAnimationFrame=function getCancelAnimationFrame(vp){if(typeof vp!=='string')return polyfillCaf;if(vp==='')return root['cancelAnimationFrame'];return root[vp+'CancelAnimationFrame']||root[vp+'CancelRequestAnimationFrame'];};var find=function find(arr,predicate){var i=0;while(arr[i]!==void 0){if(predicate(arr[i]))return arr[i];i=i+1;}};var vp=find(vendorPrefixes,function(vp){return !!getRequestAnimationFrame(vp);});var raf=getRequestAnimationFrame(vp);var caf=getCancelAnimationFrame(vp);root.requestAnimationFrame=raf;root.cancelAnimationFrame=caf;var regexLG=/^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i;var regexRG=/^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i;var regexPR=/^p\s*\(\s*([axyn])\s*\)\s*(.*)/i;var regexColorStop=/[\d.]+:(#[^\s]+|[^\)]+\))/gi;function spaceColorStops(colorStops){var _colorStops$length;var length=colorStops.length;colorStops[length-1].length=(_colorStops$length=colorStops[length-1].length)!==null&&_colorStops$length!==void 0?_colorStops$length:{type:'%',value:'100'};if(length>1){var _colorStops$0$length;colorStops[0].length=(_colorStops$0$length=colorStops[0].length)!==null&&_colorStops$0$length!==void 0?_colorStops$0$length:{type:'%',value:'0'};}var previousIndex=0;var previousOffset=Number(colorStops[0].length.value);for(var i=1;i<length;i++){var _colorStops$i$length;// support '%' & 'px'
- var offset=(_colorStops$i$length=colorStops[i].length)===null||_colorStops$i$length===void 0?void 0:_colorStops$i$length.value;if(!isNil(offset)&&!isNil(previousOffset)){for(var j=1;j<i-previousIndex;j++)colorStops[previousIndex+j].length={type:'%',value:""+(previousOffset+(Number(offset)-previousOffset)*j/(i-previousIndex))};previousIndex=i;previousOffset=Number(offset);}}}// The position of the gradient line's starting point.
- // different from CSS side(to top) @see https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#values
- var SideOrCornerToDegMap={left:270-90,top:0-90,bottom:180-90,right:90-90,'left top':315-90,'top left':315-90,'left bottom':225-90,'bottom left':225-90,'right top':45-90,'top right':45-90,'right bottom':135-90,'bottom right':135-90};var angleToDeg=memoize(function(orientation){var angle;if(orientation.type==='angular'){angle=Number(orientation.value);}else {angle=SideOrCornerToDegMap[orientation.value]||0;}return getOrCreateUnitValue(angle,'deg');});var positonToCSSUnitValue=memoize(function(position){var cx=50;var cy=50;var unitX='%';var unitY='%';if((position===null||position===void 0?void 0:position.type)==='position'){var _position$value=position.value,x=_position$value.x,y=_position$value.y;if((x===null||x===void 0?void 0:x.type)==='position-keyword'){if(x.value==='left'){cx=0;}else if(x.value==='center'){cx=50;}else if(x.value==='right'){cx=100;}else if(x.value==='top'){cy=0;}else if(x.value==='bottom'){cy=100;}}if((y===null||y===void 0?void 0:y.type)==='position-keyword'){if(y.value==='left'){cx=0;}else if(y.value==='center'){cy=50;}else if(y.value==='right'){cx=100;}else if(y.value==='top'){cy=0;}else if(y.value==='bottom'){cy=100;}}if((x===null||x===void 0?void 0:x.type)==='px'||(x===null||x===void 0?void 0:x.type)==='%'||(x===null||x===void 0?void 0:x.type)==='em'){unitX=x===null||x===void 0?void 0:x.type;cx=Number(x.value);}if((y===null||y===void 0?void 0:y.type)==='px'||(y===null||y===void 0?void 0:y.type)==='%'||(y===null||y===void 0?void 0:y.type)==='em'){unitY=y===null||y===void 0?void 0:y.type;cy=Number(y.value);}}return {cx:getOrCreateUnitValue(cx,unitX),cy:getOrCreateUnitValue(cy,unitY)};});var parseGradient$1=memoize(function(colorStr){if(colorStr.indexOf('linear')>-1||colorStr.indexOf('radial')>-1){var ast=parseGradient(colorStr);return ast.map(function(_ref){var type=_ref.type,orientation=_ref.orientation,colorStops=_ref.colorStops;spaceColorStops(colorStops);var steps=colorStops.map(function(colorStop){// TODO: only support % for now, should calc percentage of axis length when using px/em
- return {offset:getOrCreateUnitValue(Number(colorStop.length.value),'%'),color:colorStopToString(colorStop)};});if(type==='linear-gradient'){return new CSSGradientValue(exports.GradientType.LinearGradient,{angle:orientation?angleToDeg(orientation):Odeg,steps:steps});}else if(type==='radial-gradient'){if(!orientation){orientation=[{type:'shape',value:'circle'}];}if(orientation[0].type==='shape'&&orientation[0].value==='circle'){var _positonToCSSUnitValu=positonToCSSUnitValue(orientation[0].at),cx=_positonToCSSUnitValu.cx,cy=_positonToCSSUnitValu.cy;var size;if(orientation[0].style){var _orientation$0$style=orientation[0].style,_type=_orientation$0$style.type,value=_orientation$0$style.value;if(_type==='extent-keyword'){size=getOrCreateKeyword(value);}else {size=getOrCreateUnitValue(value,_type);}}return new CSSGradientValue(exports.GradientType.RadialGradient,{cx:cx,cy:cy,size:size,steps:steps});}// TODO: support ellipse shape
- // TODO: repeating-linear-gradient & repeating-radial-gradient
- // } else if (type === 'repeating-linear-gradient') {
- // } else if (type === 'repeating-radial-gradient') {
- }});}// legacy format, should be deprecated later
- var type=colorStr[0];if(colorStr[1]==='('||colorStr[2]==='('){if(type==='l'){var arr=regexLG.exec(colorStr);if(arr){var _arr$2$match;var steps=((_arr$2$match=arr[2].match(regexColorStop))===null||_arr$2$match===void 0?void 0:_arr$2$match.map(function(stop){return stop.split(':');}))||[];return [new CSSGradientValue(exports.GradientType.LinearGradient,{angle:getOrCreateUnitValue(parseFloat(arr[1]),'deg'),steps:steps.map(function(_ref2){var offset=_ref2[0],color=_ref2[1];return {offset:getOrCreateUnitValue(Number(offset)*100,'%'),color:color};})})];}}else if(type==='r'){var parsedRadialGradient=parseRadialGradient(colorStr);if(parsedRadialGradient){if(isString(parsedRadialGradient)){colorStr=parsedRadialGradient;}else {return [new CSSGradientValue(exports.GradientType.RadialGradient,parsedRadialGradient)];}}}else if(type==='p'){return parsePattern(colorStr);}}});function parseRadialGradient(gradientStr){var arr=regexRG.exec(gradientStr);if(arr){var _arr$4$match;var steps=((_arr$4$match=arr[4].match(regexColorStop))===null||_arr$4$match===void 0?void 0:_arr$4$match.map(function(stop){return stop.split(':');}))||[];return {cx:getOrCreateUnitValue(50,'%'),cy:getOrCreateUnitValue(50,'%'),steps:steps.map(function(_ref3){var offset=_ref3[0],color=_ref3[1];return {offset:getOrCreateUnitValue(Number(offset)*100,'%'),color:color};})};}return null;}function parsePattern(patternStr){var arr=regexPR.exec(patternStr);if(arr){var repetition=arr[1];var src=arr[2];switch(repetition){case'a':repetition='repeat';break;case'x':repetition='repeat-x';break;case'y':repetition='repeat-y';break;case'n':repetition='no-repeat';break;default:repetition='no-repeat';}return {image:src,// @ts-ignore
- repetition:repetition};}return null;}function isCSSGradientValue(object){return !!object.type&&!!object.value;}function isPattern(object){return object&&!!object.image;}function isCSSRGB(object){return object&&!isNil(object.r)&&!isNil(object.g)&&!isNil(object.b);}/**
- * @see https://github.com/WebKit/WebKit/blob/main/Source/WebCore/css/parser/CSSParser.cpp#L97
- */var parseColor=memoize(function(colorStr){if(isPattern(colorStr)){return _extends({repetition:'repeat'},colorStr);}if(isNil(colorStr)){colorStr='';}if(colorStr==='transparent'){// transparent black
- return transparentColor;}else if(colorStr==='currentColor'){// @see https://github.com/adobe-webplatform/Snap.svg/issues/526
- colorStr='black';}// support CSS gradient syntax
- var g=parseGradient$1(colorStr);if(g){return g;}// constants
- var color$1=color(colorStr);var rgba=[0,0,0,0];if(color$1!==null){rgba[0]=color$1.r||0;rgba[1]=color$1.g||0;rgba[2]=color$1.b||0;rgba[3]=color$1.opacity;}// return new CSSRGB(...rgba);
- return getOrCreateRGBA.apply(void 0,rgba);});function mergeColors(left,right){// only support constant value, exclude gradient & pattern
- if(!isCSSRGB(left)||!isCSSRGB(right)){return;}return [[Number(left.r),Number(left.g),Number(left.b),Number(left.alpha)],[Number(right.r),Number(right.g),Number(right.b),Number(right.alpha)],function(color){var rgba=color.slice();if(rgba[3]){for(var i=0;i<3;i++)rgba[i]=Math.round(clamp(rgba[i],0,255));}rgba[3]=clamp(rgba[3],0,1);return "rgba("+rgba.join(',')+")";}];}function parseDimension(unitRegExp,string){if(isNil(string)){return getOrCreateUnitValue(0,'px');}string=(""+string).trim().toLowerCase();if(isFinite(Number(string))){if('px'.search(unitRegExp)>=0){return getOrCreateUnitValue(Number(string),'px');}else if('deg'.search(unitRegExp)>=0){return getOrCreateUnitValue(Number(string),'deg');}}var matchedUnits=[];string=string.replace(unitRegExp,function(match){matchedUnits.push(match);return 'U'+match;});var taggedUnitRegExp='U('+unitRegExp.source+')';return matchedUnits.map(function(unit){return getOrCreateUnitValue(Number(string.replace(new RegExp('U'+unit,'g'),'').replace(new RegExp(taggedUnitRegExp,'g'),'*0')),unit);})[0];}/**
- * <length>
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length
- * length with only absolute unit, eg. 1px
- */var parseLength=memoize(function(css){return parseDimension(new RegExp('px','g'),css);});/**
- * <percentage>
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage
- */var parserPercentage=memoize(function(css){return parseDimension(new RegExp('%','g'),css);});/**
- * length with absolute or relative unit,
- * eg. 1px, 0.7em, 50%, calc(100% - 200px);
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length-percentage
- */ // export const parseLengthOrPercentage = memoize((css: string): CSSUnitValue => {
- // if (isNumber(css) || isFinite(Number(css))) {
- // return getOrCreateUnitValue(Number(css), 'px');
- // }
- // return parseDimension(new RegExp('px|%|em|rem', 'g'), css) as CSSUnitValue;
- // });
- var parseLengthOrPercentage=function parseLengthOrPercentage(css){if(isNumber(css)||isFinite(Number(css))){// Number(css) is NaN
- return getOrCreateUnitValue(Number(css)||0,'px');// return Number(css);
- }return parseDimension(new RegExp('px|%|em|rem','g'),css);};var parseAngle=memoize(function(css){return parseDimension(new RegExp('deg|rad|grad|turn','g'),css);});/**
- * merge CSSUnitValue
- *
- * @example
- * 10px + 20px = 30px
- * 10deg + 10rad
- * 10% + 20% = 30%
- */function mergeDimensions(left,right,target,nonNegative,index){if(index===void 0){index=0;}var unit='';var leftValue=left.value||0;var rightValue=right.value||0;var canonicalUnit=toCanonicalUnit(left.unit);var leftCanonicalUnitValue=left.convertTo(canonicalUnit);var rightCanonicalUnitValue=right.convertTo(canonicalUnit);if(leftCanonicalUnitValue&&rightCanonicalUnitValue){leftValue=leftCanonicalUnitValue.value;rightValue=rightCanonicalUnitValue.value;unit=unitTypeToString(left.unit);}else {// format '%' to 'px'
- if(CSSUnitValue.isLength(left.unit)||CSSUnitValue.isLength(right.unit)){leftValue=convertPercentUnit(left,index,target);rightValue=convertPercentUnit(right,index,target);unit='px';}}// // format 'rad' 'turn' to 'deg'
- // if (CSSUnitValue.isAngle(left.unit) || CSSUnitValue.isAngle(right.unit)) {
- // leftValue = convertAngleUnit(left);
- // rightValue = convertAngleUnit(right);
- // unit = 'deg';
- // }
- return [leftValue,rightValue,function(value){if(nonNegative){value=Math.max(value,0);}return value+unit;}];}function convertAngleUnit(value){var deg=0;if(value.unit===exports.UnitType.kDegrees){deg=value.value;}else if(value.unit===exports.UnitType.kRadians){deg=rad2deg(Number(value.value));}else if(value.unit===exports.UnitType.kTurns){deg=turn2deg(Number(value.value));}return deg;}function parseDimensionArrayFormat(string,size){var parsed;if(Array.isArray(string)){// [1, '2px', 3]
- parsed=string.map(function(segment){return Number(segment);});}else if(isString(string)){parsed=string.split(' ').map(function(segment){return Number(segment);});}else if(isNumber(string)){parsed=[string];}if(size===2){if(parsed.length===1){return [parsed[0],parsed[0]];}else {return [parsed[0],parsed[1]];}}else {if(parsed.length===1){return [parsed[0],parsed[0],parsed[0],parsed[0]];}else if(parsed.length===2){return [parsed[0],parsed[1],parsed[0],parsed[1]];}else if(parsed.length===3){return [parsed[0],parsed[1],parsed[2],parsed[1]];}else {return [parsed[0],parsed[1],parsed[2],parsed[3]];}}}function parseDimensionArray(string){if(isString(string)){// "1px 2px 3px"
- return string.split(' ').map(function(segment){return parseLengthOrPercentage(segment);});}else {// [1, '2px', 3]
- return string.map(function(segment){return parseLengthOrPercentage(segment.toString());});}}// export function mergeDimensionList(
- // left: CSSUnitValue[],
- // right: CSSUnitValue[],
- // target: IElement | null,
- // ): [number[], number[], (list: number[]) => string] | undefined {
- // if (left.length !== right.length) {
- // return;
- // }
- // const unit = left[0].unit;
- // return [
- // left.map((l) => l.value),
- // right.map((l) => l.value),
- // (values: number[]) => {
- // return values.map((n) => new CSSUnitValue(n, unit)).join(' ');
- // },
- // ];
- // }
- function convertPercentUnit(valueWithUnit,vec3Index,target){if(valueWithUnit.value===0){return 0;}if(valueWithUnit.unit===exports.UnitType.kPixels){return Number(valueWithUnit.value);}else if(valueWithUnit.unit===exports.UnitType.kPercentage&&target){var bounds=target.nodeName===exports.Shape.GROUP?target.getLocalBounds():// : target.getGeometryBounds();
- target.geometry.contentBounds;return valueWithUnit.value/100*bounds.halfExtents[vec3Index]*2;}return 0;}var parseParam=function parseParam(css){return parseDimension(/deg|rad|grad|turn|px|%/g,css);};var supportedFilters=['blur','brightness','drop-shadow','contrast','grayscale','sepia','saturate','hue-rotate','invert'];function parseFilter(filterStr){if(filterStr===void 0){filterStr='';}filterStr=filterStr.toLowerCase().trim();if(filterStr==='none'){return [];}var filterRegExp=/\s*([\w-]+)\(([^)]*)\)/g;var result=[];var match;var prevLastIndex=0;while(match=filterRegExp.exec(filterStr)){if(match.index!==prevLastIndex){return [];}prevLastIndex=match.index+match[0].length;if(supportedFilters.indexOf(match[1])>-1){result.push({name:match[1],params:match[2].split(' ').map(function(p){return parseParam(p)||parseColor(p);})});}if(filterRegExp.lastIndex===filterStr.length){return result;}}return [];}function numberToString(x){// scale(0.00000001) -> scale(0)
- // return x.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
- return x.toString();}/**
- * parse string or number to CSSUnitValue(numeric)
- *
- * eg.
- * * 0 -> CSSUnitValue(0)
- * * '2' -> CSSUnitValue(2)
- */var parseNumber=memoize(function(string){if(typeof string==='number'){return getOrCreateUnitValue(string);}if(/^\s*[-+]?(\d*\.)?\d+\s*$/.test(string)){return getOrCreateUnitValue(Number(string));}else {return getOrCreateUnitValue(0);}});/**
- * separate string to array
- * eg.
- * * [0.5, 0.5] -> [CSSUnitValue, CSSUnitValue]
- */var parseNumberList=memoize(function(string){if(isString(string)){return string.split(' ').map(parseNumber);}else {return string.map(parseNumber);}});function mergeNumbers(left,right){return [left,right,numberToString];}function clampedMergeNumbers(min,max){return function(left,right){return [left,right,function(x){return numberToString(clamp(x,min,max));}];};}function mergeNumberLists(left,right){if(left.length!==right.length){return;}return [left,right,function(numberList){return numberList;}];}var internalParsePath=function internalParsePath(path){// empty path
- if(path===''||Array.isArray(path)&&path.length===0){return {absolutePath:[],hasArc:false,segments:[],polygons:[],polylines:[],curve:null,totalLength:0,rect:{x:0,y:0,width:0,height:0}};}var absolutePath;try{absolutePath=normalizePath(path);}catch(e){absolutePath=normalizePath('');console.error("[g]: Invalid SVG Path definition: "+path);}var hasArc=hasArcOrBezier(absolutePath);var _extractPolygons=extractPolygons(absolutePath),polygons=_extractPolygons.polygons,polylines=_extractPolygons.polylines;// for later use
- var segments=path2Segments(absolutePath);// Only calculate bbox here since we don't need length now.
- var _getPathBBox=getPathBBox(segments,0),x=_getPathBBox.x,y=_getPathBBox.y,width=_getPathBBox.width,height=_getPathBBox.height;return {absolutePath:absolutePath,hasArc:hasArc,segments:segments,polygons:polygons,polylines:polylines,// curve,
- // Delay the calculation of length.
- totalLength:0,rect:{x:Number.isFinite(x)?x:0,y:Number.isFinite(y)?y:0,width:Number.isFinite(width)?width:0,height:Number.isFinite(height)?height:0}};};var memoizedParsePath=memoize(internalParsePath);function parsePath(path,object){var result=isString(path)?memoizedParsePath(path):internalParsePath(path);if(object){object.parsedStyle.defX=result.rect.x;object.parsedStyle.defY=result.rect.y;}return result;}function mergePaths(left,right,object){var curve1=left.curve;var curve2=right.curve;if(!curve1||curve1.length===0){// convert to curves to do morphing & picking later
- // @see http://thednp.github.io/kute.js/svgCubicMorph.html
- curve1=path2Curve(left.absolutePath,false);left.curve=curve1;}if(!curve2||curve2.length===0){curve2=path2Curve(right.absolutePath,false);right.curve=curve2;}var curves=[curve1,curve2];if(curve1.length!==curve2.length){curves=equalizeSegments(curve1,curve2);}var curve0=getDrawDirection(curves[0])!==getDrawDirection(curves[1])?reverseCurve(curves[0]):clonePath(curves[0]);return [curve0,getRotatedCurve(curves[1],curve0),function(pathArray){// need converting to path string?
- return pathArray;}];}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/points
- *
- * @example
- * points="100,10 250,150 200,110"
- */function parsePoints(pointsOrStr,object){var points;if(isString(pointsOrStr)){points=pointsOrStr.split(' ').map(function(pointStr){var _pointStr$split=pointStr.split(','),x=_pointStr$split[0],y=_pointStr$split[1];return [Number(x),Number(y)];});}else {points=pointsOrStr;}var segments=[];var tempLength=0;var segmentT;var segmentL;var totalLength=polyline.length(points);points.forEach(function(p,i){if(points[i+1]){segmentT=[0,0];segmentT[0]=tempLength/totalLength;segmentL=line.length(p[0],p[1],points[i+1][0],points[i+1][1]);tempLength+=segmentL;segmentT[1]=tempLength/totalLength;segments.push(segmentT);}});var minX=Math.min.apply(Math,points.map(function(point){return point[0];}));var minY=Math.min.apply(Math,points.map(function(point){return point[1];}));if(object){object.parsedStyle.defX=minX;object.parsedStyle.defY=minY;}return {points:points,totalLength:totalLength,segments:segments};}function mergePoints(left,right){return [left.points,right.points,function(points){return points;}];}var _=null;function cast(pattern){return function(contents){var i=0;return pattern.map(function(x){return x===_?contents[i++]:x;});};}function id(x){return x;}// type: [argTypes, convertTo3D, convertTo2D]
- // In the argument types string, lowercase characters represent optional arguments
- var transformFunctions={// @ts-ignore
- matrix:['NNNNNN',[_,_,0,0,_,_,0,0,0,0,1,0,_,_,0,1],id],matrix3d:['NNNNNNNNNNNNNNNN',id],rotate:['A'],rotatex:['A'],rotatey:['A'],rotatez:['A'],rotate3d:['NNNA'],perspective:['L'],scale:['Nn',cast([_,_,new CSSUnitValue(1)]),id],scalex:['N',cast([_,new CSSUnitValue(1),new CSSUnitValue(1)]),cast([_,new CSSUnitValue(1)])],scaley:['N',cast([new CSSUnitValue(1),_,new CSSUnitValue(1)]),cast([new CSSUnitValue(1),_])],scalez:['N',cast([new CSSUnitValue(1),new CSSUnitValue(1),_])],scale3d:['NNN',id],skew:['Aa',null,id],skewx:['A',null,cast([_,Odeg])],skewy:['A',null,cast([Odeg,_])],translate:['Tt',cast([_,_,Opx]),id],translatex:['T',cast([_,Opx,Opx]),cast([_,Opx])],translatey:['T',cast([Opx,_,Opx]),cast([Opx,_])],translatez:['L',cast([Opx,Opx,_])],translate3d:['TTL',id]};/**
- * none
- * scale(1) scale(1, 2)
- * scaleX(1)
- */function parseTransform(string){string=(string||'none').toLowerCase().trim();if(string==='none'){return [];}var transformRegExp=/\s*(\w+)\(([^)]*)\)/g;var result=[];var match;var prevLastIndex=0;while(match=transformRegExp.exec(string)){if(match.index!==prevLastIndex){return [];}prevLastIndex=match.index+match[0].length;var functionName=match[1];// scale
- var functionData=transformFunctions[functionName];// scale(1, 2)
- if(!functionData){// invalid, eg. scale()
- return [];}var args=match[2].split(',');// 1,2
- var argTypes=functionData[0];// Nn
- if(argTypes.length<args.length){// scale(N, n)
- return [];}var parsedArgs=[];for(var i=0;i<argTypes.length;i++){var arg=args[i];var type=argTypes[i];var parsedArg=void 0;if(!arg){// @ts-ignore
- parsedArg={a:Odeg,n:parsedArgs[0],t:Opx}[type];}else {// @ts-ignore
- parsedArg={A:function A(s){return s.trim()==='0'?Odeg:parseAngle(s);},N:parseNumber,T:parseLengthOrPercentage,L:parseLength}[type.toUpperCase()](arg);}if(parsedArg===undefined){return [];}parsedArgs.push(parsedArg);}result.push({t:functionName,d:parsedArgs});// { t: scale, d: [1, 2] }
- if(transformRegExp.lastIndex===string.length){return result;}}return [];}function convertItemToMatrix(item){var x;var y;var z;var angle;switch(item.t){case'rotatex':angle=deg2rad(convertAngleUnit(item.d[0]));return [1,0,0,0,0,Math.cos(angle),Math.sin(angle),0,0,-Math.sin(angle),Math.cos(angle),0,0,0,0,1];case'rotatey':angle=deg2rad(convertAngleUnit(item.d[0]));return [Math.cos(angle),0,-Math.sin(angle),0,0,1,0,0,Math.sin(angle),0,Math.cos(angle),0,0,0,0,1];case'rotate':case'rotatez':angle=deg2rad(convertAngleUnit(item.d[0]));return [Math.cos(angle),Math.sin(angle),0,0,-Math.sin(angle),Math.cos(angle),0,0,0,0,1,0,0,0,0,1];case'rotate3d':x=item.d[0].value;y=item.d[1].value;z=item.d[2].value;angle=deg2rad(convertAngleUnit(item.d[3]));var sqrLength=x*x+y*y+z*z;if(sqrLength===0){x=1;y=0;z=0;}else if(sqrLength!==1){var length=Math.sqrt(sqrLength);x/=length;y/=length;z/=length;}var s=Math.sin(angle/2);var sc=s*Math.cos(angle/2);var sq=s*s;return [1-2*(y*y+z*z)*sq,2*(x*y*sq+z*sc),2*(x*z*sq-y*sc),0,2*(x*y*sq-z*sc),1-2*(x*x+z*z)*sq,2*(y*z*sq+x*sc),0,2*(x*z*sq+y*sc),2*(y*z*sq-x*sc),1-2*(x*x+y*y)*sq,0,0,0,0,1];case'scale':return [item.d[0].value,0,0,0,0,item.d[1].value,0,0,0,0,1,0,0,0,0,1];case'scalex':return [item.d[0].value,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];case'scaley':return [1,0,0,0,0,item.d[0].value,0,0,0,0,1,0,0,0,0,1];case'scalez':return [1,0,0,0,0,1,0,0,0,0,item.d[0].value,0,0,0,0,1];case'scale3d':return [item.d[0].value,0,0,0,0,item.d[1].value,0,0,0,0,item.d[2].value,0,0,0,0,1];case'skew':var xAngle=deg2rad(convertAngleUnit(item.d[0]));var yAngle=deg2rad(convertAngleUnit(item.d[1]));return [1,Math.tan(yAngle),0,0,Math.tan(xAngle),1,0,0,0,0,1,0,0,0,0,1];case'skewx':angle=deg2rad(convertAngleUnit(item.d[0]));return [1,0,0,0,Math.tan(angle),1,0,0,0,0,1,0,0,0,0,1];case'skewy':angle=deg2rad(convertAngleUnit(item.d[0]));return [1,Math.tan(angle),0,0,0,1,0,0,0,0,1,0,0,0,0,1];case'translate':// TODO: pass target
- x=convertPercentUnit(item.d[0],0,null)||0;y=convertPercentUnit(item.d[1],0,null)||0;return [1,0,0,0,0,1,0,0,0,0,1,0,x,y,0,1];case'translatex':x=convertPercentUnit(item.d[0],0,null)||0;return [1,0,0,0,0,1,0,0,0,0,1,0,x,0,0,1];case'translatey':y=convertPercentUnit(item.d[0],0,null)||0;return [1,0,0,0,0,1,0,0,0,0,1,0,0,y,0,1];case'translatez':z=convertPercentUnit(item.d[0],0,null)||0;return [1,0,0,0,0,1,0,0,0,0,1,0,0,0,z,1];case'translate3d':x=convertPercentUnit(item.d[0],0,null)||0;y=convertPercentUnit(item.d[1],0,null)||0;z=convertPercentUnit(item.d[2],0,null)||0;return [1,0,0,0,0,1,0,0,0,0,1,0,x,y,z,1];case'perspective':var t=convertPercentUnit(item.d[0],0,null)||0;var p=t?-1/t:0;return [1,0,0,0,0,1,0,0,0,0,1,p,0,0,0,1];case'matrix':return [item.d[0].value,item.d[1].value,0,0,item.d[2].value,item.d[3].value,0,0,0,0,1,0,item.d[4].value,item.d[5].value,0,1];case'matrix3d':return item.d.map(function(d){return d.value;});}}function multiplyMatrices(a,b){return [a[0]*b[0]+a[4]*b[1]+a[8]*b[2]+a[12]*b[3],a[1]*b[0]+a[5]*b[1]+a[9]*b[2]+a[13]*b[3],a[2]*b[0]+a[6]*b[1]+a[10]*b[2]+a[14]*b[3],a[3]*b[0]+a[7]*b[1]+a[11]*b[2]+a[15]*b[3],a[0]*b[4]+a[4]*b[5]+a[8]*b[6]+a[12]*b[7],a[1]*b[4]+a[5]*b[5]+a[9]*b[6]+a[13]*b[7],a[2]*b[4]+a[6]*b[5]+a[10]*b[6]+a[14]*b[7],a[3]*b[4]+a[7]*b[5]+a[11]*b[6]+a[15]*b[7],a[0]*b[8]+a[4]*b[9]+a[8]*b[10]+a[12]*b[11],a[1]*b[8]+a[5]*b[9]+a[9]*b[10]+a[13]*b[11],a[2]*b[8]+a[6]*b[9]+a[10]*b[10]+a[14]*b[11],a[3]*b[8]+a[7]*b[9]+a[11]*b[10]+a[15]*b[11],a[0]*b[12]+a[4]*b[13]+a[8]*b[14]+a[12]*b[15],a[1]*b[12]+a[5]*b[13]+a[9]*b[14]+a[13]*b[15],a[2]*b[12]+a[6]*b[13]+a[10]*b[14]+a[14]*b[15],a[3]*b[12]+a[7]*b[13]+a[11]*b[14]+a[15]*b[15]];}function convertToMatrix(transformList){if(transformList.length===0){return [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];}return transformList.map(convertItemToMatrix).reduce(multiplyMatrices);}function makeMatrixDecomposition(transformList){var translate=[0,0,0];var scale=[1,1,1];var skew=[0,0,0];var perspective=[0,0,0,1];var quaternion=[0,0,0,1];// @ts-ignore
- decomposeMat4(convertToMatrix(transformList),translate,scale,skew,perspective,quaternion);return [[translate,scale,skew,quaternion,perspective]];}var composeMatrix=function(){function multiply(a,b){var result=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];for(var i=0;i<4;i++){for(var j=0;j<4;j++){for(var k=0;k<4;k++){result[i][j]+=b[i][k]*a[k][j];}}}return result;}function is2D(m){return m[0][2]==0&&m[0][3]==0&&m[1][2]==0&&m[1][3]==0&&m[2][0]==0&&m[2][1]==0&&m[2][2]==1&&m[2][3]==0&&m[3][2]==0&&m[3][3]==1;}function composeMatrix(translate,scale,skew,quat,perspective){var matrix=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];for(var i=0;i<4;i++){matrix[i][3]=perspective[i];}for(var _i=0;_i<3;_i++){for(var j=0;j<3;j++){matrix[3][_i]+=translate[j]*matrix[j][_i];}}var x=quat[0],y=quat[1],z=quat[2],w=quat[3];var rotMatrix=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];rotMatrix[0][0]=1-2*(y*y+z*z);rotMatrix[0][1]=2*(x*y-z*w);rotMatrix[0][2]=2*(x*z+y*w);rotMatrix[1][0]=2*(x*y+z*w);rotMatrix[1][1]=1-2*(x*x+z*z);rotMatrix[1][2]=2*(y*z-x*w);rotMatrix[2][0]=2*(x*z-y*w);rotMatrix[2][1]=2*(y*z+x*w);rotMatrix[2][2]=1-2*(x*x+y*y);matrix=multiply(matrix,rotMatrix);var temp=[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]];if(skew[2]){temp[2][1]=skew[2];matrix=multiply(matrix,temp);}if(skew[1]){temp[2][1]=0;temp[2][0]=skew[0];matrix=multiply(matrix,temp);}if(skew[0]){temp[2][0]=0;temp[1][0]=skew[0];matrix=multiply(matrix,temp);}for(var _i2=0;_i2<3;_i2++){for(var _j=0;_j<3;_j++){matrix[_i2][_j]*=scale[_i2];}}if(is2D(matrix)){return [matrix[0][0],matrix[0][1],matrix[1][0],matrix[1][1],matrix[3][0],matrix[3][1]];}return matrix[0].concat(matrix[1],matrix[2],matrix[3]);}return composeMatrix;}();function numberToLongString(x){return x.toFixed(6).replace('.000000','');}function mergeMatrices(left,right){var leftArgs;var rightArgs;// @ts-ignore
- if(left.decompositionPair!==right){// @ts-ignore
- left.decompositionPair=right;// @ts-ignore
- leftArgs=makeMatrixDecomposition(left);}// @ts-ignore
- if(right.decompositionPair!==left){// @ts-ignore
- right.decompositionPair=left;// @ts-ignore
- rightArgs=makeMatrixDecomposition(right);}if(leftArgs[0]===null||rightArgs[0]===null)return [// @ts-ignore
- [false],// @ts-ignore
- [true],// @ts-ignore
- function(x){return x?right[0].d:left[0].d;}];leftArgs[0].push(0);rightArgs[0].push(1);return [leftArgs,rightArgs,// @ts-ignore
- function(list){// @ts-ignore
- var q=quat(leftArgs[0][3],rightArgs[0][3],list[5]);var mat=composeMatrix(list[0],list[1],list[2],q,list[4]);var stringifiedArgs=mat.map(numberToLongString).join(',');return stringifiedArgs;}];}function dot$2(v1,v2){var result=0;for(var i=0;i<v1.length;i++){result+=v1[i]*v2[i];}return result;}function quat(fromQ,toQ,f){var product=dot$2(fromQ,toQ);product=clamp(product,-1.0,1.0);var quat=[];if(product===1.0){quat=fromQ;}else {var theta=Math.acos(product);var w=Math.sin(f*theta)*1/Math.sqrt(1-product*product);for(var i=0;i<4;i++){quat.push(fromQ[i]*(Math.cos(f*theta)-product*w)+toQ[i]*w);}}return quat;}// scalex/y/z -> scale
- function typeTo2D(type){return type.replace(/[xy]/,'');}// scalex/y/z -> scale3d
- function typeTo3D(type){return type.replace(/(x|y|z|3d)?$/,'3d');}var isMatrixOrPerspective=function isMatrixOrPerspective(lt,rt){return lt==='perspective'&&rt==='perspective'||(lt==='matrix'||lt==='matrix3d')&&(rt==='matrix'||rt==='matrix3d');};function mergeTransforms(left,right,target){var flipResults=false;// padding empty transform, eg. merge 'scale(10)' with 'none' -> scale(1)
- if(!left.length||!right.length){if(!left.length){flipResults=true;left=right;right=[];}var _loop=function _loop(){var _left$i=left[i],type=_left$i.t,args=_left$i.d;// none -> scale(1)/translateX(0)
- var defaultValue=type.substring(0,5)==='scale'?1:0;right.push({t:type,d:args.map(function(arg){if(typeof arg==='number'){return getOrCreateUnitValue(defaultValue);}return getOrCreateUnitValue(defaultValue,arg.unit);// {
- // unit: arg.unit,
- // value: defaultValue,
- // };
- })});};for(var i=0;i<left.length;i++){_loop();}}var leftResult=[];var rightResult=[];var types=[];// merge matrix() with matrix3d()
- if(left.length!==right.length){var merged=mergeMatrices(left,right);// @ts-ignore
- leftResult=[merged[0]];// @ts-ignore
- rightResult=[merged[1]];types=[['matrix',[merged[2]]]];}else {for(var _i3=0;_i3<left.length;_i3++){var leftType=left[_i3].t;var rightType=right[_i3].t;var leftArgs=left[_i3].d;var rightArgs=right[_i3].d;var leftFunctionData=transformFunctions[leftType];var rightFunctionData=transformFunctions[rightType];var type=void 0;if(isMatrixOrPerspective(leftType,rightType)){var _merged=mergeMatrices([left[_i3]],[right[_i3]]);// @ts-ignore
- leftResult.push(_merged[0]);// @ts-ignore
- rightResult.push(_merged[1]);types.push(['matrix',[_merged[2]]]);continue;}else if(leftType===rightType){type=leftType;}else if(leftFunctionData[2]&&rightFunctionData[2]&&typeTo2D(leftType)===typeTo2D(rightType)){type=typeTo2D(leftType);// @ts-ignore
- leftArgs=leftFunctionData[2](leftArgs);// @ts-ignore
- rightArgs=rightFunctionData[2](rightArgs);}else if(leftFunctionData[1]&&rightFunctionData[1]&&typeTo3D(leftType)===typeTo3D(rightType)){type=typeTo3D(leftType);// @ts-ignore
- leftArgs=leftFunctionData[1](leftArgs);// @ts-ignore
- rightArgs=rightFunctionData[1](rightArgs);}else {var _merged2=mergeMatrices(left,right);// @ts-ignore
- leftResult=[_merged2[0]];// @ts-ignore
- rightResult=[_merged2[1]];types=[['matrix',[_merged2[2]]]];break;}var leftArgsCopy=[];var rightArgsCopy=[];var stringConversions=[];for(var j=0;j<leftArgs.length;j++){// const merge = leftArgs[j].unit === UnitType.kNumber ? mergeDimensions : mergeDimensions;
- var _merged3=mergeDimensions(leftArgs[j],rightArgs[j],target,false,j);leftArgsCopy[j]=_merged3[0];rightArgsCopy[j]=_merged3[1];stringConversions.push(_merged3[2]);}leftResult.push(leftArgsCopy);rightResult.push(rightArgsCopy);types.push([type,stringConversions]);}}if(flipResults){var tmp=leftResult;leftResult=rightResult;rightResult=tmp;}return [leftResult,rightResult,function(list){return list.map(function(args,i){var stringifiedArgs=args.map(function(arg,j){return types[i][1][j](arg);}).join(',');if(types[i][0]==='matrix'&&stringifiedArgs.split(',').length===16){types[i][0]='matrix3d';}if(types[i][0]==='matrix3d'&&stringifiedArgs.split(',').length===6){types[i][0]='matrix';}return types[i][0]+'('+stringifiedArgs+')';}).join(' ');}];}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
- * eg. 'center' 'top left' '50px 50px'
- */var parseTransformOrigin=memoize(function(value){if(isString(value)){if(value==='text-anchor'){return [getOrCreateUnitValue(0,'px'),getOrCreateUnitValue(0,'px')];}var values=value.split(' ');if(values.length===1){if(values[0]==='top'||values[0]==='bottom'){// 'top' -> 'center top'
- values[1]=values[0];values[0]='center';}else {// '50px' -> '50px center'
- values[1]='center';}}if(values.length!==2){return null;}// eg. center bottom
- return [parseLengthOrPercentage(convertKeyword2Percent(values[0])),parseLengthOrPercentage(convertKeyword2Percent(values[1]))];}else {return [getOrCreateUnitValue(value[0]||0,'px'),getOrCreateUnitValue(value[1]||0,'px')];}});function convertKeyword2Percent(keyword){if(keyword==='center'){return '50%';}else if(keyword==='left'||keyword==='top'){return '0';}else if(keyword==='right'||keyword==='bottom'){return '100%';}return keyword;}var CSSPropertyAngle=/*#__PURE__*/function(){function CSSPropertyAngle(){this.parser=parseAngle;this.parserWithCSSDisabled=null;this.mixer=mergeNumbers;}var _proto=CSSPropertyAngle.prototype;_proto.calculator=function calculator(name,oldParsed,parsed,object){return convertAngleUnit(parsed);};return CSSPropertyAngle;}();/**
- * clipPath / textPath / offsetPath
- */var CSSPropertyClipPath=/*#__PURE__*/function(){function CSSPropertyClipPath(){}var _proto=CSSPropertyClipPath.prototype;_proto.calculator=function calculator(name,oldPath,newPath,object){// unset
- if(newPath instanceof CSSKeywordValue){newPath=null;}runtime.sceneGraphService.updateDisplayObjectDependency(name,oldPath,newPath,object);if(name==='clipPath'){// should affect children
- object.forEach(function(leaf){if(leaf.childNodes.length===0){runtime.sceneGraphService.dirtifyToRoot(leaf);}});}return newPath;};return CSSPropertyClipPath;}();var CSSPropertyColor=/*#__PURE__*/function(){function CSSPropertyColor(){this.parser=parseColor;this.parserWithCSSDisabled=parseColor;this.mixer=mergeColors;}var _proto=CSSPropertyColor.prototype;_proto.calculator=function calculator(name,oldParsed,parsed,object){if(parsed instanceof CSSKeywordValue){// 'unset' 'none'
- return parsed.value==='none'?noneColor:transparentColor;}return parsed;};return CSSPropertyColor;}();var CSSPropertyFilter=/*#__PURE__*/function(){function CSSPropertyFilter(){this.parser=parseFilter;}var _proto=CSSPropertyFilter.prototype;_proto.calculator=function calculator(name,oldParsed,parsed){// unset or none
- if(parsed instanceof CSSKeywordValue){return [];}return parsed;};return CSSPropertyFilter;}();function getFontSize(object){var fontSize=object.parsedStyle.fontSize;return isNil(fontSize)?null:fontSize;}/**
- * <length> & <percentage>
- */var CSSPropertyLengthOrPercentage=/*#__PURE__*/function(){function CSSPropertyLengthOrPercentage(){this.parser=parseLengthOrPercentage;this.parserWithCSSDisabled=null;this.mixer=mergeNumbers;}var _proto=CSSPropertyLengthOrPercentage.prototype;/**
- * according to parent's bounds
- *
- * @example
- * CSS.percent(50) -> CSS.px(0.5 * parent.width)
- */_proto.calculator=function calculator(name,oldParsed,computed,object,registry){if(isNumber(computed)){return computed;}if(CSSUnitValue.isRelativeUnit(computed.unit)){if(computed.unit===exports.UnitType.kPercentage){// TODO: merge dimensions
- return 0;}else if(computed.unit===exports.UnitType.kEms){if(object.parentNode){var fontSize=getFontSize(object.parentNode);if(fontSize){fontSize*=computed.value;return fontSize;}else {registry.addUnresolveProperty(object,name);}}else {registry.addUnresolveProperty(object,name);}return 0;}else if(computed.unit===exports.UnitType.kRems){var _object$ownerDocument;if(object===null||object===void 0?void 0:(_object$ownerDocument=object.ownerDocument)===null||_object$ownerDocument===void 0?void 0:_object$ownerDocument.documentElement){var _fontSize=getFontSize(object.ownerDocument.documentElement);if(_fontSize){_fontSize*=computed.value;return _fontSize;}else {registry.addUnresolveProperty(object,name);}}else {registry.addUnresolveProperty(object,name);}return 0;}}else {// remove listener if exists
- // registry.unregisterParentGeometryBoundsChangedHandler(object, name);
- // return absolute value
- return computed.value;}};return CSSPropertyLengthOrPercentage;}();/**
- * format to Tuple2<CSSUnitValue>
- *
- * @example
- * rect.style.lineDash = 10;
- * rect.style.lineDash = [10, 10];
- * rect.style.lineDash = '10 10';
- */var CSSPropertyLengthOrPercentage12=/*#__PURE__*/function(){function CSSPropertyLengthOrPercentage12(){this.mixer=mergeNumberLists;}var _proto=CSSPropertyLengthOrPercentage12.prototype;_proto.parser=function parser(radius){var parsed=parseDimensionArray(isNumber(radius)?[radius]:radius);var formatted;if(parsed.length===1){formatted=[parsed[0],parsed[0]];}else {formatted=[parsed[0],parsed[1]];}return formatted;};_proto.calculator=function calculator(name,oldParsed,computed){return computed.map(function(c){return c.value;});};return CSSPropertyLengthOrPercentage12;}();/**
- * used in rounded rect
- *
- * @example
- * rect.style.radius = 10;
- * rect.style.radius = '10 10';
- * rect.style.radius = '10 10 10 10';
- */var CSSPropertyLengthOrPercentage14=/*#__PURE__*/function(){function CSSPropertyLengthOrPercentage14(){this.mixer=mergeNumberLists;}var _proto=CSSPropertyLengthOrPercentage14.prototype;_proto.parser=function parser(radius){var parsed=parseDimensionArray(isNumber(radius)?[radius]:radius);var formatted;// format to Tuple<CSSUnitValue>
- if(parsed.length===1){formatted=[parsed[0],parsed[0],parsed[0],parsed[0]];}else if(parsed.length===2){formatted=[parsed[0],parsed[1],parsed[0],parsed[1]];}else if(parsed.length===3){formatted=[parsed[0],parsed[1],parsed[2],parsed[1]];}else {formatted=[parsed[0],parsed[1],parsed[2],parsed[3]];}return formatted;};_proto.calculator=function calculator(name,oldParsed,computed){return computed.map(function(c){return c.value;});};return CSSPropertyLengthOrPercentage14;}();/**
- * local position
- */var CSSPropertyLocalPosition=/*#__PURE__*/function(_CSSPropertyLengthOrP){_inheritsLoose(CSSPropertyLocalPosition,_CSSPropertyLengthOrP);function CSSPropertyLocalPosition(){return _CSSPropertyLengthOrP.apply(this,arguments)||this;}var _proto=CSSPropertyLocalPosition.prototype;/**
- * update local position
- */_proto.postProcessor=function postProcessor(object,attributes){var x;var y;var z;switch(object.nodeName){case exports.Shape.CIRCLE:case exports.Shape.ELLIPSE:var _object$parsedStyle=object.parsedStyle,cx=_object$parsedStyle.cx,cy=_object$parsedStyle.cy,cz=_object$parsedStyle.cz;if(!isNil(cx)){x=cx;}if(!isNil(cy)){y=cy;}if(!isNil(cz)){z=cz;}break;case exports.Shape.LINE:var _object$parsedStyle2=object.parsedStyle,x1=_object$parsedStyle2.x1,x2=_object$parsedStyle2.x2,y1=_object$parsedStyle2.y1,y2=_object$parsedStyle2.y2;var minX=Math.min(x1,x2);var minY=Math.min(y1,y2);x=minX;y=minY;z=0;break;case exports.Shape.RECT:case exports.Shape.IMAGE:case exports.Shape.GROUP:case exports.Shape.HTML:case exports.Shape.TEXT:case exports.Shape.MESH:if(!isNil(object.parsedStyle.x)){x=object.parsedStyle.x;}if(!isNil(object.parsedStyle.y)){y=object.parsedStyle.y;}if(!isNil(object.parsedStyle.z)){z=object.parsedStyle.z;}break;}if(object.nodeName!==exports.Shape.PATH&&object.nodeName!==exports.Shape.POLYLINE&&object.nodeName!==exports.Shape.POLYGON){object.parsedStyle.defX=x||0;object.parsedStyle.defY=y||0;}var needResetLocalPosition=!isNil(x)||!isNil(y)||!isNil(z);// only if `transform` won't be processed later
- if(needResetLocalPosition&&attributes.indexOf('transform')===-1){// account for current transform if needed
- var transform=object.parsedStyle.transform;if(transform&&transform.length){parsedTransformToMat4(transform,object);}else {var _object$getLocalPosit=object.getLocalPosition(),ox=_object$getLocalPosit[0],oy=_object$getLocalPosit[1],oz=_object$getLocalPosit[2];object.setLocalPosition(isNil(x)?ox:x,isNil(y)?oy:y,isNil(z)?oz:z);}}};return CSSPropertyLocalPosition;}(CSSPropertyLengthOrPercentage);var CSSPropertyMarker=/*#__PURE__*/function(){function CSSPropertyMarker(){}var _proto=CSSPropertyMarker.prototype;_proto.calculator=function calculator(name,oldMarker,newMarker,object){var _newMarker;// unset
- if(newMarker instanceof CSSKeywordValue){newMarker=null;}var cloned=(_newMarker=newMarker)===null||_newMarker===void 0?void 0:_newMarker.cloneNode(true);if(cloned){// FIXME: SVG should not inherit parent's style, add a flag here
- cloned.style.isMarker=true;}return cloned;};return CSSPropertyMarker;}();var CSSPropertyNumber=/*#__PURE__*/function(){function CSSPropertyNumber(){this.mixer=mergeNumbers;this.parser=parseNumber;this.parserWithCSSDisabled=null;}var _proto=CSSPropertyNumber.prototype;_proto.calculator=function calculator(name,oldParsed,computed){return computed.value;};return CSSPropertyNumber;}();var CSSPropertyOffsetDistance=/*#__PURE__*/function(){function CSSPropertyOffsetDistance(){this.parser=parseNumber;this.parserWithCSSDisabled=null;this.mixer=clampedMergeNumbers(0,1);}var _proto=CSSPropertyOffsetDistance.prototype;_proto.calculator=function calculator(name,oldParsed,computed){return computed.value;};_proto.postProcessor=function postProcessor(object){var _object$parsedStyle=object.parsedStyle,offsetPath=_object$parsedStyle.offsetPath,offsetDistance=_object$parsedStyle.offsetDistance;if(!offsetPath){return;}var nodeName=offsetPath.nodeName;if(nodeName===exports.Shape.LINE||nodeName===exports.Shape.PATH||nodeName===exports.Shape.POLYLINE){// set position in world space
- var point=offsetPath.getPoint(offsetDistance);if(point){object.parsedStyle.defX=point.x;object.parsedStyle.defY=point.y;object.setLocalPosition(point.x,point.y);}}};return CSSPropertyOffsetDistance;}();/**
- * opacity
- */var CSSPropertyOpacity=/*#__PURE__*/function(){function CSSPropertyOpacity(){this.parser=parseNumber;this.parserWithCSSDisabled=null;this.mixer=clampedMergeNumbers(0,1);}var _proto=CSSPropertyOpacity.prototype;_proto.calculator=function calculator(name,oldParsed,computed){return computed.value;};return CSSPropertyOpacity;}();/**
- * Axis-Aligned Bounding Box
- * 为了便于后续 Frustum Culling,通过查找表定义 p-vertex 和 n-vertex
- * @see https://github.com/antvis/GWebGPUEngine/issues/3
- */var AABB=/*#__PURE__*/function(){function AABB(){this.center=[0,0,0];this.halfExtents=[0,0,0];this.min=[0,0,0];this.max=[0,0,0];}AABB.isEmpty=function isEmpty(aabb){return !aabb||aabb.halfExtents[0]===0&&aabb.halfExtents[1]===0&&aabb.halfExtents[2]===0;};var _proto=AABB.prototype;// center: vec3 = vec3.create();
- // halfExtents: vec3 = vec3.create();
- // min: vec3 = vec3.create();
- // max: vec3 = vec3.create();
- _proto.update=function update(center,halfExtents){copyVec3(this.center,center);copyVec3(this.halfExtents,halfExtents);subVec3(this.min,this.center,this.halfExtents);addVec3(this.max,this.center,this.halfExtents);// vec3.copy(this.center, center);
- // vec3.copy(this.halfExtents, halfExtents);
- // vec3.sub(this.min, this.center, this.halfExtents);
- // vec3.add(this.max, this.center, this.halfExtents);
- };_proto.setMinMax=function setMinMax(min,max){// vec3.add(this.center, max, min);
- // vec3.scale(this.center, this.center, 0.5);
- // vec3.sub(this.halfExtents, max, min);
- // vec3.scale(this.halfExtents, this.halfExtents, 0.5);
- // vec3.copy(this.min, min);
- // vec3.copy(this.max, max);
- addVec3(this.center,max,min);scaleVec3(this.center,this.center,0.5);subVec3(this.halfExtents,max,min);scaleVec3(this.halfExtents,this.halfExtents,0.5);copyVec3(this.min,min);copyVec3(this.max,max);};_proto.getMin=function getMin(){return this.min;};_proto.getMax=function getMax(){return this.max;};_proto.add=function add(aabb){if(AABB.isEmpty(aabb)){return;}if(AABB.isEmpty(this)){this.setMinMax(aabb.getMin(),aabb.getMax());return;}var tc=this.center;var tcx=tc[0];var tcy=tc[1];var tcz=tc[2];var th=this.halfExtents;var thx=th[0];var thy=th[1];var thz=th[2];var tminx=tcx-thx;var tmaxx=tcx+thx;var tminy=tcy-thy;var tmaxy=tcy+thy;var tminz=tcz-thz;var tmaxz=tcz+thz;var oc=aabb.center;var ocx=oc[0];var ocy=oc[1];var ocz=oc[2];var oh=aabb.halfExtents;var ohx=oh[0];var ohy=oh[1];var ohz=oh[2];var ominx=ocx-ohx;var omaxx=ocx+ohx;var ominy=ocy-ohy;var omaxy=ocy+ohy;var ominz=ocz-ohz;var omaxz=ocz+ohz;if(ominx<tminx){tminx=ominx;}if(omaxx>tmaxx){tmaxx=omaxx;}if(ominy<tminy){tminy=ominy;}if(omaxy>tmaxy){tmaxy=omaxy;}if(ominz<tminz){tminz=ominz;}if(omaxz>tmaxz){tmaxz=omaxz;}tc[0]=(tminx+tmaxx)*0.5;tc[1]=(tminy+tmaxy)*0.5;tc[2]=(tminz+tmaxz)*0.5;th[0]=(tmaxx-tminx)*0.5;th[1]=(tmaxy-tminy)*0.5;th[2]=(tmaxz-tminz)*0.5;this.min[0]=tminx;this.min[1]=tminy;this.min[2]=tminz;this.max[0]=tmaxx;this.max[1]=tmaxy;this.max[2]=tmaxz;};_proto.setFromTransformedAABB=function setFromTransformedAABB(aabb,m){var bc=this.center;var br=this.halfExtents;var ac=aabb.center;var ar=aabb.halfExtents;var mx0=m[0];var mx1=m[4];var mx2=m[8];var my0=m[1];var my1=m[5];var my2=m[9];var mz0=m[2];var mz1=m[6];var mz2=m[10];var mx0a=Math.abs(mx0);var mx1a=Math.abs(mx1);var mx2a=Math.abs(mx2);var my0a=Math.abs(my0);var my1a=Math.abs(my1);var my2a=Math.abs(my2);var mz0a=Math.abs(mz0);var mz1a=Math.abs(mz1);var mz2a=Math.abs(mz2);bc[0]=m[12]+mx0*ac[0]+mx1*ac[1]+mx2*ac[2];bc[1]=m[13]+my0*ac[0]+my1*ac[1]+my2*ac[2];bc[2]=m[14]+mz0*ac[0]+mz1*ac[1]+mz2*ac[2];// vec3.set(
- // bc,
- // m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
- // m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
- // m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2],
- // );
- br[0]=mx0a*ar[0]+mx1a*ar[1]+mx2a*ar[2];br[1]=my0a*ar[0]+my1a*ar[1]+my2a*ar[2];br[2]=mz0a*ar[0]+mz1a*ar[1]+mz2a*ar[2];// vec3.set(
- // br,
- // mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
- // my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
- // mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2],
- // );
- // this.min = vec3.sub(this.min, bc, br);
- // this.max = vec3.add(this.max, bc, br);
- subVec3(this.min,bc,br);addVec3(this.max,bc,br);};_proto.intersects=function intersects(aabb){var aMax=this.getMax();var aMin=this.getMin();var bMax=aabb.getMax();var bMin=aabb.getMin();return aMin[0]<=bMax[0]&&aMax[0]>=bMin[0]&&aMin[1]<=bMax[1]&&aMax[1]>=bMin[1]&&aMin[2]<=bMax[2]&&aMax[2]>=bMin[2];};_proto.intersection=function intersection(aabb){if(!this.intersects(aabb)){return null;}var intersection=new AABB();// const min = vec3.max(vec3.create(), this.getMin(), aabb.getMin());
- // const max = vec3.min(vec3.create(), this.getMax(), aabb.getMax());
- var min=maxVec3([0,0,0],this.getMin(),aabb.getMin());var max=minVec3([0,0,0],this.getMax(),aabb.getMax());intersection.setMinMax(min,max);return intersection;}// containsPoint(point: vec3) {
- // const min = this.getMin();
- // const max = this.getMax();
- // return !(
- // point[0] < min[0] ||
- // point[0] > max[0] ||
- // point[1] < min[1] ||
- // point[1] > max[1] ||
- // point[2] < min[2] ||
- // point[2] > max[2]
- // );
- // }
- /**
- * get n-vertex
- * @param plane plane of CullingVolume
- */;_proto.getNegativeFarPoint=function getNegativeFarPoint(plane){if(plane.pnVertexFlag===0x111){return copyVec3([0,0,0],this.min);// return vec3.copy(vec3.create(), this.min);
- }else if(plane.pnVertexFlag===0x110){return [this.min[0],this.min[1],this.max[2]];// return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
- }else if(plane.pnVertexFlag===0x101){return [this.min[0],this.max[1],this.min[2]];// return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
- }else if(plane.pnVertexFlag===0x100){return [this.min[0],this.max[1],this.max[2]];// return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
- }else if(plane.pnVertexFlag===0x011){return [this.max[0],this.min[1],this.min[2]];// return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
- }else if(plane.pnVertexFlag===0x010){return [this.max[0],this.min[1],this.max[2]];// return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
- }else if(plane.pnVertexFlag===0x001){return [this.max[0],this.max[1],this.min[2]];// return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
- }else {return [this.max[0],this.max[1],this.max[2]];// return vec3.fromValues(this.max[0], this.max[1], this.max[2]);
- }}/**
- * get p-vertex
- * @param plane plane of CullingVolume
- */;_proto.getPositiveFarPoint=function getPositiveFarPoint(plane){if(plane.pnVertexFlag===0x111){return copyVec3([0,0,0],this.max);// return vec3.copy(vec3.create(), this.max);
- }else if(plane.pnVertexFlag===0x110){return [this.max[0],this.max[1],this.min[2]];// return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
- }else if(plane.pnVertexFlag===0x101){return [this.max[0],this.min[1],this.max[2]];// return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
- }else if(plane.pnVertexFlag===0x100){return [this.max[0],this.min[1],this.min[2]];// return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
- }else if(plane.pnVertexFlag===0x011){return [this.min[0],this.max[1],this.max[2]];// return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
- }else if(plane.pnVertexFlag===0x010){return [this.min[0],this.max[1],this.min[2]];// return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
- }else if(plane.pnVertexFlag===0x001){return [this.min[0],this.min[1],this.max[2]];// return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
- }else {return [this.min[0],this.min[1],this.min[2]];// return vec3.fromValues(this.min[0], this.min[1], this.min[2]);
- }};return AABB;}();var Plane=/*#__PURE__*/function(){function Plane(distance,normal){this.distance=void 0;this.normal=void 0;/**
- * lookup table for p-vertex & n-vertex when doing frustum culling
- */this.pnVertexFlag=void 0;this.distance=distance||0;this.normal=normal||fromValues$2(0,1,0);this.updatePNVertexFlag();}var _proto=Plane.prototype;_proto.updatePNVertexFlag=function updatePNVertexFlag(){this.pnVertexFlag=(Number(this.normal[0]>=0)<<8)+(Number(this.normal[1]>=0)<<4)+Number(this.normal[2]>=0);};_proto.distanceToPoint=function distanceToPoint(point){return dot(point,this.normal)-this.distance;};_proto.normalize=function normalize(){var invLen=1/len(this.normal);scale$1(this.normal,this.normal,invLen);this.distance*=invLen;};_proto.intersectsLine=function intersectsLine(start,end,point){var d0=this.distanceToPoint(start);var d1=this.distanceToPoint(end);var t=d0/(d0-d1);var intersects=t>=0&&t<=1;if(intersects&&point){lerp(point,start,end,t);}return intersects;};return Plane;}();(function(Mask){Mask[Mask["OUTSIDE"]=4294967295]="OUTSIDE";Mask[Mask["INSIDE"]=0]="INSIDE";Mask[Mask["INDETERMINATE"]=2147483647]="INDETERMINATE";})(exports.Mask||(exports.Mask={}));var Frustum=/*#__PURE__*/function(){function Frustum(planes){this.planes=[];if(planes){this.planes=planes;}else {for(var i=0;i<6;i++){this.planes.push(new Plane());}}}/**
- * extract 6 planes from projectionMatrix
- * @see http://www8.cs.umu.se/kurser/5DV051/HT12/lab/plane_extraction.pdf
- */var _proto=Frustum.prototype;_proto.extractFromVPMatrix=function extractFromVPMatrix(projectionMatrix){// @ts-ignore
- var m0=projectionMatrix[0],m1=projectionMatrix[1],m2=projectionMatrix[2],m3=projectionMatrix[3],m4=projectionMatrix[4],m5=projectionMatrix[5],m6=projectionMatrix[6],m7=projectionMatrix[7],m8=projectionMatrix[8],m9=projectionMatrix[9],m10=projectionMatrix[10],m11=projectionMatrix[11],m12=projectionMatrix[12],m13=projectionMatrix[13],m14=projectionMatrix[14],m15=projectionMatrix[15];// right
- set$1(this.planes[0].normal,m3-m0,m7-m4,m11-m8);this.planes[0].distance=m15-m12;// left
- set$1(this.planes[1].normal,m3+m0,m7+m4,m11+m8);this.planes[1].distance=m15+m12;// bottom
- set$1(this.planes[2].normal,m3+m1,m7+m5,m11+m9);this.planes[2].distance=m15+m13;// top
- set$1(this.planes[3].normal,m3-m1,m7-m5,m11-m9);this.planes[3].distance=m15-m13;// far
- set$1(this.planes[4].normal,m3-m2,m7-m6,m11-m10);this.planes[4].distance=m15-m14;// near
- set$1(this.planes[5].normal,m3+m2,m7+m6,m11+m10);this.planes[5].distance=m15+m14;this.planes.forEach(function(plane){plane.normalize();plane.updatePNVertexFlag();});};return Frustum;}();var Point=/*#__PURE__*/function(){function Point(x,y){if(x===void 0){x=0;}if(y===void 0){y=0;}this.x=0;this.y=0;this.x=x;this.y=y;}var _proto=Point.prototype;_proto.clone=function clone(){return new Point(this.x,this.y);};_proto.copyFrom=function copyFrom(p){this.x=p.x;this.y=p.y;};return Point;}();var Rectangle=/*#__PURE__*/function(){function Rectangle(x,y,width,height){this.x=void 0;this.y=void 0;this.width=void 0;this.height=void 0;this.left=void 0;this.right=void 0;this.top=void 0;this.bottom=void 0;this.x=x;this.y=y;this.width=width;this.height=height;this.left=x;this.right=x+width;this.top=y;this.bottom=y+height;}var _proto=Rectangle.prototype;_proto.toJSON=function toJSON(){};return Rectangle;}();var CSSPropertyPath=/*#__PURE__*/function(){function CSSPropertyPath(){/**
- * path2Curve
- */this.parser=parsePath;this.parserWithCSSDisabled=parsePath;this.mixer=mergePaths;}var _proto=CSSPropertyPath.prototype;_proto.calculator=function calculator(name,oldParsed,parsed){// unset
- if(parsed instanceof CSSKeywordValue&&parsed.value==='unset'){return {absolutePath:[],hasArc:false,segments:[],polygons:[],polylines:[],curve:null,totalLength:0,rect:new Rectangle(0,0,0,0)};}return parsed;};/**
- * update local position
- */_proto.postProcessor=function postProcessor(object,attributes){if(object.nodeName===exports.Shape.PATH&&attributes.indexOf('transform')===-1){var _object$parsedStyle=object.parsedStyle,_object$parsedStyle$d=_object$parsedStyle.defX,defX=_object$parsedStyle$d===void 0?0:_object$parsedStyle$d,_object$parsedStyle$d2=_object$parsedStyle.defY,defY=_object$parsedStyle$d2===void 0?0:_object$parsedStyle$d2;object.setLocalPosition(defX,defY);}};return CSSPropertyPath;}();var CSSPropertyPoints=/*#__PURE__*/function(){function CSSPropertyPoints(){this.parser=parsePoints;this.mixer=mergePoints;}var _proto=CSSPropertyPoints.prototype;/**
- * update local position
- */_proto.postProcessor=function postProcessor(object,attributes){if((object.nodeName===exports.Shape.POLYGON||object.nodeName===exports.Shape.POLYLINE)&&attributes.indexOf('transform')===-1){var _object$parsedStyle=object.parsedStyle,defX=_object$parsedStyle.defX,defY=_object$parsedStyle.defY;object.setLocalPosition(defX,defY);}};return CSSPropertyPoints;}();var CSSPropertyShadowBlur=/*#__PURE__*/function(_CSSPropertyLengthOrP){_inheritsLoose(CSSPropertyShadowBlur,_CSSPropertyLengthOrP);function CSSPropertyShadowBlur(){var _this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_CSSPropertyLengthOrP.call.apply(_CSSPropertyLengthOrP,[this].concat(args))||this;_this.mixer=clampedMergeNumbers(0,Infinity);return _this;}return CSSPropertyShadowBlur;}(CSSPropertyLengthOrPercentage);var CSSPropertyText=/*#__PURE__*/function(){function CSSPropertyText(){}var _proto=CSSPropertyText.prototype;_proto.calculator=function calculator(name,oldParsed,parsed,object){if(parsed instanceof CSSKeywordValue){if(parsed.value==='unset'){return '';}else {return parsed.value;}}// allow number as valid text content
- return ""+parsed;};_proto.postProcessor=function postProcessor(object){object.nodeValue=""+object.parsedStyle.text||'';};return CSSPropertyText;}();/**
- * it must transform after text get parsed
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform
- */var CSSPropertyTextTransform=/*#__PURE__*/function(){function CSSPropertyTextTransform(){}var _proto=CSSPropertyTextTransform.prototype;_proto.calculator=function calculator(name,oldParsed,parsed,object){var rawText=object.getAttribute('text');if(rawText){var transformedText=rawText;if(parsed.value==='capitalize'){transformedText=rawText.charAt(0).toUpperCase()+rawText.slice(1);}else if(parsed.value==='lowercase'){transformedText=rawText.toLowerCase();}else if(parsed.value==='uppercase'){transformedText=rawText.toUpperCase();}object.parsedStyle.text=transformedText;}return parsed.value;};return CSSPropertyTextTransform;}();/**
- * @see /zh/docs/api/animation#支持变换的属性
- *
- * support the following formats like CSS Transform:
- *
- * scale
- * * scale(x, y)
- * * scaleX(x)
- * * scaleY(x)
- * * scaleZ(z)
- * * scale3d(x, y, z)
- *
- * translate (unit: none, px, %(relative to its bounds))
- * * translate(x, y) eg. translate(0, 0) translate(0, 30px) translate(100%, 100%)
- * * translateX(0)
- * * translateY(0)
- * * translateZ(0)
- * * translate3d(0, 0, 0)
- *
- * rotate (unit: deg rad turn)
- * * rotate(0.5turn) rotate(30deg) rotate(1rad)
- *
- * none
- *
- * unsupported for now:
- * * calc() eg. translate(calc(100% + 10px))
- * * matrix/matrix3d()
- * * skew/skewX/skewY
- * * perspective
- */var CSSPropertyTransform=/*#__PURE__*/function(){function CSSPropertyTransform(){this.parser=parseTransform;this.parserWithCSSDisabled=parseTransform;this.mixer=mergeTransforms;}var _proto=CSSPropertyTransform.prototype;_proto.calculator=function calculator(name,oldParsed,parsed,object){// 'none'
- if(parsed instanceof CSSKeywordValue){return [];}return parsed;};_proto.postProcessor=function postProcessor(object){var transform=object.parsedStyle.transform;parsedTransformToMat4(transform,object);};return CSSPropertyTransform;}();/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
- * @example
- * [10px, 10px] [10%, 10%]
- */var CSSPropertyTransformOrigin=function CSSPropertyTransformOrigin(){this.parser=parseTransformOrigin;};/**
- * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
- */(function(Strategy){Strategy[Strategy["Standard"]=0]="Standard";})(exports.Strategy||(exports.Strategy={}));(function(SortReason){SortReason[SortReason["ADDED"]=0]="ADDED";SortReason[SortReason["REMOVED"]=1]="REMOVED";SortReason[SortReason["Z_INDEX_CHANGED"]=2]="Z_INDEX_CHANGED";})(exports.SortReason||(exports.SortReason={}));var CSSPropertyZIndex=/*#__PURE__*/function(){function CSSPropertyZIndex(){this.parser=parseNumber;}var _proto=CSSPropertyZIndex.prototype;_proto.calculator=function calculator(name,oldParsed,computed,object){return computed.value;};_proto.postProcessor=function postProcessor(object){if(object.parentNode){var parentEntity=object.parentNode;var parentRenderable=parentEntity.renderable;var parentSortable=parentEntity.sortable;if(parentRenderable){parentRenderable.dirty=true;}// need re-sort on parent
- if(parentSortable){parentSortable.dirty=true;parentSortable.dirtyReason=exports.SortReason.Z_INDEX_CHANGED;}}};return CSSPropertyZIndex;}();/**
- * canvas.customElements
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
- */var CustomElementRegistry=/*#__PURE__*/function(){function CustomElementRegistry(){this.registry={};this.define(exports.Shape.CIRCLE,Circle);this.define(exports.Shape.ELLIPSE,Ellipse);this.define(exports.Shape.RECT,Rect);this.define(exports.Shape.IMAGE,Image);this.define(exports.Shape.LINE,Line);this.define(exports.Shape.GROUP,Group);this.define(exports.Shape.PATH,Path);this.define(exports.Shape.POLYGON,Polygon);this.define(exports.Shape.POLYLINE,Polyline);this.define(exports.Shape.TEXT,Text);this.define(exports.Shape.HTML,HTML);}var _proto=CustomElementRegistry.prototype;_proto.define=function define(name,constructor){this.registry[name]=constructor;}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/get
- */;_proto.get=function get(name){return this.registry[name];};return CustomElementRegistry;}();function isFederatedEvent(value){return !!value.type;}/**
- * An DOM-compatible synthetic event implementation that is "forwarded" on behalf of an original
- * FederatedEvent or native {@link https://dom.spec.whatwg.org/#event Event}.
- */var FederatedEvent=/*#__PURE__*/function(){/**
- * The event boundary which manages this event. Propagation can only occur
- * within the boundary's jurisdiction.
- */function FederatedEvent(manager){/**
- * The type of event, supports the following:
- * * pointerdown
- * * touchstart
- * * mousedown
- * * rightdown
- * * ...
- */this.type=void 0;/**
- * The propagation phase.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
- */this.eventPhase=FederatedEvent.prototype.NONE;/**
- * can be used to implement event delegation
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
- */this.target=void 0;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles
- */this.bubbles=true;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/cancelBubble
- */this.cancelBubble=true;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
- */this.cancelable=false;/** the event target when listeners binded */this.currentTarget=void 0;/** Flags whether the default response of the user agent was prevent through this event. */this.defaultPrevented=false;/**
- * timestamp when the event created
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/timeStamp
- */this.timeStamp=void 0;/**
- * the original event.
- */this.nativeEvent=void 0;/** The original event that caused this event, if any. */this.originalEvent=void 0;/** Flags whether propagation was stopped. */this.propagationStopped=false;/** Flags whether propagation was immediately stopped. */this.propagationImmediatelyStopped=false;this.manager=void 0;/** Event-specific detail */this.detail=void 0;/**
- * The coordinates of the evnet relative to the nearest DOM layer.
- * This is a non-standard property.
- */this.layer=new Point();/**
- * The coordinates of the event relative to the DOM document.
- * This is a non-standard property.
- * relative to the DOM document.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/pageX
- */this.page=new Point();/**
- * relative to Canvas, origin is left-top
- */this.canvas=new Point();/**
- * relative to Viewport, account for Camera
- */this.viewport=new Point();this.path=void 0;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
- */this.view=void 0;this.which=void 0;this.returnValue=void 0;this.srcElement=void 0;this.composed=false;this.isTrusted=void 0;this.NONE=0;this.CAPTURING_PHASE=1;this.AT_TARGET=2;this.BUBBLING_PHASE=3;this.manager=manager;}var _proto=FederatedEvent.prototype;/**
- * The propagation path for this event
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/composedPath
- *
- * So composedPath()[0] represents the original target.
- * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events#retargeting
- */_proto.composedPath=function composedPath(){if(this.manager&&(!this.path||this.path[0]!==this.target)){this.path=this.target?this.manager.propagationPath(this.target):[];}return this.path;}/**
- * @deprecated
- */;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
- */_proto.preventDefault=function preventDefault(){if(this.nativeEvent instanceof Event&&this.nativeEvent.cancelable){this.nativeEvent.preventDefault();}this.defaultPrevented=true;}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopImmediatePropagation
- */;_proto.stopImmediatePropagation=function stopImmediatePropagation(){this.propagationImmediatelyStopped=true;}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation
- */;_proto.stopPropagation=function stopPropagation(){this.propagationStopped=true;};/**
- * added for compatibility with DOM Event,
- * deprecated props and methods
- */_proto.initEvent=function initEvent(){};_proto.initUIEvent=function initUIEvent(){};_proto.clone=function clone(){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_createClass(FederatedEvent,[{key:"name",get:/**
- * @deprecated
- */function get(){return this.type;}},{key:"layerX",get:function get(){return this.layer.x;}},{key:"layerY",get:function get(){return this.layer.y;}},{key:"pageX",get:function get(){return this.page.x;}},{key:"pageY",get:function get(){return this.page.y;}},{key:"x",get:function get(){return this.canvas.x;}},{key:"y",get:function get(){return this.canvas.y;}},{key:"canvasX",get:function get(){return this.canvas.x;}},{key:"canvasY",get:function get(){return this.canvas.y;}},{key:"viewportX",get:function get(){return this.viewport.x;}},{key:"viewportY",get:function get(){return this.viewport.y;}},{key:"propagationPath",get:function get(){return this.composedPath();}}]);return FederatedEvent;}();/**
- * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
- *
- * @example
- const event = new CustomEvent('build', { detail: { prop1: 'xx' } });
- circle.addEventListener('build', (e) => {
- e.target; // circle
- e.detail; // { prop1: 'xx' }
- });
- circle.dispatchEvent(event);
- */var CustomEvent=/*#__PURE__*/function(_FederatedEvent){_inheritsLoose(CustomEvent,_FederatedEvent);// eslint-disable-next-line @typescript-eslint/ban-types
- function CustomEvent(eventName,object){var _this;_this=_FederatedEvent.call(this,null)||this;_this.type=eventName;_this.detail=object;// compatible with G 3.0
- Object.assign(_assertThisInitialized(_this),object);return _this;}return CustomEvent;}(FederatedEvent);var DELEGATION_SPLITTER=':';/**
- * Objects that can receive events and may have listeners for them.
- * eg. Element, Canvas, DisplayObject
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
- */var EventTarget=/*#__PURE__*/function(){function EventTarget(){/**
- * event emitter
- */this.emitter=new eventemitter3();}var _proto=EventTarget.prototype;/**
- * @deprecated
- * @alias addEventListener
- */_proto.on=function on(type,listener,options){this.addEventListener(type,listener,options);return this;}/**
- * support `capture` & `once` in options
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
- */;_proto.addEventListener=function addEventListener(type,listener,options){var capture=isBoolean(options)&&options||isObject(options)&&options.capture;var once=isObject(options)&&options.once;var context=isFunction(listener)?undefined:listener;// compatible with G 3.0
- // support using delegate name in event type, eg. 'node:click'
- var useDelegatedName=false;var delegatedName='';if(type.indexOf(DELEGATION_SPLITTER)>-1){var _type$split=type.split(DELEGATION_SPLITTER),name=_type$split[0],eventType=_type$split[1];type=eventType;delegatedName=name;useDelegatedName=true;}type=capture?type+"capture":type;listener=isFunction(listener)?listener:listener.handleEvent;// compatible with G 3.0
- if(useDelegatedName){var originListener=listener;listener=function listener(){var _args$0$target;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}if(((_args$0$target=args[0].target)===null||_args$0$target===void 0?void 0:_args$0$target.name)!==delegatedName){return;}// @ts-ignore
- originListener.apply(void 0,args);};}if(once){this.emitter.once(type,listener,context);}else {this.emitter.on(type,listener,context);}return this;}/**
- * @deprecated
- * @alias removeEventListener
- */;_proto.off=function off(type,listener,options){if(type){this.removeEventListener(type,listener,options);}else {// remove all listeners
- this.removeAllEventListeners();}return this;};_proto.removeAllEventListeners=function removeAllEventListeners(){this.emitter.removeAllListeners();};_proto.removeEventListener=function removeEventListener(type,listener,options){var _listener;var capture=isBoolean(options)&&options||isObject(options)&&options.capture;var context=isFunction(listener)?undefined:listener;type=capture?type+"capture":type;listener=isFunction(listener)?listener:(_listener=listener)===null||_listener===void 0?void 0:_listener.handleEvent;this.emitter.off(type,listener,context);return this;}/**
- * @deprecated
- * @alias dispatchEvent
- */ // eslint-disable-next-line @typescript-eslint/ban-types
- ;_proto.emit=function emit(eventName,object){this.dispatchEvent(new CustomEvent(eventName,object));}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
- */;_proto.dispatchEvent=function dispatchEvent(e,skipPropagate){if(skipPropagate===void 0){skipPropagate=false;}if(!isFederatedEvent(e)){throw new Error('DisplayObject cannot propagate events outside of the Federated Events API');}// should account for Element / Document / Canvas
- var canvas;// @ts-ignore
- if(this.document){canvas=this;// @ts-ignore
- }else if(this.defaultView){canvas=this.defaultView;}else {var _this$ownerDocument;canvas=(_this$ownerDocument=this.ownerDocument)===null||_this$ownerDocument===void 0?void 0:_this$ownerDocument.defaultView;}// assign event manager
- if(canvas){var _e$manager;e.manager=canvas.getEventService()||null;if(!e.manager){return false;}e.defaultPrevented=false;e.path=[];if(!skipPropagate){e.target=this;}(_e$manager=e.manager)===null||_e$manager===void 0?void 0:_e$manager.dispatchEvent(e,e.type,skipPropagate);}return !e.defaultPrevented;};return EventTarget;}();/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node
- */var Node=/*#__PURE__*/function(_EventTarget){_inheritsLoose(Node,_EventTarget);function Node(){var _this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_EventTarget.call.apply(_EventTarget,[this].concat(args))||this;_this.shadow=false;/**
- * points to canvas.document
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument
- */_this.ownerDocument=null;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isConnected
- * @example
- circle.isConnected; // false
- canvas.appendChild(circle);
- circle.isConnected; // true
- */_this.isConnected=false;/**
- * Returns node's node document's document base URL.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node
- */_this.baseURI='';/**
- * Returns the children.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
- */_this.childNodes=[];/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
- */_this.nodeType=0;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeName
- */_this.nodeName='';/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeValue
- */_this.nodeValue=null;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode
- */_this.parentNode=null;return _this;}Node.isNode=function isNode(target){return !!target.childNodes;};var _proto=Node.prototype;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/getRootNode
- */_proto.getRootNode=function getRootNode(opts){if(opts===void 0){opts={};}if(this.parentNode){return this.parentNode.getRootNode(opts);}if(opts.composed&&this.host){return this.host.getRootNode(opts);}return this;};_proto.hasChildNodes=function hasChildNodes(){return this.childNodes.length>0;};_proto.isDefaultNamespace=function isDefaultNamespace(namespace){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.lookupNamespaceURI=function lookupNamespaceURI(prefix){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.lookupPrefix=function lookupPrefix(namespace){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.normalize=function normalize(){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isEqualNode
- */;_proto.isEqualNode=function isEqualNode(otherNode){// TODO: compare 2 nodes, not sameness
- return this===otherNode;};_proto.isSameNode=function isSameNode(otherNode){return this.isEqualNode(otherNode);};/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
- * @see https://github.com/b-fuze/deno-dom/blob/master/src/dom/node.ts#L338
- */_proto.compareDocumentPosition=function compareDocumentPosition(other){if(other===this){// same node
- return 0;}// if (!(other instanceof Node)) {
- // throw new TypeError(
- // 'Node.compareDocumentPosition: Argument 1 does not implement interface Node.',
- // );
- // }
- var node1Root=other;// eslint-disable-next-line @typescript-eslint/no-this-alias
- var node2Root=this;var node1Hierarchy=[node1Root];var node2Hierarchy=[node2Root];while((_node1Root$parentNode=node1Root.parentNode)!==null&&_node1Root$parentNode!==void 0?_node1Root$parentNode:node2Root.parentNode){var _node1Root$parentNode;node1Root=node1Root.parentNode?(node1Hierarchy.push(node1Root.parentNode),node1Root.parentNode):node1Root;node2Root=node2Root.parentNode?(node2Hierarchy.push(node2Root.parentNode),node2Root.parentNode):node2Root;}// Check if they don't share the same root node
- if(node1Root!==node2Root){return Node.DOCUMENT_POSITION_DISCONNECTED|Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC|Node.DOCUMENT_POSITION_PRECEDING;}var longerHierarchy=node1Hierarchy.length>node2Hierarchy.length?node1Hierarchy:node2Hierarchy;var shorterHierarchy=longerHierarchy===node1Hierarchy?node2Hierarchy:node1Hierarchy;// Check if either is a container of the other
- if(longerHierarchy[longerHierarchy.length-shorterHierarchy.length]===shorterHierarchy[0]){return longerHierarchy===node1Hierarchy?// other is a child of this
- Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING:// this is a child of other
- Node.DOCUMENT_POSITION_CONTAINS|Node.DOCUMENT_POSITION_PRECEDING;}// Find their first common ancestor and see whether they
- // are preceding or following
- var longerStart=longerHierarchy.length-shorterHierarchy.length;for(var i=shorterHierarchy.length-1;i>=0;i--){var shorterHierarchyNode=shorterHierarchy[i];var longerHierarchyNode=longerHierarchy[longerStart+i];// We found the first common ancestor
- if(longerHierarchyNode!==shorterHierarchyNode){var siblings=shorterHierarchyNode.parentNode.childNodes;if(siblings.indexOf(shorterHierarchyNode)<siblings.indexOf(longerHierarchyNode)){// Shorter is before longer
- if(shorterHierarchy===node1Hierarchy){// Other is before this
- return Node.DOCUMENT_POSITION_PRECEDING;}else {// This is before other
- return Node.DOCUMENT_POSITION_FOLLOWING;}}else {// Longer is before shorter
- if(longerHierarchy===node1Hierarchy){// Other is before this
- return Node.DOCUMENT_POSITION_PRECEDING;}else {// Other is after this
- return Node.DOCUMENT_POSITION_FOLLOWING;}}}}return Node.DOCUMENT_POSITION_FOLLOWING;}/**
- * @deprecated
- * @alias contains
- */;_proto.contain=function contain(other){return this.contains(other);};_proto.contains=function contains(other){// the node itself, one of its direct children
- var tmp=other;// @see https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
- while(tmp&&this!==tmp){tmp=tmp.parentNode;}return !!tmp;};_proto.getAncestor=function getAncestor(n){// eslint-disable-next-line @typescript-eslint/no-this-alias
- var temp=this;while(n>0&&temp){temp=temp.parentNode;n--;}return temp;};_proto.forEach=function forEach(callback,assigned){if(assigned===void 0){assigned=false;}if(!callback(this)){(assigned?this.childNodes.slice():this.childNodes).forEach(function(child){child.forEach(callback);});}};_createClass(Node,[{key:"textContent",get:/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent
- */function get(){var out='';if(this.nodeName===exports.Shape.TEXT){// @ts-ignore
- out+=this.style.text;}for(var _iterator=_createForOfIteratorHelperLoose(this.childNodes),_step;!(_step=_iterator()).done;){var child=_step.value;if(child.nodeName===exports.Shape.TEXT){out+=child.nodeValue;}else {out+=child.textContent;}}return out;},set:function set(content){var _this2=this;// remove all children
- this.childNodes.slice().forEach(function(child){_this2.removeChild(child);});if(this.nodeName===exports.Shape.TEXT){// @ts-ignore
- this.style.text=""+content;}}},{key:"parent",get:/**
- * @deprecated
- * @alias parentNode
- */function get(){return this.parentNode;}},{key:"parentElement",get:function get(){return null;}},{key:"nextSibling",get:function get(){return null;}},{key:"previousSibling",get:function get(){return null;}},{key:"firstChild",get:function get(){return this.childNodes.length>0?this.childNodes[0]:null;}},{key:"lastChild",get:function get(){return this.childNodes.length>0?this.childNodes[this.childNodes.length-1]:null;}}]);return Node;}(EventTarget);/**
- * Both nodes are in different documents or different trees in the same document.
- */Node.DOCUMENT_POSITION_DISCONNECTED=1;/**
- * otherNode precedes the node in either a pre-order depth-first traversal
- * of a tree containing both (e.g., as an ancestor or previous sibling or a descendant of a previous sibling or previous sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
- */Node.DOCUMENT_POSITION_PRECEDING=2;/**
- * otherNode follows the node in either a pre-order depth-first traversal of a tree containing both (e.g., as a descendant or following sibling or a descendant of a following sibling or following sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
- */Node.DOCUMENT_POSITION_FOLLOWING=4;/**
- * otherNode is an ancestor of the node.
- */Node.DOCUMENT_POSITION_CONTAINS=8;/**
- * otherNode is a descendant of the node.
- */Node.DOCUMENT_POSITION_CONTAINED_BY=16;/**
- * The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable.
- */Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC=32;/**
- * the entry of DOM tree
- * Document -> Node -> EventTarget
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
- */var Document=/*#__PURE__*/function(_Node){_inheritsLoose(Document,_Node);function Document(){var _this;_this=_Node.call(this)||this;/**
- * only document has defaultView, points to canvas,
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView
- */_this.defaultView=null;/**
- * the root element of document, eg. <html>
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement
- */_this.documentElement=void 0;/**
- * document.timeline in WAAPI
- */_this.timeline=void 0;_this.ownerDocument=null;_this.nodeName='document';// create timeline
- try{_this.timeline=new runtime.AnimationTimeline(_assertThisInitialized(_this));}catch(e){}/**
- * for inherited properties, the initial value is used on the root element only,
- * as long as no specified value is supplied.
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value
- */var initialStyle={};BUILT_IN_PROPERTIES.forEach(function(_ref){var n=_ref.n,inh=_ref.inh,d=_ref.d;if(inh&&d){initialStyle[n]=isFunction(d)?d(exports.Shape.GROUP):d;}});// like <html> in DOM tree
- _this.documentElement=new Group({id:'g-root',style:initialStyle});_this.documentElement.ownerDocument=_assertThisInitialized(_this);_this.documentElement.parentNode=_assertThisInitialized(_this);_this.childNodes=[_this.documentElement];return _this;}var _proto=Document.prototype;/**
- * @example const circle = document.createElement('circle', { style: { r: 10 } });
- */_proto.createElement=function createElement(tagName,options){// @observablehq/plot will create <svg>
- if(tagName==='svg'){return this.documentElement;}// d3 will use <tspan>
- var clazz=this.defaultView.customElements.get(tagName);if(!clazz){console.warn('Unsupported tagName: ',tagName);clazz=tagName==='tspan'?Text:Group;}var shape=new clazz(options);shape.ownerDocument=this;return shape;};_proto.createElementNS=function createElementNS(namespaceURI,tagName,options){return this.createElement(tagName,options);};_proto.cloneNode=function cloneNode(deep){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.destroy=function destroy(){try{this.documentElement.destroyChildren();this.timeline.destroy();}catch(e){}}/**
- * Picking 2D graphics with RBush based on BBox, fast but inaccurate.
- */;_proto.elementsFromBBox=function elementsFromBBox(minX,minY,maxX,maxY){var rBush=this.defaultView.context.rBushRoot;var rBushNodes=rBush.search({minX:minX,minY:minY,maxX:maxX,maxY:maxY});var hitTestList=[];rBushNodes.forEach(function(_ref2){var displayObject=_ref2.displayObject;var pointerEvents=displayObject.parsedStyle.pointerEvents;// account for `visibility`
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
- var isVisibilityAffected=['auto','visiblepainted','visiblefill','visiblestroke','visible'].includes(pointerEvents);if((!isVisibilityAffected||isVisibilityAffected&&displayObject.isVisible())&&!displayObject.isCulled()&&displayObject.isInteractive()){hitTestList.push(displayObject);}});// find group with max z-index
- hitTestList.sort(function(a,b){return b.sortable.renderOrder-a.sortable.renderOrder;});return hitTestList;};_proto.elementFromPointSync=function elementFromPointSync(x,y){var _this$defaultView$can=this.defaultView.canvas2Viewport({x:x,y:y}),viewportX=_this$defaultView$can.x,viewportY=_this$defaultView$can.y;var _this$defaultView$get=this.defaultView.getConfig(),width=_this$defaultView$get.width,height=_this$defaultView$get.height;// outside canvas' viewport
- if(viewportX<0||viewportY<0||viewportX>width||viewportY>height){return null;}var _this$defaultView$vie=this.defaultView.viewport2Client({x:viewportX,y:viewportY}),clientX=_this$defaultView$vie.x,clientY=_this$defaultView$vie.y;var _this$defaultView$get2=this.defaultView.getRenderingService().hooks.pickSync.call({topmost:true,position:{x:x,y:y,viewportX:viewportX,viewportY:viewportY,clientX:clientX,clientY:clientY},picked:[]}),picked=_this$defaultView$get2.picked;return picked&&picked[0]||this.documentElement;}/**
- * Do picking with API instead of triggering interactive events.
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementFromPoint
- */;_proto.elementFromPoint=/*#__PURE__*/function(){var _elementFromPoint=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(x,y){var _this$defaultView$can2,viewportX,viewportY,_this$defaultView$get3,width,height,_this$defaultView$vie2,clientX,clientY,_yield$this$defaultVi,picked;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_this$defaultView$can2=this.defaultView.canvas2Viewport({x:x,y:y}),viewportX=_this$defaultView$can2.x,viewportY=_this$defaultView$can2.y;_this$defaultView$get3=this.defaultView.getConfig(),width=_this$defaultView$get3.width,height=_this$defaultView$get3.height;// outside canvas' viewport
- if(!(viewportX<0||viewportY<0||viewportX>width||viewportY>height)){_context.next=4;break;}return _context.abrupt("return",null);case 4:_this$defaultView$vie2=this.defaultView.viewport2Client({x:viewportX,y:viewportY}),clientX=_this$defaultView$vie2.x,clientY=_this$defaultView$vie2.y;_context.next=7;return this.defaultView.getRenderingService().hooks.pick.promise({topmost:true,position:{x:x,y:y,viewportX:viewportX,viewportY:viewportY,clientX:clientX,clientY:clientY},picked:[]});case 7:_yield$this$defaultVi=_context.sent;picked=_yield$this$defaultVi.picked;return _context.abrupt("return",picked&&picked[0]||this.documentElement);case 10:case"end":return _context.stop();}},_callee,this);}));function elementFromPoint(_x,_x2){return _elementFromPoint.apply(this,arguments);}return elementFromPoint;}();_proto.elementsFromPointSync=function elementsFromPointSync(x,y){var _this$defaultView$can3=this.defaultView.canvas2Viewport({x:x,y:y}),viewportX=_this$defaultView$can3.x,viewportY=_this$defaultView$can3.y;var _this$defaultView$get4=this.defaultView.getConfig(),width=_this$defaultView$get4.width,height=_this$defaultView$get4.height;// outside canvas' viewport
- if(viewportX<0||viewportY<0||viewportX>width||viewportY>height){return [];}var _this$defaultView$vie3=this.defaultView.viewport2Client({x:viewportX,y:viewportY}),clientX=_this$defaultView$vie3.x,clientY=_this$defaultView$vie3.y;var _this$defaultView$get5=this.defaultView.getRenderingService().hooks.pickSync.call({topmost:false,position:{x:x,y:y,viewportX:viewportX,viewportY:viewportY,clientX:clientX,clientY:clientY},picked:[]}),picked=_this$defaultView$get5.picked;if(picked[picked.length-1]!==this.documentElement){picked.push(this.documentElement);}return picked;}/**
- * Do picking with API instead of triggering interactive events.
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementsFromPoint
- */;_proto.elementsFromPoint=/*#__PURE__*/function(){var _elementsFromPoint=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(x,y){var _this$defaultView$can4,viewportX,viewportY,_this$defaultView$get6,width,height,_this$defaultView$vie4,clientX,clientY,_yield$this$defaultVi2,picked;return _regeneratorRuntime().wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_this$defaultView$can4=this.defaultView.canvas2Viewport({x:x,y:y}),viewportX=_this$defaultView$can4.x,viewportY=_this$defaultView$can4.y;_this$defaultView$get6=this.defaultView.getConfig(),width=_this$defaultView$get6.width,height=_this$defaultView$get6.height;// outside canvas' viewport
- if(!(viewportX<0||viewportY<0||viewportX>width||viewportY>height)){_context2.next=4;break;}return _context2.abrupt("return",[]);case 4:_this$defaultView$vie4=this.defaultView.viewport2Client({x:viewportX,y:viewportY}),clientX=_this$defaultView$vie4.x,clientY=_this$defaultView$vie4.y;_context2.next=7;return this.defaultView.getRenderingService().hooks.pick.promise({topmost:false,position:{x:x,y:y,viewportX:viewportX,viewportY:viewportY,clientX:clientX,clientY:clientY},picked:[]});case 7:_yield$this$defaultVi2=_context2.sent;picked=_yield$this$defaultVi2.picked;if(picked[picked.length-1]!==this.documentElement){picked.push(this.documentElement);}return _context2.abrupt("return",picked);case 11:case"end":return _context2.stop();}},_callee2,this);}));function elementsFromPoint(_x3,_x4){return _elementsFromPoint.apply(this,arguments);}return elementsFromPoint;}()/**
- * eg. Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
- */;_proto.appendChild=function appendChild(newChild,index){throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);};_proto.insertBefore=function insertBefore(newChild,refChild){throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);};_proto.removeChild=function removeChild(oldChild,destroy){throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);};_proto.replaceChild=function replaceChild(newChild,oldChild,destroy){throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);};_proto.append=function append(){throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);};_proto.prepend=function prepend(){throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);}/**
- * Execute query on documentElement.
- */;_proto.getElementById=function getElementById(id){return this.documentElement.getElementById(id);};_proto.getElementsByName=function getElementsByName(name){return this.documentElement.getElementsByName(name);};_proto.getElementsByTagName=function getElementsByTagName(tagName){return this.documentElement.getElementsByTagName(tagName);};_proto.getElementsByClassName=function getElementsByClassName(className){return this.documentElement.getElementsByClassName(className);};_proto.querySelector=function querySelector(selectors){return this.documentElement.querySelector(selectors);};_proto.querySelectorAll=function querySelectorAll(selectors){return this.documentElement.querySelectorAll(selectors);};_proto.find=function find(filter){return this.documentElement.find(filter);};_proto.findAll=function findAll(filter){return this.documentElement.findAll(filter);};_createClass(Document,[{key:"children",get:function get(){return this.childNodes;}},{key:"childElementCount",get:function get(){return this.childNodes.length;}},{key:"firstElementChild",get:function get(){return this.firstChild;}},{key:"lastElementChild",get:function get(){return this.lastChild;}}]);return Document;}(Node);/**
- * built-in events for element
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
- *
- * TODO: use MutationObserver instead
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
- */(function(ElementEvent){ElementEvent["REPARENT"]="reparent";ElementEvent["DESTROY"]="destroy";/**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified
- */ElementEvent["ATTR_MODIFIED"]="DOMAttrModified";/**
- * it has been inserted
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted
- */ElementEvent["INSERTED"]="DOMNodeInserted";/**
- * it is being removed
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved
- */ElementEvent["REMOVED"]="removed";/**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnodeinsertedintodocument
- */ElementEvent["MOUNTED"]="DOMNodeInsertedIntoDocument";/**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnoderemovedfromdocument
- */ElementEvent["UNMOUNTED"]="DOMNodeRemovedFromDocument";ElementEvent["BOUNDS_CHANGED"]="bounds-changed";ElementEvent["CULLED"]="culled";})(exports.ElementEvent||(exports.ElementEvent={}));var MutationEvent=/*#__PURE__*/function(_FederatedEvent){_inheritsLoose(MutationEvent,_FederatedEvent);function MutationEvent(typeArg,relatedNode,prevValue,newValue,attrName,attrChange,prevParsedValue,newParsedValue){var _this;_this=_FederatedEvent.call(this,null)||this;_this.relatedNode=void 0;_this.prevValue=void 0;_this.newValue=void 0;_this.attrName=void 0;_this.attrChange=void 0;_this.prevParsedValue=void 0;_this.newParsedValue=void 0;_this.relatedNode=relatedNode;_this.prevValue=prevValue;_this.newValue=newValue;_this.attrName=attrName;_this.attrChange=attrChange;_this.prevParsedValue=prevParsedValue;_this.newParsedValue=newParsedValue;_this.type=typeArg;return _this;}return MutationEvent;}(FederatedEvent);MutationEvent.ADDITION=2;MutationEvent.MODIFICATION=1;MutationEvent.REMOVAL=3;var entityCounter=0;function resetEntityCounter(){entityCounter=0;}var insertedEvent=new MutationEvent(exports.ElementEvent.INSERTED,null,'','','',0,'','');var removedEvent=new MutationEvent(exports.ElementEvent.REMOVED,null,'','','',0,'','');var destroyEvent=new CustomEvent(exports.ElementEvent.DESTROY);/**
- * Has following capabilities:
- * * Node insert/remove, eg. appendChild, removeChild, remove...
- * * Query eg. querySelector getElementById...
- * * Animation
- */var Element=/*#__PURE__*/function(_Node){_inheritsLoose(Element,_Node);function Element(){var _this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_Node.call.apply(_Node,[this].concat(args))||this;/**
- * Unique id.
- */_this.entity=entityCounter++;_this.renderable={bounds:undefined,boundsDirty:true,renderBounds:undefined,renderBoundsDirty:true,dirtyRenderBounds:undefined,dirty:false,proxyNodeName:undefined};_this.cullable={strategy:exports.Strategy.Standard,visibilityPlaneMask:-1,visible:true,enable:true};_this.transformable={dirtyFlag:false,localDirtyFlag:false,frozen:false,localPosition:[0,0,0],localRotation:[0,0,0,1],localScale:[1,1,1],localTransform:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],localSkew:[0,0],position:[0,0,0],rotation:[0,0,0,1],scaling:[1,1,1],worldTransform:[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],origin:[0,0,0]};_this.sortable={dirty:false,sorted:undefined,renderOrder:0,dirtyChildren:[],dirtyReason:undefined};_this.geometry={contentBounds:undefined,renderBounds:undefined};_this.rBushNode={aabb:undefined};/**
- * used with `getElementById()`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/id
- */_this.id=void 0;/**
- * used in `getElementsByName`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
- */_this.name=void 0;/**
- * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/namespaceURI
- */_this.namespaceURI='g';_this.scrollLeft=0;_this.scrollTop=0;/**
- * We don't support border now
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
- */_this.clientTop=0;_this.clientLeft=0;/**
- * is destroyed or not
- */_this.destroyed=false;/**
- * compatible with `style`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
- */_this.style={};_this.computedStyle=runtime.enableCSSParsing?{anchor:unsetKeywordValue,opacity:unsetKeywordValue,fillOpacity:unsetKeywordValue,strokeOpacity:unsetKeywordValue,fill:unsetKeywordValue,stroke:unsetKeywordValue,transform:unsetKeywordValue,transformOrigin:unsetKeywordValue,visibility:unsetKeywordValue,pointerEvents:unsetKeywordValue,lineWidth:unsetKeywordValue,lineCap:unsetKeywordValue,lineJoin:unsetKeywordValue,increasedLineWidthForHitTesting:unsetKeywordValue,fontSize:unsetKeywordValue,fontFamily:unsetKeywordValue,fontStyle:unsetKeywordValue,fontWeight:unsetKeywordValue,fontVariant:unsetKeywordValue,textAlign:unsetKeywordValue,textBaseline:unsetKeywordValue,textTransform:unsetKeywordValue,zIndex:unsetKeywordValue,filter:unsetKeywordValue,shadowType:unsetKeywordValue}:null;/**
- * Renderers will use these used values.
- */_this.parsedStyle={// opacity: '',
- // fillOpacity: '',
- // strokeOpacity: '',
- // transformOrigin: '',
- // visibility: '',
- // pointerEvents: '',
- // lineWidth: '',
- // lineCap: '',
- // lineJoin: '',
- // increasedLineWidthForHitTesting: '',
- // fontSize: '',
- // fontFamily: '',
- // fontStyle: '',
- // fontWeight: '',
- // fontVariant: '',
- // textAlign: '',
- // textBaseline: '',
- // textTransform: '',
- };/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
- */_this.attributes={};return _this;}Element.isElement=function isElement(target){return !!target.getAttribute;};var _proto=Element.prototype;_proto.cloneNode=function cloneNode(deep){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.appendChild=function appendChild(child,index){var _this$ownerDocument;if(child.destroyed){throw new Error(ERROR_MSG_APPEND_DESTROYED_ELEMENT);}runtime.sceneGraphService.attach(child,this,index);if((_this$ownerDocument=this.ownerDocument)===null||_this$ownerDocument===void 0?void 0:_this$ownerDocument.defaultView){this.ownerDocument.defaultView.mountChildren(child);}insertedEvent.relatedNode=this;child.dispatchEvent(insertedEvent);return child;};_proto.insertBefore=function insertBefore(newChild,refChild){if(!refChild){this.appendChild(newChild);}else {var index=this.childNodes.indexOf(refChild);this.appendChild(newChild,index-1);}return newChild;};_proto.replaceChild=function replaceChild(newChild,oldChild){var index=this.childNodes.indexOf(oldChild);this.removeChild(oldChild);this.appendChild(newChild,index);return oldChild;};_proto.removeChild=function removeChild(child){var _child$ownerDocument;// should emit on itself before detach
- removedEvent.relatedNode=this;child.dispatchEvent(removedEvent);if((_child$ownerDocument=child.ownerDocument)===null||_child$ownerDocument===void 0?void 0:_child$ownerDocument.defaultView){child.ownerDocument.defaultView.unmountChildren(child);}// remove from scene graph
- runtime.sceneGraphService.detach(child);return child;}/**
- * Remove all children which can be appended to its original parent later again.
- */;_proto.removeChildren=function removeChildren(){for(var i=this.childNodes.length-1;i>=0;i--){var child=this.childNodes[i];this.removeChild(child);}}/**
- * Recursively destroy all children which can not be appended to its original parent later again.
- */;_proto.destroyChildren=function destroyChildren(){for(var i=this.childNodes.length-1;i>=0;i--){var child=this.childNodes[i];if(child.childNodes.length){child.destroyChildren();}child.destroy();}}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
- */;_proto.matches=function matches(selector){return runtime.sceneGraphService.matches(selector,this);};_proto.getElementById=function getElementById(id){return runtime.sceneGraphService.querySelector("#"+id,this);};_proto.getElementsByName=function getElementsByName(name){return runtime.sceneGraphService.querySelectorAll("[name=\""+name+"\"]",this);};_proto.getElementsByClassName=function getElementsByClassName(className){return runtime.sceneGraphService.querySelectorAll("."+className,this);};_proto.getElementsByTagName=function getElementsByTagName(tagName){return runtime.sceneGraphService.querySelectorAll(tagName,this);};_proto.querySelector=function querySelector(selectors){return runtime.sceneGraphService.querySelector(selectors,this);};_proto.querySelectorAll=function querySelectorAll(selectors){return runtime.sceneGraphService.querySelectorAll(selectors,this);}/**
- * should traverses the element and its parents (heading toward the document root)
- * until it finds a node that matches the specified CSS selector.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill
- */;_proto.closest=function closest(selectors){var el=this;do{if(runtime.sceneGraphService.matches(selectors,el))return el;el=el.parentElement;}while(el!==null);return null;}/**
- * search in scene group, but should not include itself
- */;_proto.find=function find(filter){var _this2=this;var target=null;this.forEach(function(object){if(object!==_this2&&filter(object)){target=object;return true;}return false;});return target;};_proto.findAll=function findAll(filter){var _this3=this;var objects=[];this.forEach(function(object){if(object!==_this3&&filter(object)){objects.push(object);}});return objects;}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/after
- */;_proto.after=function after(){var _this4=this;if(this.parentNode){var index=this.parentNode.childNodes.indexOf(this);for(var _len2=arguments.length,nodes=new Array(_len2),_key2=0;_key2<_len2;_key2++){nodes[_key2]=arguments[_key2];}nodes.forEach(function(node,i){var _this4$parentNode;return (_this4$parentNode=_this4.parentNode)===null||_this4$parentNode===void 0?void 0:_this4$parentNode.appendChild(node,index+i+1);});}}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/before
- */;_proto.before=function before(){if(this.parentNode){var index=this.parentNode.childNodes.indexOf(this);for(var _len3=arguments.length,nodes=new Array(_len3),_key3=0;_key3<_len3;_key3++){nodes[_key3]=arguments[_key3];}var first=nodes[0],rest=nodes.slice(1);this.parentNode.appendChild(first,index);first.after.apply(first,rest);}}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceWith
- */;_proto.replaceWith=function replaceWith(){this.after.apply(this,arguments);this.remove();}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/append
- */;_proto.append=function append(){var _this5=this;for(var _len4=arguments.length,nodes=new Array(_len4),_key4=0;_key4<_len4;_key4++){nodes[_key4]=arguments[_key4];}nodes.forEach(function(node){return _this5.appendChild(node);});}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/prepend
- */;_proto.prepend=function prepend(){var _this6=this;for(var _len5=arguments.length,nodes=new Array(_len5),_key5=0;_key5<_len5;_key5++){nodes[_key5]=arguments[_key5];}nodes.forEach(function(node,i){return _this6.appendChild(node,i);});}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceChildren
- */;_proto.replaceChildren=function replaceChildren(){while(this.childNodes.length&&this.firstChild){this.removeChild(this.firstChild);}this.append.apply(this,arguments);}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/remove
- */;_proto.remove=function remove(){if(this.parentNode){return this.parentNode.removeChild(this);}return this;};_proto.destroy=function destroy(){// destroy itself before remove
- this.dispatchEvent(destroyEvent);// remove from scenegraph first
- this.remove();// remove event listeners
- this.emitter.removeAllListeners();this.destroyed=true;};_proto.getGeometryBounds=function getGeometryBounds(){return runtime.sceneGraphService.getGeometryBounds(this);};_proto.getRenderBounds=function getRenderBounds(){return runtime.sceneGraphService.getBounds(this,true);}/**
- * get bounds in world space, account for children
- */;_proto.getBounds=function getBounds(){return runtime.sceneGraphService.getBounds(this);}/**
- * get bounds in local space, account for children
- */;_proto.getLocalBounds=function getLocalBounds(){return runtime.sceneGraphService.getLocalBounds(this);}/**
- * account for context's bounds in client space,
- * but not accounting for children
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
- */;_proto.getBoundingClientRect=function getBoundingClientRect(){return runtime.sceneGraphService.getBoundingClientRect(this);}/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getClientRects
- */;_proto.getClientRects=function getClientRects(){return [this.getBoundingClientRect()];};/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap
- * eg. circle.computedStyleMap().get('fill');
- */_proto.computedStyleMap=function computedStyleMap(){return new Map(Object.entries(this.computedStyle));};/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
- */_proto.getAttributeNames=function getAttributeNames(){return Object.keys(this.attributes);}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
- */;_proto.getAttribute=function getAttribute(name){// @see https://github.com/antvis/G/issues/1267
- if(isSymbol(name)){return runtime.enableCSSParsing?null:undefined;}var value=this.attributes[name];if(value===undefined){var attributeName=formatAttributeName(name);value=this.attributes[attributeName];// if the given attribute does not exist, the value returned will either be null or ""
- return runtime.enableCSSParsing?isNil(value)?null:value:value;}else {return value;}}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
- */;_proto.hasAttribute=function hasAttribute(qualifiedName){return this.getAttributeNames().includes(qualifiedName);}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
- */;_proto.hasAttributes=function hasAttributes(){return !!this.getAttributeNames().length;}/**
- * should use removeAttribute() instead of setting the attribute value to null either directly or using setAttribute(). Many attributes will not behave as expected if you set them to null.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
- */;_proto.removeAttribute=function removeAttribute(attributeName){this.setAttribute(attributeName,null);delete this.attributes[attributeName];}/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
- */;_proto.setAttribute=function setAttribute(attributeName,value,force){this.attributes[attributeName]=value;};_proto.getAttributeNS=function getAttributeNS(namespace,localName){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.getAttributeNode=function getAttributeNode(qualifiedName){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.getAttributeNodeNS=function getAttributeNodeNS(namespace,localName){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.hasAttributeNS=function hasAttributeNS(namespace,localName){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.removeAttributeNS=function removeAttributeNS(namespace,localName){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.removeAttributeNode=function removeAttributeNode(attr){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.setAttributeNS=function setAttributeNS(namespace,qualifiedName,value){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.setAttributeNode=function setAttributeNode(attr){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.setAttributeNodeNS=function setAttributeNodeNS(attr){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.toggleAttribute=function toggleAttribute(qualifiedName,force){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_createClass(Element,[{key:"className",get:/**
- * used in `getElementsByClassName`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
- */function get(){// @ts-ignore
- return this.getAttribute('class')||'';},set:function set(className){this.setAttribute('class',className);}},{key:"classList",get:/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
- */function get(){return this.className.split(' ').filter(function(c){return c!=='';});}},{key:"tagName",get:function get(){return this.nodeName;}},{key:"children",get:function get(){return this.childNodes;}},{key:"childElementCount",get:function get(){return this.childNodes.length;}},{key:"firstElementChild",get:function get(){return this.firstChild;}},{key:"lastElementChild",get:function get(){return this.lastChild;}},{key:"parentElement",get:function get(){return this.parentNode;}},{key:"nextSibling",get:function get(){if(this.parentNode){var index=this.parentNode.childNodes.indexOf(this);return this.parentNode.childNodes[index+1]||null;}return null;}},{key:"previousSibling",get:function get(){if(this.parentNode){var index=this.parentNode.childNodes.indexOf(this);return this.parentNode.childNodes[index-1]||null;}return null;}}]);return Element;}(Node);var FederatedMouseEvent=/*#__PURE__*/function(_FederatedEvent){_inheritsLoose(FederatedMouseEvent,_FederatedEvent);function FederatedMouseEvent(){var _this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_FederatedEvent.call.apply(_FederatedEvent,[this].concat(args))||this;/** Whether the "alt" key was pressed when this mouse event occurred. */_this.altKey=void 0;/** The specific button that was pressed in this mouse event. */_this.button=void 0;/** The button depressed when this event occurred. */_this.buttons=void 0;/** Whether the "control" key was pressed when this mouse event occurred. */_this.ctrlKey=void 0;/** Whether the "meta" key was pressed when this mouse event occurred. */_this.metaKey=void 0;/** This is currently not implemented in the Federated Events API. */_this.relatedTarget=void 0;/** Whether the "shift" key was pressed when this mouse event occurred. */_this.shiftKey=void 0;/**
- * The coordinates of the mouse event relative to the canvas.
- */_this.client=new Point();/**
- * The movement in this pointer relative to the last `mousemove` event.
- */_this.movement=new Point();/**
- * The offset of the pointer coordinates w.r.t. target DisplayObject in world space. This is
- * not supported at the moment.
- */_this.offset=new Point();/**
- * The pointer coordinates in world space.
- */_this.global=new Point();/**
- * The pointer coordinates in sceen space.
- */_this.screen=new Point();return _this;}var _proto=FederatedMouseEvent.prototype;_proto.getModifierState=function getModifierState(key){return 'getModifierState'in this.nativeEvent&&this.nativeEvent.getModifierState(key);};_proto.initMouseEvent=function initMouseEvent(){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_createClass(FederatedMouseEvent,[{key:"clientX",get:function get(){return this.client.x;}},{key:"clientY",get:function get(){return this.client.y;}},{key:"movementX",get:function get(){return this.movement.x;}},{key:"movementY",get:function get(){return this.movement.y;}},{key:"offsetX",get:function get(){return this.offset.x;}},{key:"offsetY",get:function get(){return this.offset.y;}},{key:"globalX",get:function get(){return this.global.x;}},{key:"globalY",get:function get(){return this.global.y;}},{key:"screenX",get:function get(){return this.screen.x;}},{key:"screenY",get:function get(){return this.screen.y;}}]);return FederatedMouseEvent;}(FederatedEvent);var FederatedPointerEvent=/*#__PURE__*/function(_FederatedMouseEvent){_inheritsLoose(FederatedPointerEvent,_FederatedMouseEvent);function FederatedPointerEvent(){var _this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_FederatedMouseEvent.call.apply(_FederatedMouseEvent,[this].concat(args))||this;/**
- * The unique identifier of the pointer.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
- */_this.pointerId=void 0;/**
- * The width of the pointer's contact along the x-axis, measured in CSS pixels.
- * radiusX of TouchEvents will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
- */_this.width=0;/**
- * The height of the pointer's contact along the y-axis, measured in CSS pixels.
- * radiusY of TouchEvents will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
- */_this.height=0;/**
- * Indicates whether or not the pointer device that created the event is the primary pointer.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
- */_this.isPrimary=false;/**
- * The type of pointer that triggered the event.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
- */_this.pointerType=void 0;/**
- * Pressure applied by the pointing device during the event.
- *s
- * A Touch's force property will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
- */_this.pressure=void 0;/**
- * Barrel pressure on a stylus pointer.
- *
- * @see https://w3c.github.io/pointerevents/#pointerevent-interface
- */_this.tangentialPressure=void 0;/**
- * The angle, in degrees, between the pointer device and the screen.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
- */_this.tiltX=void 0;/**
- * The angle, in degrees, between the pointer device and the screen.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
- */_this.tiltY=void 0;/**
- * Twist of a stylus pointer.
- *
- * @see https://w3c.github.io/pointerevents/#pointerevent-interface
- */_this.twist=void 0;return _this;}var _proto=FederatedPointerEvent.prototype;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents
- */_proto.getCoalescedEvents=function getCoalescedEvents(){if(this.type==='pointermove'||this.type==='mousemove'||this.type==='touchmove'){return [this];}return [];}/**
- * @see https://chromestatus.com/feature/5765569655603200
- */;_proto.getPredictedEvents=function getPredictedEvents(){throw new Error('getPredictedEvents is not supported!');}/**
- * @see https://github.com/antvis/G/issues/1115
- * We currently reuses event objects in the event system,
- * avoiding the creation of a large number of event objects.
- * Reused objects are only used to carry different data,
- * such as coordinate information, native event objects,
- * and therefore the lifecycle is limited to the event handler,
- * which can lead to unintended consequences if an attempt is made to cache the entire event object.
- *
- * Therefore, while keeping the above performance considerations in mind, it is possible to provide a clone method that creates a new object when the user really wants to cache it, e.g.
- */;_proto.clone=function clone(){return this.manager.clonePointerEvent(this);};return FederatedPointerEvent;}(FederatedMouseEvent);var FederatedWheelEvent=/*#__PURE__*/function(_FederatedMouseEvent){_inheritsLoose(FederatedWheelEvent,_FederatedMouseEvent);function FederatedWheelEvent(){var _this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}_this=_FederatedMouseEvent.call.apply(_FederatedMouseEvent,[this].concat(args))||this;/**
- * The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
- * `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
- */_this.deltaMode=void 0;/** Horizontal scroll amount */_this.deltaX=void 0;/** Vertical scroll amount */_this.deltaY=void 0;/** z-axis scroll amount. */_this.deltaZ=void 0;/** Units specified in lines. */_this.DOM_DELTA_LINE=0;/** Units specified in pages. */_this.DOM_DELTA_PAGE=1;/** Units specified in pixels. */_this.DOM_DELTA_PIXEL=2;return _this;}var _proto=FederatedWheelEvent.prototype;_proto.clone=function clone(){return this.manager.cloneWheelEvent(this);};return FederatedWheelEvent;}(FederatedMouseEvent);function isDisplayObject(value){return !!(value===null||value===void 0?void 0:value.nodeName);}var mutationEvent=new MutationEvent(exports.ElementEvent.ATTR_MODIFIED,null,null,null,null,MutationEvent.MODIFICATION,null,null);var DEFAULT_STYLE_PROPS={anchor:'',opacity:'',fillOpacity:'',strokeOpacity:'',fill:'',stroke:'',transform:'',transformOrigin:'',visibility:'',pointerEvents:'',lineWidth:'',lineCap:'',lineJoin:'',increasedLineWidthForHitTesting:'',fontSize:'',fontFamily:'',fontStyle:'',fontWeight:'',fontVariant:'',textAlign:'',textBaseline:'',textTransform:'',zIndex:'',filter:'',shadowType:''};var DEFAULT_PARSED_STYLE_PROPS={anchor:[0,0],fill:noneColor,stroke:noneColor,transform:[],zIndex:0,filter:[],shadowType:'outer',miterLimit:10};var DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED=_extends({},DEFAULT_PARSED_STYLE_PROPS,{opacity:1,fillOpacity:1,strokeOpacity:1,visibility:'visible',pointerEvents:'auto',lineWidth:1,lineCap:'butt',lineJoin:'miter',increasedLineWidthForHitTesting:0,fillRule:'nonzero'// TODO: transformOrigin
- });var INHERITABLE_BASE_STYLE_PROPS=['opacity','fillOpacity','strokeOpacity','transformOrigin','visibility','pointerEvents','lineWidth','lineCap','lineJoin','increasedLineWidthForHitTesting'];var INHERITABLE_STYLE_PROPS=[].concat(INHERITABLE_BASE_STYLE_PROPS,['fontSize','fontFamily','fontStyle','fontWeight','fontVariant','textAlign','textBaseline','textTransform']);var DATASET_PREFIX='data-';/**
- * prototype chains: DisplayObject -> Element -> Node -> EventTarget
- *
- * mixins: Animatable, Transformable, Visible
- * @see https://github.com/tannerntannern/ts-mixer/blob/master/README.md#mixing-generic-classes
- *
- * Provide abilities in scene graph, such as:
- * * transform `translate/rotate/scale`
- * * add/remove child
- * * visibility and z-index
- *
- * Those abilities are implemented with those components: `Transform/Sortable/Visible`.
- *
- * Emit following events:
- * * init
- * * destroy
- * * attributeChanged
- */var DisplayObject=/*#__PURE__*/function(_Element){_inheritsLoose(DisplayObject,_Element);function DisplayObject(config){var _this$config$capture;var _this;_this=_Element.call(this)||this;// assign name, id to config
- // eg. group.get('name')
- /**
- * contains style props in constructor's params, eg. fill, stroke...
- */_this.config=void 0;_this.isCustomElement=false;_this.isMutationObserved=false;/**
- * push to active animations after calling `animate()`
- */_this.activeAnimations=[];/**
- * Use data-* attribute.
- * @see https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
- * @example
- * group.dataset.prop1 = 1;
- * group.getAttribute('data-prop1'); // 1
- */_this.dataset=void 0;/**
- * Use `this.style.clipPath` instead.
- * @deprecated
- */_this.getClip=function(){return this.style.clipPath||null;};_this.config=config;// compatible with G 3.0
- _this.config.interactive=(_this$config$capture=_this.config.capture)!==null&&_this$config$capture!==void 0?_this$config$capture:_this.config.interactive;// init scene graph node
- _this.id=_this.config.id||'';_this.name=_this.config.name||'';if(_this.config.className||_this.config.class){_this.className=_this.config.className||_this.config.class;}_this.nodeName=_this.config.type||exports.Shape.GROUP;// compatible with G 3.0
- _this.config.style=_this.config.style||_this.config.attrs||{};Object.assign(_this.config.style,_this.config.attrs);// this.config.style = {
- // // ...DEFAULT_STYLE_PROPS,
- // ...this.config.style,
- // ...this.config.attrs,
- // };
- if(_this.config.visible!=null){_this.config.style.visibility=_this.config.visible===false?'hidden':'visible';}if(_this.config.interactive!=null){_this.config.style.pointerEvents=_this.config.interactive===false?'none':'auto';}// merge parsed value
- Object.assign(_this.parsedStyle,runtime.enableCSSParsing?DEFAULT_PARSED_STYLE_PROPS:DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED,_this.config.initialParsedStyle);if(runtime.enableCSSParsing){Object.assign(_this.attributes,DEFAULT_STYLE_PROPS);}// start to process attributes
- _this.initAttributes(_this.config.style);var Proxy=runtime.globalThis.Proxy?runtime.globalThis.Proxy:function(){};if(runtime.enableDataset){_this.dataset=new Proxy({},{get:function get(target,name){var formattedName=""+DATASET_PREFIX+kebabize(name);if(target[formattedName]!==undefined){return target[formattedName];}return _this.getAttribute(formattedName);},set:function set(_,prop,value){_this.setAttribute(""+DATASET_PREFIX+kebabize(prop),value);return true;}});}if(runtime.enableStyleSyntax){_this.style=new Proxy(// @ts-ignore
- {// ...this.attributes,
- setProperty:function setProperty(propertyName,value){_this.setAttribute(propertyName,value);},getPropertyValue:function getPropertyValue(propertyName){return _this.getAttribute(propertyName);},removeProperty:function removeProperty(propertyName){_this.removeAttribute(propertyName);},item:function item(){return '';}},{get:function get(target,name){if(target[name]!==undefined){// if (name in target) {
- return target[name];}return _this.getAttribute(name);},set:function set(_,prop,value){_this.setAttribute(prop,value);return true;}});}return _this;}var _proto=DisplayObject.prototype;_proto.destroy=function destroy(){_Element.prototype.destroy.call(this);// stop all active animations
- this.getAnimations().forEach(function(animation){animation.cancel();});// FIXME
- // this.renderable = null;
- // this.cullable = null;
- // this.transformable = null;
- // this.rBushNode = null;
- // this.geometry = null;
- // this.sortable = null;
- };_proto.cloneNode=function cloneNode(deep,customCloneFunc){var clonedStyle=_extends({},this.attributes);for(var attributeName in clonedStyle){var attribute=clonedStyle[attributeName];// @see https://github.com/antvis/G/issues/1095
- if(isDisplayObject(attribute)&&// share the same clipPath if possible
- attributeName!=='clipPath'&&attributeName!=='offsetPath'&&attributeName!=='textPath'){clonedStyle[attributeName]=attribute.cloneNode(deep);}// TODO: clone other type
- if(customCloneFunc){clonedStyle[attributeName]=customCloneFunc(attributeName,attribute);}}var cloned=new this.constructor({// copy id & name
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode#notes
- id:this.id,name:this.name,className:this.name,interactive:this.interactive,style:clonedStyle});// apply transform
- cloned.setLocalTransform(this.getLocalTransform());if(deep){this.children.forEach(function(child){// skip marker
- if(!child.style.isMarker){var clonedChild=child.cloneNode(deep);cloned.appendChild(clonedChild);}});}return cloned;};_proto.initAttributes=function initAttributes(attributes){if(attributes===void 0){attributes={};}var renderable=this.renderable;var options={forceUpdateGeometry:true// usedAttributes:
- // // only Group / Text should account for text relative props
- // this.tagName === Shape.GROUP || this.tagName === Shape.TEXT
- // ? INHERITABLE_STYLE_PROPS
- // : INHERITABLE_BASE_STYLE_PROPS,
- };if(runtime.enableCSSParsing){// @ts-ignore
- options.usedAttributes=INHERITABLE_STYLE_PROPS;}// account for FCP, process properties as less as possible
- var formattedAttributes={};for(var name in attributes){var attributeName=formatAttributeName(name);formattedAttributes[attributeName]=attributes[name];}runtime.styleValueRegistry.processProperties(this,formattedAttributes,options);// redraw at next frame
- renderable.dirty=true;};_proto.setAttribute=function setAttribute(name,value,force){if(force===void 0){force=false;}var attributeName=formatAttributeName(name);// ignore undefined value
- if(isUndefined(value)){return;}if(force||value!==this.attributes[attributeName]){this.internalSetAttribute(attributeName,value);_Element.prototype.setAttribute.call(this,attributeName,value);}}/**
- * called when attributes get changed or initialized
- */;_proto.internalSetAttribute=function internalSetAttribute(name,value,parseOptions){var _runtime$styleValueRe;if(parseOptions===void 0){parseOptions={};}var renderable=this.renderable;var oldValue=this.attributes[name];var oldParsedValue=this.parsedStyle[name];runtime.styleValueRegistry.processProperties(this,(_runtime$styleValueRe={},_runtime$styleValueRe[name]=value,_runtime$styleValueRe),parseOptions);// redraw at next frame
- renderable.dirty=true;var newParsedValue=this.parsedStyle[name];if(this.isConnected){mutationEvent.relatedNode=this;mutationEvent.prevValue=oldValue;mutationEvent.newValue=value;mutationEvent.attrName=name;mutationEvent.prevParsedValue=oldParsedValue;mutationEvent.newParsedValue=newParsedValue;if(this.isMutationObserved){this.dispatchEvent(mutationEvent);}else {mutationEvent.target=this;this.ownerDocument.defaultView.dispatchEvent(mutationEvent,true);}}if((this.isCustomElement&&this.isConnected||!this.isCustomElement)&&this.attributeChangedCallback){this.attributeChangedCallback(name,oldValue,value,oldParsedValue,newParsedValue);}}// #region transformable
- /**
- * returns different values than getBoundingClientRect(), as the latter returns value relative to the viewport
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
- *
- * FIXME: It is worth noting that getBBox responds to original untransformed values of a drawn object.
- * @see https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox
- */;_proto.getBBox=function getBBox(){var aabb=this.getBounds();var _aabb$getMin=aabb.getMin(),left=_aabb$getMin[0],top=_aabb$getMin[1];var _aabb$getMax=aabb.getMax(),right=_aabb$getMax[0],bottom=_aabb$getMax[1];return new Rectangle(left,top,right-left,bottom-top);};_proto.setOrigin=function setOrigin(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}runtime.sceneGraphService.setOrigin(this,createVec3(position,y,z));return this;};_proto.getOrigin=function getOrigin(){return runtime.sceneGraphService.getOrigin(this);}/**
- * set position in world space
- */;_proto.setPosition=function setPosition(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}runtime.sceneGraphService.setPosition(this,createVec3(position,y,z));return this;}/**
- * set position in local space
- */;_proto.setLocalPosition=function setLocalPosition(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}runtime.sceneGraphService.setLocalPosition(this,createVec3(position,y,z));return this;}/**
- * translate in world space
- */;_proto.translate=function translate(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}runtime.sceneGraphService.translate(this,createVec3(position,y,z));return this;}/**
- * translate in local space
- */;_proto.translateLocal=function translateLocal(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}runtime.sceneGraphService.translateLocal(this,createVec3(position,y,z));return this;};_proto.getPosition=function getPosition(){return runtime.sceneGraphService.getPosition(this);};_proto.getLocalPosition=function getLocalPosition(){return runtime.sceneGraphService.getLocalPosition(this);}/**
- * compatible with G 3.0
- *
- * scaling in local space
- * scale(10) = scale(10, 10, 10)
- *
- * we can't set scale in world space
- */;_proto.scale=function scale(scaling,y,z){return this.scaleLocal(scaling,y,z);};_proto.scaleLocal=function scaleLocal(scaling,y,z){if(typeof scaling==='number'){y=y||scaling;z=z||scaling;scaling=createVec3(scaling,y,z);}runtime.sceneGraphService.scaleLocal(this,scaling);return this;}/**
- * set scaling in local space
- */;_proto.setLocalScale=function setLocalScale(scaling,y,z){if(typeof scaling==='number'){y=y||scaling;z=z||scaling;scaling=createVec3(scaling,y,z);}runtime.sceneGraphService.setLocalScale(this,scaling);return this;}/**
- * get scaling in local space
- */;_proto.getLocalScale=function getLocalScale(){return runtime.sceneGraphService.getLocalScale(this);}/**
- * get scaling in world space
- */;_proto.getScale=function getScale(){return runtime.sceneGraphService.getScale(this);}/**
- * only return degrees of Z axis in world space
- */;_proto.getEulerAngles=function getEulerAngles(){var _getEuler=getEuler(create$2(),runtime.sceneGraphService.getWorldTransform(this)),ez=_getEuler[2];return rad2deg(ez);}/**
- * only return degrees of Z axis in local space
- */;_proto.getLocalEulerAngles=function getLocalEulerAngles(){var _getEuler2=getEuler(create$2(),runtime.sceneGraphService.getLocalRotation(this)),ez=_getEuler2[2];return rad2deg(ez);}/**
- * set euler angles(degrees) in world space
- */;_proto.setEulerAngles=function setEulerAngles(z){runtime.sceneGraphService.setEulerAngles(this,0,0,z);return this;}/**
- * set euler angles(degrees) in local space
- */;_proto.setLocalEulerAngles=function setLocalEulerAngles(z){runtime.sceneGraphService.setLocalEulerAngles(this,0,0,z);return this;};_proto.rotateLocal=function rotateLocal(x,y,z){if(isNil(y)&&isNil(z)){runtime.sceneGraphService.rotateLocal(this,0,0,x);}else {runtime.sceneGraphService.rotateLocal(this,x,y,z);}return this;};_proto.rotate=function rotate(x,y,z){if(isNil(y)&&isNil(z)){runtime.sceneGraphService.rotate(this,0,0,x);}else {runtime.sceneGraphService.rotate(this,x,y,z);}return this;};_proto.setRotation=function setRotation(rotation,y,z,w){runtime.sceneGraphService.setRotation(this,rotation,y,z,w);return this;};_proto.setLocalRotation=function setLocalRotation(rotation,y,z,w){runtime.sceneGraphService.setLocalRotation(this,rotation,y,z,w);return this;};_proto.setLocalSkew=function setLocalSkew(skew,y){runtime.sceneGraphService.setLocalSkew(this,skew,y);return this;};_proto.getRotation=function getRotation(){return runtime.sceneGraphService.getRotation(this);};_proto.getLocalRotation=function getLocalRotation(){return runtime.sceneGraphService.getLocalRotation(this);};_proto.getLocalSkew=function getLocalSkew(){return runtime.sceneGraphService.getLocalSkew(this);};_proto.getLocalTransform=function getLocalTransform(){return runtime.sceneGraphService.getLocalTransform(this);};_proto.getWorldTransform=function getWorldTransform(){return runtime.sceneGraphService.getWorldTransform(this);};_proto.setLocalTransform=function setLocalTransform(transform){runtime.sceneGraphService.setLocalTransform(this,transform);return this;};_proto.resetLocalTransform=function resetLocalTransform(){runtime.sceneGraphService.resetLocalTransform(this);}// #endregion transformable
- // #region animatable
- /**
- * returns an array of all Animation objects affecting this element
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
- */;_proto.getAnimations=function getAnimations(){return this.activeAnimations;}/**
- * create an animation with WAAPI
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/animate
- */;_proto.animate=function animate(keyframes,options){var _this$ownerDocument;var timeline=(_this$ownerDocument=this.ownerDocument)===null||_this$ownerDocument===void 0?void 0:_this$ownerDocument.timeline;if(timeline){return timeline.play(this,keyframes,options);}return null;}// #endregion animatable
- // #region visible
- /**
- * shortcut for Used value of `visibility`
- */;_proto.isVisible=function isVisible(){var _this$parsedStyle;return ((_this$parsedStyle=this.parsedStyle)===null||_this$parsedStyle===void 0?void 0:_this$parsedStyle.visibility)==='visible';};_proto.isInteractive=function isInteractive(){var _this$parsedStyle2;return ((_this$parsedStyle2=this.parsedStyle)===null||_this$parsedStyle2===void 0?void 0:_this$parsedStyle2.pointerEvents)!=='none';};_proto.isCulled=function isCulled(){return !!(this.cullable&&this.cullable.enable&&!this.cullable.visible);}/**
- * bring to front in current group
- */;_proto.toFront=function toFront(){if(this.parentNode){this.style.zIndex=Math.max.apply(Math,this.parentNode.children.map(function(child){return Number(child.style.zIndex);}))+1;}return this;}/**
- * send to back in current group
- */;_proto.toBack=function toBack(){if(this.parentNode){this.style.zIndex=Math.min.apply(Math,this.parentNode.children.map(function(child){return Number(child.style.zIndex);}))-1;}return this;}// #endregion visible
- // #region deprecated
- /**
- * compatible with G 3.0
- * @alias object.config
- * @deprecated
- */;_proto.getConfig=function getConfig(){return this.config;};_proto.attr=function attr(){var _this2=this;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}var name=args[0],value=args[1];if(!name){return this.attributes;}if(isObject(name)){Object.keys(name).forEach(function(key){_this2.setAttribute(key,name[key]);});return this;}if(args.length===2){this.setAttribute(name,value);return this;}return this.attributes[name];}/**
- * return 3x3 matrix in world space
- * @deprecated
- */;_proto.getMatrix=function getMatrix(transformMat4){var transform=transformMat4||this.getWorldTransform();var _mat4$getTranslation=getTranslation(create$2(),transform),tx=_mat4$getTranslation[0],ty=_mat4$getTranslation[1];var _mat4$getScaling=getScaling(create$2(),transform),sx=_mat4$getScaling[0],sy=_mat4$getScaling[1];var rotation=getRotation(create$4(),transform);var _getEuler3=getEuler(create$2(),rotation),eux=_getEuler3[0],euz=_getEuler3[2];// gimbal lock at 90 degrees
- return fromRotationTranslationScale$1(eux||euz,tx,ty,sx,sy);}/**
- * return 3x3 matrix in local space
- * @deprecated
- */;_proto.getLocalMatrix=function getLocalMatrix(){return this.getMatrix(this.getLocalTransform());}/**
- * set 3x3 matrix in world space
- * @deprecated
- */;_proto.setMatrix=function setMatrix(mat){var _decompose=decompose(mat),tx=_decompose[0],ty=_decompose[1],scalingX=_decompose[2],scalingY=_decompose[3],angle=_decompose[4];this.setEulerAngles(angle).setPosition(tx,ty).setLocalScale(scalingX,scalingY);}/**
- * set 3x3 matrix in local space
- * @deprecated
- */;_proto.setLocalMatrix=function setLocalMatrix(mat){var _decompose2=decompose(mat),tx=_decompose2[0],ty=_decompose2[1],scalingX=_decompose2[2],scalingY=_decompose2[3],angle=_decompose2[4];this.setLocalEulerAngles(angle).setLocalPosition(tx,ty).setLocalScale(scalingX,scalingY);}/**
- * Use `visibility: visible` instead.
- * @deprecated
- */;_proto.show=function show(){if(runtime.enableCSSParsing){this.style.visibility='visible';}else {this.forEach(function(object){object.style.visibility='visible';});}}/**
- * Use `visibility: hidden` instead.
- * @deprecated
- */;_proto.hide=function hide(){if(runtime.enableCSSParsing){this.style.visibility='hidden';}else {this.forEach(function(object){object.style.visibility='hidden';});}}/**
- * Use `childElementCount` instead.
- * @deprecated
- */;_proto.getCount=function getCount(){return this.childElementCount;}/**
- * Use `parentElement` instead.
- * @deprecated
- */;_proto.getParent=function getParent(){return this.parentElement;}/**
- * Use `children` instead.
- * @deprecated
- */;_proto.getChildren=function getChildren(){return this.children;}/**
- * Use `firstElementChild` instead.
- * @deprecated
- */;_proto.getFirst=function getFirst(){return this.firstElementChild;}/**
- * Use `lastElementChild` instead.
- * @deprecated
- */;_proto.getLast=function getLast(){return this.lastElementChild;}/**
- * Use `this.children[index]` instead.
- * @deprecated
- */;_proto.getChildByIndex=function getChildByIndex(index){return this.children[index]||null;}/**
- * Use `appendChild` instead.
- * @deprecated
- */;_proto.add=function add(child,index){return this.appendChild(child,index);}/**
- * Use `this.style.clipPath` instead.
- * @deprecated
- */;_proto.setClip=function setClip(clipPath){this.style.clipPath=clipPath;};/**
- * @deprecated
- */_proto.set=function set(name,value){// @ts-ignore
- this.config[name]=value;}/**
- * @deprecated
- */;_proto.get=function get(name){return this.config[name];}/**
- * Use `setPosition` instead.
- * @deprecated
- */;_proto.moveTo=function moveTo(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}this.setPosition(position,y,z);return this;}/**
- * Use `setPosition` instead.
- * @deprecated
- */;_proto.move=function move(position,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}this.setPosition(position,y,z);return this;}/**
- * Use `this.style.zIndex` instead.
- * @deprecated
- */;_proto.setZIndex=function setZIndex(zIndex){this.style.zIndex=zIndex;return this;};_createClass(DisplayObject,[{key:"interactive",get:function get(){return this.isInteractive();},set:function set(b){this.style.pointerEvents=b?'auto':'none';}}]);return DisplayObject;}(Element);var _excluded=["style"];var Circle=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Circle,_DisplayObject);function Circle(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded);return _DisplayObject.call(this,_extends({type:exports.Shape.CIRCLE,style:runtime.enableCSSParsing?_extends({cx:'',cy:'',r:''},style):_extends({},style),initialParsedStyle:{anchor:[0.5,0.5],transformOrigin:runtime.enableCSSParsing?null:[PECENTAGE_50,PECENTAGE_50]}},rest))||this;}return Circle;}(DisplayObject);var _excluded$1=["style"];/**
- * shadow root
- * @see https://yuque.antfin-inc.com/antv/czqvg5/pgqipg
- */var CustomElement=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(CustomElement,_DisplayObject);// private shadowNodes: DisplayObject[] = [];
- function CustomElement(_temp){var _this;var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$1);_this=_DisplayObject.call(this,_extends({style:runtime.enableCSSParsing?_extends({x:'',y:''},style):_extends({},style)},rest))||this;// static get observedAttributes(): string[] {
- // return [];
- // }
- _this.isCustomElement=true;return _this;}return CustomElement;}(DisplayObject);var _excluded$2=["style"];var Ellipse=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Ellipse,_DisplayObject);function Ellipse(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$2);return _DisplayObject.call(this,_extends({type:exports.Shape.ELLIPSE,style:runtime.enableCSSParsing?_extends({cx:'',cy:'',rx:'',ry:''},style):_extends({},style),initialParsedStyle:{anchor:[0.5,0.5],transformOrigin:runtime.enableCSSParsing?null:[PECENTAGE_50,PECENTAGE_50]}},rest))||this;}return Ellipse;}(DisplayObject);var _excluded$3=["style"];/**
- * its attributes are inherited by its children.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g
- *
- * @example
- * <g fill="white" stroke="green" stroke-width="5">
- <circle cx="40" cy="40" r="25" />
- <circle cx="60" cy="60" r="25" />
- </g>
- */var Group=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Group,_DisplayObject);function Group(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$3);return _DisplayObject.call(this,_extends({type:exports.Shape.GROUP,style:runtime.enableCSSParsing?_extends({x:'',y:'',width:'',height:''},style):_extends({},style)},rest))||this;}return Group;}(DisplayObject);var _excluded$4=["style"];/**
- * HTML container
- * @see https://github.com/pmndrs/drei#html
- */var HTML=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(HTML,_DisplayObject);function HTML(_temp){var _this;var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$4);_this=_DisplayObject.call(this,_extends({type:exports.Shape.HTML,style:runtime.enableCSSParsing?_extends({x:'',y:'',width:'auto',height:'auto',innerHTML:''},style):_extends({},style)},rest))||this;_this.cullable.enable=false;return _this;}/**
- * return wrapper HTMLElement
- * * <div> in g-webgl/canvas
- * * <foreignObject> in g-svg
- */var _proto=HTML.prototype;_proto.getDomElement=function getDomElement(){return this.parsedStyle.$el;}/**
- * override with $el.getBoundingClientRect
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
- */;_proto.getBoundingClientRect=function getBoundingClientRect(){return this.parsedStyle.$el.getBoundingClientRect();};_proto.getClientRects=function getClientRects(){return [this.getBoundingClientRect()];};_proto.getBounds=function getBounds(){var _this$ownerDocument,_this$ownerDocument$d;var clientRect=this.getBoundingClientRect();// calc context's offset
- // @ts-ignore
- var canvasRect=(_this$ownerDocument=this.ownerDocument)===null||_this$ownerDocument===void 0?void 0:(_this$ownerDocument$d=_this$ownerDocument.defaultView)===null||_this$ownerDocument$d===void 0?void 0:_this$ownerDocument$d.getContextService().getBoundingClientRect();if(canvasRect){var minX=clientRect.left-canvasRect.left;var minY=clientRect.top-canvasRect.top;var aabb=new AABB();// aabb.setMinMax(
- // vec3.fromValues(minX, minY, 0),
- // vec3.fromValues(minX + clientRect.width, minY + clientRect.height, 0),
- // );
- aabb.setMinMax([minX,minY,0],[minX+clientRect.width,minY+clientRect.height,0]);return aabb;}return null;};_proto.getLocalBounds=function getLocalBounds(){if(this.parentNode){var parentInvert=invert(create$1(),this.parentNode.getWorldTransform());var bounds=this.getBounds();if(!AABB.isEmpty(bounds)){var localBounds=new AABB();localBounds.setFromTransformedAABB(bounds,parentInvert);return localBounds;}}return this.getBounds();};return HTML;}(DisplayObject);var _excluded$5=["style"];var Image=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Image,_DisplayObject);function Image(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$5);return _DisplayObject.call(this,_extends({type:exports.Shape.IMAGE,style:runtime.enableCSSParsing?_extends({x:'',y:'',img:'',width:'',height:''},style):_extends({},style)},rest))||this;}return Image;}(DisplayObject);var _excluded$6=["style"];/**
- * Create a line connecting two points.
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line
- *
- * Also support for using marker.
- */var Line=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Line,_DisplayObject);function Line(_temp){var _this;var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$6);_this=_DisplayObject.call(this,_extends({type:exports.Shape.LINE,style:_extends({x1:0,y1:0,x2:0,y2:0,z1:0,z2:0,isBillboard:false},style)},rest))||this;_this.markerStartAngle=0;_this.markerEndAngle=0;var _this$parsedStyle=_this.parsedStyle,markerStart=_this$parsedStyle.markerStart,markerEnd=_this$parsedStyle.markerEnd;if(markerStart&&isDisplayObject(markerStart)){_this.markerStartAngle=markerStart.getLocalEulerAngles();_this.appendChild(markerStart);}if(markerEnd&&isDisplayObject(markerEnd)){_this.markerEndAngle=markerEnd.getLocalEulerAngles();_this.appendChild(markerEnd);}_this.transformMarker(true);_this.transformMarker(false);return _this;}var _proto=Line.prototype;_proto.attributeChangedCallback=function attributeChangedCallback(attrName,oldValue,newValue,prevParsedValue,newParsedValue){if(attrName==='x1'||attrName==='y1'||attrName==='x2'||attrName==='y2'||attrName==='markerStartOffset'||attrName==='markerEndOffset'){this.transformMarker(true);this.transformMarker(false);}else if(attrName==='markerStart'){if(prevParsedValue&&isDisplayObject(prevParsedValue)){this.markerStartAngle=0;prevParsedValue.remove();}// CSSKeyword 'unset'
- if(newParsedValue&&isDisplayObject(newParsedValue)){this.markerStartAngle=newParsedValue.getLocalEulerAngles();this.appendChild(newParsedValue);this.transformMarker(true);}}else if(attrName==='markerEnd'){if(prevParsedValue&&isDisplayObject(prevParsedValue)){this.markerEndAngle=0;prevParsedValue.remove();}if(newParsedValue&&isDisplayObject(newParsedValue)){this.markerEndAngle=newParsedValue.getLocalEulerAngles();this.appendChild(newParsedValue);this.transformMarker(false);}}};_proto.transformMarker=function transformMarker(isStart){var _this$parsedStyle2=this.parsedStyle,markerStart=_this$parsedStyle2.markerStart,markerEnd=_this$parsedStyle2.markerEnd,markerStartOffset=_this$parsedStyle2.markerStartOffset,markerEndOffset=_this$parsedStyle2.markerEndOffset,x1=_this$parsedStyle2.x1,x2=_this$parsedStyle2.x2,y1=_this$parsedStyle2.y1,y2=_this$parsedStyle2.y2,defX=_this$parsedStyle2.defX,defY=_this$parsedStyle2.defY;var marker=isStart?markerStart:markerEnd;if(!marker||!isDisplayObject(marker)){return;}var rad=0;var x;var y;var ox;var oy;var offset;var originalAngle;if(isStart){ox=x1-defX;oy=y1-defY;x=x2-x1;y=y2-y1;offset=markerStartOffset||0;originalAngle=this.markerStartAngle;}else {ox=x2-defX;oy=y2-defY;x=x1-x2;y=y1-y2;offset=markerEndOffset||0;originalAngle=this.markerEndAngle;}rad=Math.atan2(y,x);// account for markerOffset
- marker.setLocalEulerAngles(rad*180/Math.PI+originalAngle);marker.setLocalPosition(ox+Math.cos(rad)*offset,oy+Math.sin(rad)*offset);};_proto.getPoint=function getPoint(ratio,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}// TODO: account for z1/z2 in 3D line
- var _this$parsedStyle3=this.parsedStyle,x1=_this$parsedStyle3.x1,y1=_this$parsedStyle3.y1,x2=_this$parsedStyle3.x2,y2=_this$parsedStyle3.y2,defX=_this$parsedStyle3.defX,defY=_this$parsedStyle3.defY;var _LineUtil$pointAt=line.pointAt(x1,y1,x2,y2,ratio),x=_LineUtil$pointAt.x,y=_LineUtil$pointAt.y;var transformed=transformMat4(create$2(),fromValues$2(x-defX,y-defY,0),inWorldSpace?this.getWorldTransform():this.getLocalTransform());// apply local transformation
- return new Point(transformed[0],transformed[1]);};_proto.getPointAtLength=function getPointAtLength(distance,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}return this.getPoint(distance/this.getTotalLength(),inWorldSpace);};_proto.getTotalLength=function getTotalLength(){// TODO: account for z1/z2 in 3D line
- var _this$parsedStyle4=this.parsedStyle,x1=_this$parsedStyle4.x1,y1=_this$parsedStyle4.y1,x2=_this$parsedStyle4.x2,y2=_this$parsedStyle4.y2;return line.length(x1,y1,x2,y2);};return Line;}(DisplayObject);var _excluded$7=["style"];var EMPTY_PARSED_PATH={absolutePath:[],hasArc:false,segments:[],polygons:[],polylines:[],curve:null,totalLength:0,rect:new Rectangle(0,0,0,0)};var Path=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Path,_DisplayObject);function Path(_temp){var _this;var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$7);_this=_DisplayObject.call(this,_extends({type:exports.Shape.PATH,style:runtime.enableCSSParsing?_extends({path:'',miterLimit:''},style):_extends({},style),initialParsedStyle:runtime.enableCSSParsing?null:{miterLimit:4,path:_extends({},EMPTY_PARSED_PATH)}},rest))||this;_this.markerStartAngle=0;_this.markerEndAngle=0;/**
- * markers placed at the mid
- */_this.markerMidList=[];var _this$parsedStyle=_this.parsedStyle,markerStart=_this$parsedStyle.markerStart,markerEnd=_this$parsedStyle.markerEnd,markerMid=_this$parsedStyle.markerMid;if(markerStart&&isDisplayObject(markerStart)){_this.markerStartAngle=markerStart.getLocalEulerAngles();_this.appendChild(markerStart);}if(markerMid&&isDisplayObject(markerMid)){_this.placeMarkerMid(markerMid);}if(markerEnd&&isDisplayObject(markerEnd)){_this.markerEndAngle=markerEnd.getLocalEulerAngles();_this.appendChild(markerEnd);}_this.transformMarker(true);_this.transformMarker(false);return _this;}var _proto=Path.prototype;_proto.attributeChangedCallback=function attributeChangedCallback(attrName,oldValue,newValue,prevParsedValue,newParsedValue){if(attrName==='path'){// recalc markers
- this.transformMarker(true);this.transformMarker(false);this.placeMarkerMid(this.parsedStyle.markerMid);}else if(attrName==='markerStartOffset'||attrName==='markerEndOffset'){this.transformMarker(true);this.transformMarker(false);}else if(attrName==='markerStart'){if(prevParsedValue&&isDisplayObject(prevParsedValue)){this.markerStartAngle=0;prevParsedValue.remove();}// CSSKeyword 'unset'
- if(newParsedValue&&isDisplayObject(newParsedValue)){this.markerStartAngle=newParsedValue.getLocalEulerAngles();this.appendChild(newParsedValue);this.transformMarker(true);}}else if(attrName==='markerEnd'){if(prevParsedValue&&isDisplayObject(prevParsedValue)){this.markerEndAngle=0;prevParsedValue.remove();}if(newParsedValue&&isDisplayObject(newParsedValue)){this.markerEndAngle=newParsedValue.getLocalEulerAngles();this.appendChild(newParsedValue);this.transformMarker(false);}}else if(attrName==='markerMid'){this.placeMarkerMid(newParsedValue);}};_proto.transformMarker=function transformMarker(isStart){var _this$parsedStyle2=this.parsedStyle,markerStart=_this$parsedStyle2.markerStart,markerEnd=_this$parsedStyle2.markerEnd,markerStartOffset=_this$parsedStyle2.markerStartOffset,markerEndOffset=_this$parsedStyle2.markerEndOffset,defX=_this$parsedStyle2.defX,defY=_this$parsedStyle2.defY;var marker=isStart?markerStart:markerEnd;if(!marker||!isDisplayObject(marker)){return;}var rad=0;var x;var y;var ox;var oy;var offset;var originalAngle;if(isStart){var _this$getStartTangent=this.getStartTangent(),p1=_this$getStartTangent[0],p2=_this$getStartTangent[1];ox=p2[0]-defX;oy=p2[1]-defY;x=p1[0]-p2[0];y=p1[1]-p2[1];offset=markerStartOffset||0;originalAngle=this.markerStartAngle;}else {var _this$getEndTangent=this.getEndTangent(),_p=_this$getEndTangent[0],_p2=_this$getEndTangent[1];ox=_p2[0]-defX;oy=_p2[1]-defY;x=_p[0]-_p2[0];y=_p[1]-_p2[1];offset=markerEndOffset||0;originalAngle=this.markerEndAngle;}rad=Math.atan2(y,x);// account for markerOffset
- marker.setLocalEulerAngles(rad*180/Math.PI+originalAngle);marker.setLocalPosition(ox+Math.cos(rad)*offset,oy+Math.sin(rad)*offset);};_proto.placeMarkerMid=function placeMarkerMid(marker){var _this$parsedStyle3=this.parsedStyle,segments=_this$parsedStyle3.path.segments,defX=_this$parsedStyle3.defX,defY=_this$parsedStyle3.defY;// clear all existed markers
- this.markerMidList.forEach(function(marker){marker.remove();});if(marker&&isDisplayObject(marker)){for(var i=1;i<segments.length-1;i++){var _segments$i$currentPo=segments[i].currentPoint,ox=_segments$i$currentPo[0],oy=_segments$i$currentPo[1];var cloned=i===1?marker:marker.cloneNode(true);this.markerMidList.push(cloned);this.appendChild(cloned);cloned.setLocalPosition(ox-defX,oy-defY);// TODO: orient of marker
- }}}/**
- * Returns the total length of the path.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
- */;_proto.getTotalLength=function getTotalLength(){return getOrCalculatePathTotalLength(this);}/**
- * Returns the point at a given distance along the path.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getPointAtLength
- */;_proto.getPointAtLength=function getPointAtLength$1(distance,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}var _this$parsedStyle4=this.parsedStyle,defX=_this$parsedStyle4.defX,defY=_this$parsedStyle4.defY,absolutePath=_this$parsedStyle4.path.absolutePath;var _getPointAtLength2=getPointAtLength(absolutePath,distance),x=_getPointAtLength2.x,y=_getPointAtLength2.y;var transformed=transformMat4(create$2(),fromValues$2(x-defX,y-defY,0),inWorldSpace?this.getWorldTransform():this.getLocalTransform());// apply local transformation
- return new Point(transformed[0],transformed[1]);}/**
- * Returns the point at a given ratio of the total length in path.
- */;_proto.getPoint=function getPoint(ratio,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}return this.getPointAtLength(ratio*getOrCalculatePathTotalLength(this),inWorldSpace);}/**
- * Get start tangent vector
- */;_proto.getStartTangent=function getStartTangent(){var segments=this.parsedStyle.path.segments;var result=[];if(segments.length>1){var startPoint=segments[0].currentPoint;var endPoint=segments[1].currentPoint;var tangent=segments[1].startTangent;result=[];if(tangent){result.push([startPoint[0]-tangent[0],startPoint[1]-tangent[1]]);result.push([startPoint[0],startPoint[1]]);}else {result.push([endPoint[0],endPoint[1]]);result.push([startPoint[0],startPoint[1]]);}}return result;}/**
- * Get end tangent vector
- */;_proto.getEndTangent=function getEndTangent(){var segments=this.parsedStyle.path.segments;var length=segments.length;var result=[];if(length>1){var startPoint=segments[length-2].currentPoint;var endPoint=segments[length-1].currentPoint;var tangent=segments[length-1].endTangent;result=[];if(tangent){result.push([endPoint[0]-tangent[0],endPoint[1]-tangent[1]]);result.push([endPoint[0],endPoint[1]]);}else {result.push([startPoint[0],startPoint[1]]);result.push([endPoint[0],endPoint[1]]);}}return result;};return Path;}(DisplayObject);var _excluded$8=["style"];var Polygon=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Polygon,_DisplayObject);function Polygon(_temp){var _this;var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$8);_this=_DisplayObject.call(this,_extends({type:exports.Shape.POLYGON,style:runtime.enableCSSParsing?_extends({points:'',miterLimit:'',isClosed:true},style):_extends({},style),initialParsedStyle:runtime.enableCSSParsing?null:{points:{points:[],totalLength:0,segments:[]},miterLimit:4,isClosed:true}},rest))||this;_this.markerStartAngle=0;_this.markerEndAngle=0;/**
- * markers placed at the mid
- */_this.markerMidList=[];var _this$parsedStyle=_this.parsedStyle,markerStart=_this$parsedStyle.markerStart,markerEnd=_this$parsedStyle.markerEnd,markerMid=_this$parsedStyle.markerMid;if(markerStart&&isDisplayObject(markerStart)){_this.markerStartAngle=markerStart.getLocalEulerAngles();_this.appendChild(markerStart);}if(markerMid&&isDisplayObject(markerMid)){_this.placeMarkerMid(markerMid);}if(markerEnd&&isDisplayObject(markerEnd)){_this.markerEndAngle=markerEnd.getLocalEulerAngles();_this.appendChild(markerEnd);}_this.transformMarker(true);_this.transformMarker(false);return _this;}var _proto=Polygon.prototype;_proto.attributeChangedCallback=function attributeChangedCallback(attrName,oldValue,newValue,prevParsedValue,newParsedValue){if(attrName==='points'){// recalc markers
- this.transformMarker(true);this.transformMarker(false);this.placeMarkerMid(this.parsedStyle.markerMid);}else if(attrName==='markerStartOffset'||attrName==='markerEndOffset'){this.transformMarker(true);this.transformMarker(false);}else if(attrName==='markerStart'){if(prevParsedValue&&isDisplayObject(prevParsedValue)){this.markerStartAngle=0;prevParsedValue.remove();}// CSSKeyword 'unset'
- if(newParsedValue&&isDisplayObject(newParsedValue)){this.markerStartAngle=newParsedValue.getLocalEulerAngles();this.appendChild(newParsedValue);this.transformMarker(true);}}else if(attrName==='markerEnd'){if(prevParsedValue&&isDisplayObject(prevParsedValue)){this.markerEndAngle=0;prevParsedValue.remove();}if(newParsedValue&&isDisplayObject(newParsedValue)){this.markerEndAngle=newParsedValue.getLocalEulerAngles();this.appendChild(newParsedValue);this.transformMarker(false);}}else if(attrName==='markerMid'){this.placeMarkerMid(newParsedValue);}};_proto.transformMarker=function transformMarker(isStart){var _this$parsedStyle2=this.parsedStyle,markerStart=_this$parsedStyle2.markerStart,markerEnd=_this$parsedStyle2.markerEnd,markerStartOffset=_this$parsedStyle2.markerStartOffset,markerEndOffset=_this$parsedStyle2.markerEndOffset,points=_this$parsedStyle2.points.points,defX=_this$parsedStyle2.defX,defY=_this$parsedStyle2.defY;var marker=isStart?markerStart:markerEnd;if(!marker||!isDisplayObject(marker)){return;}var rad=0;var x;var y;var ox;var oy;var offset;var originalAngle;ox=points[0][0]-defX;oy=points[0][1]-defY;if(isStart){x=points[1][0]-points[0][0];y=points[1][1]-points[0][1];offset=markerStartOffset||0;originalAngle=this.markerStartAngle;}else {var length=points.length;if(!this.parsedStyle.isClosed){ox=points[length-1][0]-defX;oy=points[length-1][1]-defY;x=points[length-2][0]-points[length-1][0];y=points[length-2][1]-points[length-1][1];}else {x=points[length-1][0]-points[0][0];y=points[length-1][1]-points[0][1];}offset=markerEndOffset||0;originalAngle=this.markerEndAngle;}rad=Math.atan2(y,x);// account for markerOffset
- marker.setLocalEulerAngles(rad*180/Math.PI+originalAngle);marker.setLocalPosition(ox+Math.cos(rad)*offset,oy+Math.sin(rad)*offset);};_proto.placeMarkerMid=function placeMarkerMid(marker){var _this$parsedStyle3=this.parsedStyle,points=_this$parsedStyle3.points.points,defX=_this$parsedStyle3.defX,defY=_this$parsedStyle3.defY;// clear all existed markers
- this.markerMidList.forEach(function(marker){marker.remove();});this.markerMidList=[];if(marker&&isDisplayObject(marker)){for(var i=1;i<(this.parsedStyle.isClosed?points.length:points.length-1);i++){var ox=points[i][0]-defX;var oy=points[i][1]-defY;var cloned=i===1?marker:marker.cloneNode(true);this.markerMidList.push(cloned);this.appendChild(cloned);cloned.setLocalPosition(ox,oy);// TODO: orient of marker
- }}};return Polygon;}(DisplayObject);var _excluded$9=["style"];/**
- * Polyline inherits the marker-related capabilities of Polygon.
- */var Polyline=/*#__PURE__*/function(_Polygon){_inheritsLoose(Polyline,_Polygon);function Polyline(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$9);return _Polygon.call(this,_extends({type:exports.Shape.POLYLINE,style:runtime.enableCSSParsing?_extends({points:'',miterLimit:'',isClosed:false},style):_extends({},style),initialParsedStyle:runtime.enableCSSParsing?null:{points:{points:[],totalLength:0,segments:[]},miterLimit:4,isClosed:false}},rest))||this;}var _proto=Polyline.prototype;_proto.getTotalLength=function getTotalLength(){return this.parsedStyle.points.totalLength;};_proto.getPointAtLength=function getPointAtLength(distance,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}return this.getPoint(distance/this.getTotalLength(),inWorldSpace);};_proto.getPoint=function getPoint(ratio,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}var _this$parsedStyle=this.parsedStyle,defX=_this$parsedStyle.defX,defY=_this$parsedStyle.defY,_this$parsedStyle$poi=_this$parsedStyle.points,points=_this$parsedStyle$poi.points,segments=_this$parsedStyle$poi.segments;var subt=0;var index=0;segments.forEach(function(v,i){if(ratio>=v[0]&&ratio<=v[1]){subt=(ratio-v[0])/(v[1]-v[0]);index=i;}});var _LineUtil$pointAt=line.pointAt(points[index][0],points[index][1],points[index+1][0],points[index+1][1],subt),x=_LineUtil$pointAt.x,y=_LineUtil$pointAt.y;var transformed=transformMat4(create$2(),fromValues$2(x-defX,y-defY,0),inWorldSpace?this.getWorldTransform():this.getLocalTransform());// apply local transformation
- return new Point(transformed[0],transformed[1]);};_proto.getStartTangent=function getStartTangent(){var points=this.parsedStyle.points.points;var result=[];result.push([points[1][0],points[1][1]]);result.push([points[0][0],points[0][1]]);return result;};_proto.getEndTangent=function getEndTangent(){var points=this.parsedStyle.points.points;var l=points.length-1;var result=[];result.push([points[l-1][0],points[l-1][1]]);result.push([points[l][0],points[l][1]]);return result;};return Polyline;}(Polygon);var _excluded$a=["style"];var Rect=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Rect,_DisplayObject);function Rect(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$a);return _DisplayObject.call(this,_extends({type:exports.Shape.RECT,style:runtime.enableCSSParsing?_extends({x:'',y:'',width:'',height:'',radius:''},style):_extends({},style)},rest))||this;}return Rect;}(DisplayObject);var _excluded$b=["style"];/**
- * <text> @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextElement
- */var Text=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Text,_DisplayObject);/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement#constants
- */ // LENGTHADJUST_SPACING: number = 1;
- // LENGTHADJUST_SPACINGANDGLYPHS: number = 2;
- // LENGTHADJUST_UNKNOWN: number = 0;
- function Text(_temp){var _ref=_temp===void 0?{}:_temp,style=_ref.style,rest=_objectWithoutPropertiesLoose(_ref,_excluded$b);return _DisplayObject.call(this,_extends({type:exports.Shape.TEXT,style:runtime.enableCSSParsing?_extends({x:'',y:'',text:'',fontSize:'',fontFamily:'',fontStyle:'',fontWeight:'',fontVariant:'',textAlign:'',textBaseline:'',textTransform:'',fill:'black',letterSpacing:'',lineHeight:'',miterLimit:'',// whiteSpace: 'pre',
- wordWrap:false,wordWrapWidth:0,leading:0,dx:'',dy:'',isBillboard:false,sizeAttenuation:true},style):_extends({fill:'black'},style),initialParsedStyle:runtime.enableCSSParsing?{}:{x:0,y:0,fontSize:16,fontFamily:'sans-serif',fontStyle:'normal',fontWeight:'normal',fontVariant:'normal',lineHeight:0,letterSpacing:0,textBaseline:'alphabetic',textAlign:'start',wordWrap:false,wordWrapWidth:0,leading:0,dx:0,dy:0,isBillboard:false,sizeAttenuation:true}},rest))||this;}// lengthAdjust: SVGAnimatedEnumeration;
- // textLength: SVGAnimatedLength;
- // getCharNumAtPosition(point?: DOMPointInit): number {
- // throw new Error('Method not implemented.');
- // }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement
- */var _proto=Text.prototype;_proto.getComputedTextLength=function getComputedTextLength(){var _this$parsedStyle$met;return ((_this$parsedStyle$met=this.parsedStyle.metrics)===null||_this$parsedStyle$met===void 0?void 0:_this$parsedStyle$met.maxLineWidth)||0;}// getEndPositionOfChar(charnum: number): DOMPoint {
- // throw new Error('Method not implemented.');
- // }
- // getExtentOfChar(charnum: number): DOMRect {
- // throw new Error('Method not implemented.');
- // }
- // getNumberOfChars(): number {
- // throw new Error('Method not implemented.');
- // }
- // getRotationOfChar(charnum: number): number {
- // throw new Error('Method not implemented.');
- // }
- // getStartPositionOfChar(charnum: number): DOMPoint {
- // throw new Error('Method not implemented.');
- // }
- // getSubStringLength(charnum: number, nchars: number): number {
- // throw new Error('Method not implemented.');
- // }
- // selectSubString(charnum: number, nchars: number): void {
- // throw new Error('Method not implemented.');
- // }
- ;_proto.getLineBoundingRects=function getLineBoundingRects(){var _this$parsedStyle$met2;return ((_this$parsedStyle$met2=this.parsedStyle.metrics)===null||_this$parsedStyle$met2===void 0?void 0:_this$parsedStyle$met2.lineMetrics)||[];};_proto.isOverflowing=function isOverflowing(){return !!this.parsedStyle.isOverflowing;};return Text;}(DisplayObject);/**
- * Blink used them in code generation(css_properties.json5)
- */var BUILT_IN_PROPERTIES=[{/**
- * used in CSS Layout API
- * eg. `display: 'flex'`
- */n:'display',k:['none']},{/**
- * range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity
- */n:'opacity',int:true,inh:true,d:'1',syntax:exports.PropertySyntax.OPACITY_VALUE},{/**
- * inheritable, range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity
- * @see https://svgwg.org/svg2-draft/painting.html#FillOpacity
- */n:'fillOpacity',int:true,inh:true,d:'1',syntax:exports.PropertySyntax.OPACITY_VALUE},{/**
- * inheritable, range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity
- * @see https://svgwg.org/svg2-draft/painting.html#StrokeOpacity
- */n:'strokeOpacity',int:true,inh:true,d:'1',syntax:exports.PropertySyntax.OPACITY_VALUE},{/**
- * background-color is not inheritable
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
- */n:'fill',int:true,k:['none'],d:'none',syntax:exports.PropertySyntax.PAINT},{n:'fillRule',k:['nonzero','evenodd'],d:'nonzero'},/**
- * default to none
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke#usage_notes
- */{n:'stroke',int:true,k:['none'],d:'none',syntax:exports.PropertySyntax.PAINT,/**
- * Stroke 'none' won't affect geometry but others will.
- */l:true},{n:'shadowType',k:['inner','outer','both'],d:'outer',l:true},{n:'shadowColor',int:true,syntax:exports.PropertySyntax.COLOR},{n:'shadowOffsetX',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'shadowOffsetY',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'shadowBlur',int:true,l:true,d:'0',syntax:exports.PropertySyntax.SHADOW_BLUR},{/**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width
- */n:'lineWidth',int:true,inh:true,d:'1',l:true,a:['strokeWidth'],syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'increasedLineWidthForHitTesting',inh:true,d:'0',l:true,syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'lineJoin',inh:true,l:true,a:['strokeLinejoin'],k:['miter','bevel','round'],d:'miter'},{n:'lineCap',inh:true,l:true,a:['strokeLinecap'],k:['butt','round','square'],d:'butt'},{n:'lineDash',int:true,inh:true,k:['none'],a:['strokeDasharray'],syntax:exports.PropertySyntax.LENGTH_PERCENTAGE_12},{n:'lineDashOffset',int:true,inh:true,d:'0',a:['strokeDashoffset'],syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'offsetPath',syntax:exports.PropertySyntax.DEFINED_PATH},{n:'offsetDistance',int:true,syntax:exports.PropertySyntax.OFFSET_DISTANCE},{n:'dx',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'dy',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'zIndex',ind:true,int:true,d:'0',k:['auto'],syntax:exports.PropertySyntax.Z_INDEX},{n:'visibility',k:['visible','hidden'],ind:true,inh:true,/**
- * support interpolation
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#interpolation
- */int:true,d:'visible'},{n:'pointerEvents',inh:true,k:['none','auto','stroke','fill','painted','visible','visiblestroke','visiblefill','visiblepainted',// 'bounding-box',
- 'all'],d:'auto'},{n:'filter',ind:true,l:true,k:['none'],d:'none',syntax:exports.PropertySyntax.FILTER},{n:'clipPath',syntax:exports.PropertySyntax.DEFINED_PATH},{n:'textPath',syntax:exports.PropertySyntax.DEFINED_PATH},{n:'textPathSide',k:['left','right'],d:'left'},{n:'textPathStartOffset',l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'transform',p:100,int:true,k:['none'],d:'none',syntax:exports.PropertySyntax.TRANSFORM},{n:'transformOrigin',p:100,// int: true,
- d:function d(nodeName){if(nodeName===exports.Shape.CIRCLE||nodeName===exports.Shape.ELLIPSE){return 'center';}if(nodeName===exports.Shape.TEXT){return 'text-anchor';}return 'left top';},l:true,syntax:exports.PropertySyntax.TRANSFORM_ORIGIN},{n:'anchor',p:99,d:function d(nodeName){if(nodeName===exports.Shape.CIRCLE||nodeName===exports.Shape.ELLIPSE){return '0.5 0.5';}return '0 0';},l:true,syntax:exports.PropertySyntax.LENGTH_PERCENTAGE_12},// <circle> & <ellipse>
- {n:'cx',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{n:'cy',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{n:'cz',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{n:'r',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'rx',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'ry',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},// Rect Image Group
- {// x in local space
- n:'x',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{// y in local space
- n:'y',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{// z in local space
- n:'z',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{n:'width',int:true,l:true,/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
- */k:['auto','fit-content','min-content','max-content'],d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'height',int:true,l:true,/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/height
- */k:['auto','fit-content','min-content','max-content'],d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'radius',int:true,l:true,d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE_14},// Line
- {n:'x1',int:true,l:true,syntax:exports.PropertySyntax.COORDINATE},{n:'y1',int:true,l:true,syntax:exports.PropertySyntax.COORDINATE},{n:'z1',int:true,l:true,syntax:exports.PropertySyntax.COORDINATE},{n:'x2',int:true,l:true,syntax:exports.PropertySyntax.COORDINATE},{n:'y2',int:true,l:true,syntax:exports.PropertySyntax.COORDINATE},{n:'z2',int:true,l:true,syntax:exports.PropertySyntax.COORDINATE},// Path
- {n:'path',int:true,l:true,d:'',a:['d'],syntax:exports.PropertySyntax.PATH,p:50},// Polyline & Polygon
- {n:'points',/**
- * support interpolation
- */int:true,l:true,syntax:exports.PropertySyntax.LIST_OF_POINTS,p:50},// Text
- {n:'text',l:true,d:'',syntax:exports.PropertySyntax.TEXT,p:50},{n:'textTransform',l:true,inh:true,k:['capitalize','uppercase','lowercase','none'],d:'none',syntax:exports.PropertySyntax.TEXT_TRANSFORM,p:51// it must get parsed after text
- },{n:'font',l:true},{n:'fontSize',int:true,inh:true,/**
- * @see https://www.w3schools.com/css/css_font_size.asp
- */d:'16px',l:true,syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'fontFamily',l:true,inh:true,d:'sans-serif'},{n:'fontStyle',l:true,inh:true,k:['normal','italic','oblique'],d:'normal'},{n:'fontWeight',l:true,inh:true,k:['normal','bold','bolder','lighter'],d:'normal'},{n:'fontVariant',l:true,inh:true,k:['normal','small-caps'],d:'normal'},{n:'lineHeight',l:true,syntax:exports.PropertySyntax.LENGTH,int:true,d:'0'},{n:'letterSpacing',l:true,syntax:exports.PropertySyntax.LENGTH,int:true,d:'0'},{n:'miterLimit',l:true,syntax:exports.PropertySyntax.NUMBER,d:function d(nodeName){if(nodeName===exports.Shape.PATH||nodeName===exports.Shape.POLYGON||nodeName===exports.Shape.POLYLINE){return '4';}return '10';}},{n:'wordWrap',l:true},{n:'wordWrapWidth',l:true},{n:'maxLines',l:true},{n:'textOverflow',l:true,d:'clip'},{n:'leading',l:true},{n:'textBaseline',l:true,inh:true,k:['top','hanging','middle','alphabetic','ideographic','bottom'],d:'alphabetic'},{n:'textAlign',l:true,inh:true,k:['start','center','middle','end','left','right'],d:'start'},// {
- // n: 'whiteSpace',
- // l: true,
- // },
- {n:'markerStart',syntax:exports.PropertySyntax.MARKER},{n:'markerEnd',syntax:exports.PropertySyntax.MARKER},{n:'markerMid',syntax:exports.PropertySyntax.MARKER},{n:'markerStartOffset',syntax:exports.PropertySyntax.LENGTH,l:true,int:true,d:'0'},{n:'markerEndOffset',syntax:exports.PropertySyntax.LENGTH,l:true,int:true,d:'0'}];var GEOMETRY_ATTRIBUTE_NAMES=BUILT_IN_PROPERTIES.filter(function(n){return !!n.l;}).map(function(n){return n.n;});var propertyMetadataCache={};var unresolvedProperties=new WeakMap();// const uniqueAttributeSet = new Set<string>();
- // const tmpVec3a = vec3.create();
- // const tmpVec3b = vec3.create();
- // const tmpVec3c = vec3.create();
- var isPropertyResolved=function isPropertyResolved(object,name){var properties=unresolvedProperties.get(object);if(!properties||properties.length===0){return true;}return properties.includes(name);};var DefaultStyleValueRegistry=/*#__PURE__*/function(){/**
- * need recalc later
- */ // dirty = false;
- function DefaultStyleValueRegistry(){var _this=this;BUILT_IN_PROPERTIES.forEach(function(property){_this.registerMetadata(property);});}var _proto=DefaultStyleValueRegistry.prototype;_proto.registerMetadata=function registerMetadata(metadata){[metadata.n].concat(metadata.a||[]).forEach(function(name){propertyMetadataCache[name]=metadata;});};_proto.unregisterMetadata=function unregisterMetadata(name){delete propertyMetadataCache[name];};_proto.getPropertySyntax=function getPropertySyntax(syntax){return runtime.CSSPropertySyntaxFactory[syntax];}/**
- * * parse value, eg.
- * fill: 'red' => CSSRGB
- * translateX: '10px' => CSSUnitValue { unit: 'px', value: 10 }
- * fontSize: '2em' => { unit: 'px', value: 32 }
- *
- * * calculate used value
- * * post process
- */;_proto.processProperties=function processProperties(object,attributes,options){var _this2=this;if(options===void 0){options={skipUpdateAttribute:false,skipParse:false,forceUpdateGeometry:false,usedAttributes:[]};}if(!runtime.enableCSSParsing){Object.assign(object.attributes,attributes);var _attributeNames=Object.keys(attributes);// clipPath
- var oldClipPath=object.parsedStyle.clipPath;var oldOffsetPath=object.parsedStyle.offsetPath;object.parsedStyle=Object.assign(object.parsedStyle,attributes);var _needUpdateGeometry=!!options.forceUpdateGeometry;if(!_needUpdateGeometry){for(var i=0;i<GEOMETRY_ATTRIBUTE_NAMES.length;i++){if(GEOMETRY_ATTRIBUTE_NAMES[i]in attributes){_needUpdateGeometry=true;break;}}}if(attributes.fill){object.parsedStyle.fill=parseColor(attributes.fill);}if(attributes.stroke){object.parsedStyle.stroke=parseColor(attributes.stroke);}if(attributes.shadowColor){object.parsedStyle.shadowColor=parseColor(attributes.shadowColor);}if(attributes.filter){object.parsedStyle.filter=parseFilter(attributes.filter);}// Rect
- // @ts-ignore
- if(!isNil(attributes.radius)){// @ts-ignore
- object.parsedStyle.radius=parseDimensionArrayFormat(// @ts-ignore
- attributes.radius,4);}// Polyline
- if(!isNil(attributes.lineDash)){object.parsedStyle.lineDash=parseDimensionArrayFormat(attributes.lineDash,2);}// @ts-ignore
- if(attributes.points){// @ts-ignore
- object.parsedStyle.points=parsePoints(attributes.points,object);}// Path
- // @ts-ignore
- if(attributes.path===''){object.parsedStyle.path=_extends({},EMPTY_PARSED_PATH);}// @ts-ignore
- if(attributes.path){object.parsedStyle.path=parsePath(// @ts-ignore
- attributes.path,object);}// Text
- if(attributes.textTransform){runtime.CSSPropertySyntaxFactory['<text-transform>'].calculator(null,null,{value:attributes.textTransform},object,null);}if(attributes.clipPath){runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('clipPath',oldClipPath,attributes.clipPath,object,this);}if(attributes.offsetPath){runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('offsetPath',oldOffsetPath,attributes.offsetPath,object,this);}if(attributes.anchor){object.parsedStyle.anchor=parseDimensionArrayFormat(// @ts-ignorex
- attributes.anchor,2);}if(attributes.transform){object.parsedStyle.transform=parseTransform(attributes.transform);}if(attributes.transformOrigin){object.parsedStyle.transformOrigin=parseTransformOrigin(attributes.transformOrigin);}// Marker
- // @ts-ignore
- if(attributes.markerStart){// @ts-ignore
- object.parsedStyle.markerStart=runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,// @ts-ignore
- attributes.markerStart,// @ts-ignore
- attributes.markerStart,null,null);}// @ts-ignore
- if(attributes.markerEnd){// @ts-ignore
- object.parsedStyle.markerEnd=runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,// @ts-ignore
- attributes.markerEnd,// @ts-ignore
- attributes.markerEnd,null,null);}// @ts-ignore
- if(attributes.markerMid){// @ts-ignore
- object.parsedStyle.markerMid=runtime.CSSPropertySyntaxFactory['<marker>'].calculator('',// @ts-ignore
- attributes.markerMid,// @ts-ignore
- attributes.markerMid,null,null);}if(// Circle & Ellipse
- (object.nodeName===exports.Shape.CIRCLE||object.nodeName===exports.Shape.ELLIPSE)&&(// @ts-ignore
- !isNil(attributes.cx)||// @ts-ignore
- !isNil(attributes.cy))||(object.nodeName===exports.Shape.RECT||object.nodeName===exports.Shape.IMAGE||object.nodeName===exports.Shape.GROUP||object.nodeName===exports.Shape.HTML||object.nodeName===exports.Shape.TEXT||object.nodeName===exports.Shape.MESH)&&(// @ts-ignore
- !isNil(attributes.x)||// @ts-ignore
- !isNil(attributes.y)||// @ts-ignore
- !isNil(attributes.z))||// Line
- object.nodeName===exports.Shape.LINE&&(// @ts-ignore
- !isNil(attributes.x1)||// @ts-ignore
- !isNil(attributes.y1)||// @ts-ignore
- !isNil(attributes.z1)||// @ts-ignore
- !isNil(attributes.x2)||// @ts-ignore
- !isNil(attributes.y2)||// @ts-ignore
- !isNil(attributes.z2))){runtime.CSSPropertySyntaxFactory['<coordinate>'].postProcessor(object,_attributeNames);}if(!isNil(attributes.zIndex)){runtime.CSSPropertySyntaxFactory['<z-index>'].postProcessor(object,_attributeNames);}// @ts-ignore
- if(attributes.path){runtime.CSSPropertySyntaxFactory['<path>'].postProcessor(object,_attributeNames);}// @ts-ignore
- if(attributes.points){runtime.CSSPropertySyntaxFactory['<list-of-points>'].postProcessor(object,_attributeNames);}if(!isNil(attributes.offsetDistance)){runtime.CSSPropertySyntaxFactory['<offset-distance>'].postProcessor(object,_attributeNames);}if(attributes.transform){runtime.CSSPropertySyntaxFactory['<transform>'].postProcessor(object,_attributeNames);}if(_needUpdateGeometry){this.updateGeometry(object);}return;}var _options=options,skipUpdateAttribute=_options.skipUpdateAttribute,skipParse=_options.skipParse,forceUpdateGeometry=_options.forceUpdateGeometry,usedAttributes=_options.usedAttributes;var needUpdateGeometry=forceUpdateGeometry;var attributeNames=Object.keys(attributes);attributeNames.forEach(function(attributeName){var _propertyMetadataCach;if(!skipUpdateAttribute){object.attributes[attributeName]=attributes[attributeName];}if(!needUpdateGeometry&&((_propertyMetadataCach=propertyMetadataCache[attributeName])===null||_propertyMetadataCach===void 0?void 0:_propertyMetadataCach.l)){needUpdateGeometry=true;}});if(!skipParse){attributeNames.forEach(function(name){object.computedStyle[name]=_this2.parseProperty(name,object.attributes[name],object);});}// let hasUnresolvedProperties = false;
- // parse according to priority
- // path 50
- // points 50
- // text 50
- // textTransform 51
- // anchor 99
- // transform 100
- // transformOrigin 100
- if(usedAttributes===null||usedAttributes===void 0?void 0:usedAttributes.length){// uniqueAttributeSet.clear();
- attributeNames=Array.from(new Set(attributeNames.concat(usedAttributes)));}// [
- // 'path',
- // 'points',
- // 'text',
- // 'textTransform',
- // 'anchor',
- // 'transform',
- // 'transformOrigin',
- // ].forEach((name) => {
- // const index = attributeNames.indexOf(name);
- // if (index > -1) {
- // attributeNames.splice(index, 1);
- // attributeNames.push(name);
- // }
- // });
- attributeNames.forEach(function(name){// some style props maybe deleted after parsing such as `anchor` in Text
- if(name in object.computedStyle){object.parsedStyle[name]=_this2.computeProperty(name,object.computedStyle[name],object);}});// if (hasUnresolvedProperties) {
- // this.dirty = true;
- // return;
- // }
- // update geometry
- if(needUpdateGeometry){// object.geometry.dirty = true;
- // runtime.sceneGraphService.dirtifyToRoot(object);
- this.updateGeometry(object);}attributeNames.forEach(function(name){if(name in object.parsedStyle){_this2.postProcessProperty(name,object,attributeNames);}});if(runtime.enableCSSParsing&&object.children.length){attributeNames.forEach(function(name){if(name in object.parsedStyle&&_this2.isPropertyInheritable(name)){// update children's inheritable
- object.children.forEach(function(child){child.internalSetAttribute(name,null,{skipUpdateAttribute:true,skipParse:true});});}});}}/**
- * string -> parsed value
- */;_proto.parseProperty=function parseProperty(name,value,object){var metadata=propertyMetadataCache[name];var computed=value;if(value===''||isNil(value)){value='unset';}if(value==='unset'||value==='initial'||value==='inherit'){// computed = new CSSKeywordValue(value);
- computed=getOrCreateKeyword(value);}else {if(metadata){var keywords=metadata.k,syntax=metadata.syntax;var handler=syntax&&this.getPropertySyntax(syntax);// use keywords
- if(keywords&&keywords.indexOf(value)>-1){// computed = new CSSKeywordValue(value);
- computed=getOrCreateKeyword(value);}else if(handler&&handler.parser){// try to parse it to CSSStyleValue, eg. '10px' -> CSS.px(10)
- computed=handler.parser(value,object);}}}return computed;}/**
- * computed value -> used value
- */;_proto.computeProperty=function computeProperty(name,computed,object){var metadata=propertyMetadataCache[name];var isDocumentElement=object.id==='g-root';// let used: CSSStyleValue = computed instanceof CSSStyleValue ? computed.clone() : computed;
- var used=computed;if(metadata){var syntax=metadata.syntax,inherited=metadata.inh,defaultValue=metadata.d;if(computed instanceof CSSKeywordValue){var value=computed.value;/**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/unset
- */if(value==='unset'){if(inherited&&!isDocumentElement){value='inherit';}else {value='initial';}}if(value==='initial'){// @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial
- if(!isNil(defaultValue)){computed=this.parseProperty(name,isFunction(defaultValue)?defaultValue(object.nodeName):defaultValue,object);}}else if(value==='inherit'){// @see https://developer.mozilla.org/en-US/docs/Web/CSS/inherit
- // behave like `inherit`
- var resolved=this.tryToResolveProperty(object,name,{inherited:true});if(!isNil(resolved)){// object.parsedStyle[name] = resolved;
- // return false;
- return resolved;}else {this.addUnresolveProperty(object,name);return;}}}var handler=syntax&&this.getPropertySyntax(syntax);if(handler&&handler.calculator){// convert computed value to used value
- var oldParsedValue=object.parsedStyle[name];used=handler.calculator(name,oldParsedValue,computed,object,this);}else if(computed instanceof CSSKeywordValue){used=computed.value;}else {used=computed;}}// object.parsedStyle[name] = used;
- // return false;
- return used;};_proto.postProcessProperty=function postProcessProperty(name,object,attributes){var metadata=propertyMetadataCache[name];if(metadata&&metadata.syntax){var handler=metadata.syntax&&this.getPropertySyntax(metadata.syntax);var propertyHandler=handler;if(propertyHandler&&propertyHandler.postProcessor){propertyHandler.postProcessor(object,attributes);}}}/**
- * resolve later
- */;_proto.addUnresolveProperty=function addUnresolveProperty(object,name){var properties=unresolvedProperties.get(object);if(!properties){unresolvedProperties.set(object,[]);properties=unresolvedProperties.get(object);}if(properties.indexOf(name)===-1){properties.push(name);}};_proto.tryToResolveProperty=function tryToResolveProperty(object,name,options){if(options===void 0){options={};}var _options2=options,inherited=_options2.inherited;if(inherited){if(object.parentElement&&isPropertyResolved(object.parentElement,name)){// const computedValue = object.parentElement.computedStyle[name];
- var usedValue=object.parentElement.parsedStyle[name];if(// usedValue instanceof CSSKeywordValue &&
- usedValue==='unset'||usedValue==='initial'||usedValue==='inherit'){return;}// else if (
- // usedValue instanceof CSSUnitValue &&
- // CSSUnitValue.isRelativeUnit(usedValue.unit)
- // ) {
- // return false;
- // }
- return usedValue;}}return;};_proto.recalc=function recalc(object){var properties=unresolvedProperties.get(object);if(properties&&properties.length){var attributes={};properties.forEach(function(property){attributes[property]=object.attributes[property];});this.processProperties(object,attributes);unresolvedProperties.delete(object);}}/**
- * update geometry when relative props changed,
- * eg. r of Circle, width/height of Rect
- */;_proto.updateGeometry=function updateGeometry(object){var nodeName=object.nodeName;var geometryUpdater=runtime.geometryUpdaterFactory[nodeName];if(geometryUpdater){var geometry=object.geometry;if(!geometry.contentBounds){geometry.contentBounds=new AABB();}if(!geometry.renderBounds){geometry.renderBounds=new AABB();}var parsedStyle=object.parsedStyle;var _geometryUpdater$upda=geometryUpdater.update(parsedStyle,object),width=_geometryUpdater$upda.width,height=_geometryUpdater$upda.height,_geometryUpdater$upda2=_geometryUpdater$upda.depth,depth=_geometryUpdater$upda2===void 0?0:_geometryUpdater$upda2,_geometryUpdater$upda3=_geometryUpdater$upda.offsetX,offsetX=_geometryUpdater$upda3===void 0?0:_geometryUpdater$upda3,_geometryUpdater$upda4=_geometryUpdater$upda.offsetY,offsetY=_geometryUpdater$upda4===void 0?0:_geometryUpdater$upda4,_geometryUpdater$upda5=_geometryUpdater$upda.offsetZ,offsetZ=_geometryUpdater$upda5===void 0?0:_geometryUpdater$upda5;// init with content box
- var halfExtents=[Math.abs(width)/2,Math.abs(height)/2,depth/2];// const halfExtents = vec3.set(
- // tmpVec3a,
- // Math.abs(width) / 2,
- // Math.abs(height) / 2,
- // depth / 2,
- // );
- // anchor is center by default, don't account for lineWidth here
- var stroke=parsedStyle.stroke,lineWidth=parsedStyle.lineWidth,increasedLineWidthForHitTesting=parsedStyle.increasedLineWidthForHitTesting,shadowType=parsedStyle.shadowType,shadowColor=parsedStyle.shadowColor,_parsedStyle$filter=parsedStyle.filter,filter=_parsedStyle$filter===void 0?[]:_parsedStyle$filter,transformOrigin=parsedStyle.transformOrigin;var anchor=parsedStyle.anchor;// <Text> use textAlign & textBaseline instead of anchor
- if(nodeName===exports.Shape.TEXT){delete parsedStyle.anchor;}else if(nodeName===exports.Shape.MESH){parsedStyle.anchor[2]=0.5;}var center=[(1-(anchor&&anchor[0]||0)*2)*width/2+offsetX,(1-(anchor&&anchor[1]||0)*2)*height/2+offsetY,(1-(anchor&&anchor[2]||0)*2)*halfExtents[2]+offsetZ];// const center = vec3.set(
- // tmpVec3b,
- // ((1 - ((anchor && anchor[0]) || 0) * 2) * width) / 2 + offsetX,
- // ((1 - ((anchor && anchor[1]) || 0) * 2) * height) / 2 + offsetY,
- // (1 - ((anchor && anchor[2]) || 0) * 2) * halfExtents[2] + offsetZ,
- // );
- // update geometry's AABB
- geometry.contentBounds.update(center,halfExtents);// @see https://github.molgen.mpg.de/git-mirror/cairo/blob/master/src/cairo-stroke-style.c#L97..L128
- var expansion=nodeName===exports.Shape.POLYLINE||nodeName===exports.Shape.POLYGON||nodeName===exports.Shape.PATH?Math.SQRT2:0.5;// if (lineCap?.value === 'square') {
- // expansion = Math.SQRT1_2;
- // }
- // if (lineJoin?.value === 'miter' && expansion < Math.SQRT2 * miterLimit) {
- // expansion = Math.SQRT1_2 * miterLimit;
- // }
- // append border only if stroke existed
- var hasStroke=stroke&&!stroke.isNone;if(hasStroke){var halfLineWidth=((lineWidth||0)+(increasedLineWidthForHitTesting||0))*expansion;// halfExtents[0] += halfLineWidth[0];
- // halfExtents[1] += halfLineWidth[1];
- halfExtents[0]+=halfLineWidth;halfExtents[1]+=halfLineWidth;// vec3.add(
- // halfExtents,
- // halfExtents,
- // vec3.set(tmpVec3c, halfLineWidth, halfLineWidth, 0),
- // );
- }geometry.renderBounds.update(center,halfExtents);// account for shadow, only support constant value now
- if(shadowColor&&shadowType&&shadowType!=='inner'){var _geometry$renderBound=geometry.renderBounds,min=_geometry$renderBound.min,max=_geometry$renderBound.max;var shadowBlur=parsedStyle.shadowBlur,shadowOffsetX=parsedStyle.shadowOffsetX,shadowOffsetY=parsedStyle.shadowOffsetY;var shadowBlurInPixels=shadowBlur||0;var shadowOffsetXInPixels=shadowOffsetX||0;var shadowOffsetYInPixels=shadowOffsetY||0;var shadowLeft=min[0]-shadowBlurInPixels+shadowOffsetXInPixels;var shadowRight=max[0]+shadowBlurInPixels+shadowOffsetXInPixels;var shadowTop=min[1]-shadowBlurInPixels+shadowOffsetYInPixels;var shadowBottom=max[1]+shadowBlurInPixels+shadowOffsetYInPixels;min[0]=Math.min(min[0],shadowLeft);max[0]=Math.max(max[0],shadowRight);min[1]=Math.min(min[1],shadowTop);max[1]=Math.max(max[1],shadowBottom);geometry.renderBounds.setMinMax(min,max);}// account for filter, eg. blur(5px), drop-shadow()
- filter.forEach(function(_ref){var name=_ref.name,params=_ref.params;if(name==='blur'){var blurRadius=params[0].value;geometry.renderBounds.update(geometry.renderBounds.center,addVec3(geometry.renderBounds.halfExtents,geometry.renderBounds.halfExtents,[blurRadius,blurRadius,0]));}else if(name==='drop-shadow'){var _shadowOffsetX=params[0].value;var _shadowOffsetY=params[1].value;var _shadowBlur=params[2].value;var _geometry$renderBound2=geometry.renderBounds,_min=_geometry$renderBound2.min,_max=_geometry$renderBound2.max;var _shadowLeft=_min[0]-_shadowBlur+_shadowOffsetX;var _shadowRight=_max[0]+_shadowBlur+_shadowOffsetX;var _shadowTop=_min[1]-_shadowBlur+_shadowOffsetY;var _shadowBottom=_max[1]+_shadowBlur+_shadowOffsetY;_min[0]=Math.min(_min[0],_shadowLeft);_max[0]=Math.max(_max[0],_shadowRight);_min[1]=Math.min(_min[1],_shadowTop);_max[1]=Math.max(_max[1],_shadowBottom);geometry.renderBounds.setMinMax(_min,_max);}});anchor=parsedStyle.anchor;// if (nodeName === Shape.RECT) {
- // account for negative width / height of Rect
- // @see https://github.com/antvis/g/issues/957
- var flipY=width<0;var flipX=height<0;// } else {
- // }
- // set transform origin
- var usedOriginXValue=(flipY?-1:1)*(transformOrigin?convertPercentUnit(transformOrigin[0],0,object):0);var usedOriginYValue=(flipX?-1:1)*(transformOrigin?convertPercentUnit(transformOrigin[1],1,object):0);usedOriginXValue=usedOriginXValue-(flipY?-1:1)*(anchor&&anchor[0]||0)*geometry.contentBounds.halfExtents[0]*2;usedOriginYValue=usedOriginYValue-(flipX?-1:1)*(anchor&&anchor[1]||0)*geometry.contentBounds.halfExtents[1]*2;object.setOrigin(usedOriginXValue,usedOriginYValue);// FIXME setOrigin may have already dirtified to root.
- runtime.sceneGraphService.dirtifyToRoot(object);}};_proto.isPropertyInheritable=function isPropertyInheritable(name){var metadata=propertyMetadataCache[name];if(!metadata){return false;}return metadata.inh;};return DefaultStyleValueRegistry;}();/**
- * Different type of cameras, eg. simple camera used in 2D scene or
- * advanced camera which can do actions & switch between landmarks.
- */(function(CameraType){/**
- * Performs all the rotational operations with the focal point instead of the camera position.
- * This type of camera is useful in applications(like CAD) where 3D objects are being designed or explored.
- * Camera cannot orbits over the north & south poles.
- * @see http://voxelent.com/tutorial-cameras/
- *
- * In Three.js it's used in OrbitControls.
- * @see https://threejs.org/docs/#examples/zh/controls/OrbitControls
- */CameraType[CameraType["ORBITING"]=0]="ORBITING";/**
- * It's similar to the ORBITING camera, but it allows the camera to orbit over the north or south poles.
- *
- * In Three.js it's used in OrbitControls.
- * @see https://threejs.org/docs/#examples/en/controls/TrackballControls
- */CameraType[CameraType["EXPLORING"]=1]="EXPLORING";/**
- * Performs all the rotational operations with the camera position.
- * It's useful in first person shooting games.
- * Camera cannot orbits over the north & south poles.
- *
- * In Three.js it's used in FirstPersonControls.
- * @see https://threejs.org/docs/#examples/en/controls/FirstPersonControls
- */CameraType[CameraType["TRACKING"]=2]="TRACKING";})(exports.CameraType||(exports.CameraType={}));/**
- * CameraType must be TRACKING
- */(function(CameraTrackingMode){CameraTrackingMode[CameraTrackingMode["DEFAULT"]=0]="DEFAULT";CameraTrackingMode[CameraTrackingMode["ROTATIONAL"]=1]="ROTATIONAL";CameraTrackingMode[CameraTrackingMode["TRANSLATIONAL"]=2]="TRANSLATIONAL";CameraTrackingMode[CameraTrackingMode["CINEMATIC"]=3]="CINEMATIC";})(exports.CameraTrackingMode||(exports.CameraTrackingMode={}));(function(CameraProjectionMode){CameraProjectionMode[CameraProjectionMode["ORTHOGRAPHIC"]=0]="ORTHOGRAPHIC";CameraProjectionMode[CameraProjectionMode["PERSPECTIVE"]=1]="PERSPECTIVE";})(exports.CameraProjectionMode||(exports.CameraProjectionMode={}));var CameraEvent={UPDATED:'updated'};var MIN_DISTANCE=0.0002;/**
- * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计
- * @see https://github.com/d13g0/nucleo.js/blob/master/source/camera/Camera.js
- *
- * 保存相机参数,定义相机动作:
- * 1. dolly 沿 n 轴移动
- * 2. pan 沿 u v 轴移动
- * 3. rotate 以方位角旋转
- * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互
- */var Camera=/*#__PURE__*/function(){function Camera(){this.canvas=void 0;this.eventEmitter=new eventemitter3();/**
- * 相机矩阵
- */this.matrix=create$1();/**
- * u 轴
- * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition
- */this.right=fromValues$2(1,0,0);/**
- * v 轴 +Y is down
- */this.up=fromValues$2(0,1,0);/**
- * n 轴 +Z is inside
- */this.forward=fromValues$2(0,0,1);/**
- * 相机位置
- */this.position=fromValues$2(0,0,1);/**
- * 视点位置
- */this.focalPoint=fromValues$2(0,0,0);/**
- * 视点到相机位置的向量
- * focalPoint - position
- */this.distanceVector=fromValues$2(0,0,-1);/**
- * 相机位置到视点距离
- * length(focalPoint - position)
- */this.distance=1;/**
- * @see https://en.wikipedia.org/wiki/Azimuth
- */this.azimuth=0;this.elevation=0;this.roll=0;this.relAzimuth=0;this.relElevation=0;this.relRoll=0;/**
- * 沿 n 轴移动时,保证移动速度从快到慢
- */this.dollyingStep=0;this.maxDistance=Infinity;this.minDistance=-Infinity;/**
- * zoom factor of the camera, default is 1
- * eg. https://threejs.org/docs/#api/en/cameras/OrthographicCamera.zoom
- */this.zoom=1;/**
- * invert the horizontal coordinate system HCS
- */this.rotateWorld=false;/**
- * 投影矩阵参数
- */ /**
- * field of view [0-360]
- * @see http://en.wikipedia.org/wiki/Angle_of_view
- */this.fov=30;this.near=0.1;this.far=1000;this.aspect=1;this.left=void 0;this.rright=void 0;this.top=void 0;this.bottom=void 0;this.projectionMatrix=create$1();this.projectionMatrixInverse=create$1();this.jitteredProjectionMatrix=undefined;this.view=void 0;this.enableUpdate=true;// protected following = undefined;
- this.type=exports.CameraType.EXPLORING;this.trackingMode=exports.CameraTrackingMode.DEFAULT;this.projectionMode=exports.CameraProjectionMode.PERSPECTIVE;/**
- * for culling use
- */this.frustum=new Frustum();/**
- * ortho matrix for Canvas2D & SVG
- */this.orthoMatrix=create$1();}var _proto=Camera.prototype;// constructor(type = CameraType.EXPLORING, trackingMode = CameraTrackingMode.DEFAULT) {
- // this.setType(type, trackingMode);
- // }
- _proto.isOrtho=function isOrtho(){return this.projectionMode===exports.CameraProjectionMode.ORTHOGRAPHIC;};_proto.getProjectionMode=function getProjectionMode(){return this.projectionMode;};_proto.getPerspective=function getPerspective(){// account for TAA
- return this.jitteredProjectionMatrix||this.projectionMatrix;};_proto.getPerspectiveInverse=function getPerspectiveInverse(){return this.projectionMatrixInverse;};_proto.getFrustum=function getFrustum(){return this.frustum;};_proto.getPosition=function getPosition(){return this.position;};_proto.getFocalPoint=function getFocalPoint(){return this.focalPoint;};_proto.getDollyingStep=function getDollyingStep(){return this.dollyingStep;};_proto.getNear=function getNear(){return this.near;};_proto.getFar=function getFar(){return this.far;};_proto.getZoom=function getZoom(){return this.zoom;};_proto.getOrthoMatrix=function getOrthoMatrix(){return this.orthoMatrix;};_proto.getView=function getView(){return this.view;};_proto.setEnableUpdate=function setEnableUpdate(enabled){this.enableUpdate=enabled;};_proto.setType=function setType(type,trackingMode){this.type=type;if(this.type===exports.CameraType.EXPLORING){this.setWorldRotation(true);}else {this.setWorldRotation(false);}this._getAngles();if(this.type===exports.CameraType.TRACKING&&trackingMode!==undefined){this.setTrackingMode(trackingMode);}return this;};_proto.setProjectionMode=function setProjectionMode(projectionMode){this.projectionMode=projectionMode;return this;};_proto.setTrackingMode=function setTrackingMode(trackingMode){if(this.type!==exports.CameraType.TRACKING){throw new Error('Impossible to set a tracking mode if the camera is not of tracking type');}this.trackingMode=trackingMode;return this;}/**
- * If flag is true, it reverses the azimuth and elevation angles.
- * Subsequent calls to rotate, setAzimuth, setElevation,
- * changeAzimuth or changeElevation will cause the inverted effect.
- * setRoll or changeRoll is not affected by this method.
- *
- * This inversion is useful when one wants to simulate that the world
- * is moving, instead of the camera.
- *
- * By default the camera angles are not reversed.
- * @param {Boolean} flag the boolean flag to reverse the angles.
- */;_proto.setWorldRotation=function setWorldRotation(flag){this.rotateWorld=flag;this._getAngles();return this;}/**
- * 计算 MV 矩阵,为相机矩阵的逆矩阵
- */;_proto.getViewTransform=function getViewTransform(){return invert(create$1(),this.matrix);};_proto.getWorldTransform=function getWorldTransform(){return this.matrix;};_proto.jitterProjectionMatrix=function jitterProjectionMatrix(x,y){var translation=fromTranslation(create$1(),[x,y,0]);this.jitteredProjectionMatrix=multiply(create$1(),translation,this.projectionMatrix);};_proto.clearJitterProjectionMatrix=function clearJitterProjectionMatrix(){this.jitteredProjectionMatrix=undefined;}/**
- * 设置相机矩阵
- */;_proto.setMatrix=function setMatrix(matrix){this.matrix=matrix;this._update();return this;};_proto.setFov=function setFov(fov){this.setPerspective(this.near,this.far,fov,this.aspect);return this;};_proto.setAspect=function setAspect(aspect){this.setPerspective(this.near,this.far,this.fov,aspect);return this;};_proto.setNear=function setNear(near){if(this.projectionMode===exports.CameraProjectionMode.PERSPECTIVE){this.setPerspective(near,this.far,this.fov,this.aspect);}else {this.setOrthographic(this.left,this.rright,this.top,this.bottom,near,this.far);}return this;};_proto.setFar=function setFar(far){if(this.projectionMode===exports.CameraProjectionMode.PERSPECTIVE){this.setPerspective(this.near,far,this.fov,this.aspect);}else {this.setOrthographic(this.left,this.rright,this.top,this.bottom,this.near,far);}return this;}/**
- * Sets an offset in a larger frustum, used in PixelPicking
- */;_proto.setViewOffset=function setViewOffset(fullWidth,fullHeight,x,y,width,height){this.aspect=fullWidth/fullHeight;if(this.view===undefined){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;if(this.projectionMode===exports.CameraProjectionMode.PERSPECTIVE){this.setPerspective(this.near,this.far,this.fov,this.aspect);}else {this.setOrthographic(this.left,this.rright,this.top,this.bottom,this.near,this.far);}return this;};_proto.clearViewOffset=function clearViewOffset(){if(this.view!==undefined){this.view.enabled=false;}if(this.projectionMode===exports.CameraProjectionMode.PERSPECTIVE){this.setPerspective(this.near,this.far,this.fov,this.aspect);}else {this.setOrthographic(this.left,this.rright,this.top,this.bottom,this.near,this.far);}return this;};_proto.setZoom=function setZoom(zoom){this.zoom=zoom;if(this.projectionMode===exports.CameraProjectionMode.ORTHOGRAPHIC){this.setOrthographic(this.left,this.rright,this.top,this.bottom,this.near,this.far);}else if(this.projectionMode===exports.CameraProjectionMode.PERSPECTIVE){this.setPerspective(this.near,this.far,this.fov,this.aspect);}return this;}/**
- * Zoom by specified point in viewport coordinates.
- */;_proto.setZoomByViewportPoint=function setZoomByViewportPoint(zoom,viewportPoint){var _this$canvas$viewport=this.canvas.viewport2Canvas({x:viewportPoint[0],y:viewportPoint[1]}),ox=_this$canvas$viewport.x,oy=_this$canvas$viewport.y;var roll=this.roll;this.rotate(0,0,-roll);this.setPosition(ox,oy);this.setFocalPoint(ox,oy);this.setZoom(zoom);this.rotate(0,0,roll);var _this$canvas$viewport2=this.canvas.viewport2Canvas({x:viewportPoint[0],y:viewportPoint[1]}),cx=_this$canvas$viewport2.x,cy=_this$canvas$viewport2.y;// project to rotated axis
- var dvec=fromValues$2(cx-ox,cy-oy,0);var dx=dot(dvec,this.right)/length(this.right);var dy=dot(dvec,this.up)/length(this.up);this.pan(-dx,-dy);return this;};_proto.setPerspective=function setPerspective(near,far,fov,aspect){var _this$view;this.projectionMode=exports.CameraProjectionMode.PERSPECTIVE;this.fov=fov;this.near=near;this.far=far;this.aspect=aspect;var top=this.near*Math.tan(deg2rad(0.5*this.fov))/this.zoom;var height=2*top;var width=this.aspect*height;var left=-0.5*width;if((_this$view=this.view)===null||_this$view===void 0?void 0:_this$view.enabled){var fullWidth=this.view.fullWidth;var fullHeight=this.view.fullHeight;left+=this.view.offsetX*width/fullWidth;top-=this.view.offsetY*height/fullHeight;width*=this.view.width/fullWidth;height*=this.view.height/fullHeight;}makePerspective(this.projectionMatrix,left,left+width,top,top-height,near,this.far);// flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
- scale(this.projectionMatrix,this.projectionMatrix,fromValues$2(1,-1,1));invert(this.projectionMatrixInverse,this.projectionMatrix);this.triggerUpdate();return this;};_proto.setOrthographic=function setOrthographic(l,r,t,b,near,far){var _this$view2;this.projectionMode=exports.CameraProjectionMode.ORTHOGRAPHIC;this.rright=r;this.left=l;this.top=t;this.bottom=b;this.near=near;this.far=far;var dx=(this.rright-this.left)/(2*this.zoom);var dy=(this.top-this.bottom)/(2*this.zoom);var cx=(this.rright+this.left)/2;var cy=(this.top+this.bottom)/2;var left=cx-dx;var right=cx+dx;var top=cy+dy;var bottom=cy-dy;if((_this$view2=this.view)===null||_this$view2===void 0?void 0:_this$view2.enabled){var scaleW=(this.rright-this.left)/this.view.fullWidth/this.zoom;var scaleH=(this.top-this.bottom)/this.view.fullHeight/this.zoom;left+=scaleW*this.view.offsetX;right=left+scaleW*this.view.width;top-=scaleH*this.view.offsetY;bottom=top-scaleH*this.view.height;}ortho(this.projectionMatrix,left,right,bottom,top,near,far);// flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
- scale(this.projectionMatrix,this.projectionMatrix,fromValues$2(1,-1,1));invert(this.projectionMatrixInverse,this.projectionMatrix);this._getOrthoMatrix();this.triggerUpdate();return this;}/**
- * Move the camera in world coordinates.
- * It will keep looking at the current focal point.
- *
- * support scalars or vectors.
- * @example
- * setPosition(1, 2, 3);
- * setPosition([1, 2, 3]);
- */;_proto.setPosition=function setPosition(x,y,z){if(y===void 0){y=this.position[1];}if(z===void 0){z=this.position[2];}var position=createVec3(x,y,z);this._setPosition(position);this.setFocalPoint(this.focalPoint);this.triggerUpdate();return this;}/**
- * Sets the focal point of this camera in world coordinates.
- *
- * support scalars or vectors.
- * @example
- * setFocalPoint(1, 2, 3);
- * setFocalPoint([1, 2, 3]);
- */;_proto.setFocalPoint=function setFocalPoint(x,y,z){if(y===void 0){y=this.focalPoint[1];}if(z===void 0){z=this.focalPoint[2];}var up=fromValues$2(0,1,0);this.focalPoint=createVec3(x,y,z);if(this.trackingMode===exports.CameraTrackingMode.CINEMATIC){var d=subtract$1(create$2(),this.focalPoint,this.position);x=d[0];y=d[1];z=d[2];var r=length(d);var el=rad2deg(Math.asin(y/r));var az=90+rad2deg(Math.atan2(z,x));var m=create$1();rotateY(m,m,deg2rad(az));rotateX(m,m,deg2rad(el));up=transformMat4(create$2(),[0,1,0],m);}invert(this.matrix,lookAt(create$1(),this.position,this.focalPoint,up));this._getAxes();this._getDistance();this._getAngles();this.triggerUpdate();return this;};_proto.getDistance=function getDistance(){return this.distance;};_proto.getDistanceVector=function getDistanceVector(){return this.distanceVector;}/**
- * Moves the camera towards/from the focal point.
- */;_proto.setDistance=function setDistance(d){if(this.distance===d||d<0){return this;}this.distance=d;if(this.distance<MIN_DISTANCE){this.distance=MIN_DISTANCE;}this.dollyingStep=this.distance/100;var pos=create$2();d=this.distance;var n=this.forward;var f=this.focalPoint;pos[0]=d*n[0]+f[0];pos[1]=d*n[1]+f[1];pos[2]=d*n[2]+f[2];this._setPosition(pos);this.triggerUpdate();return this;};_proto.setMaxDistance=function setMaxDistance(d){this.maxDistance=d;return this;};_proto.setMinDistance=function setMinDistance(d){this.minDistance=d;return this;}/**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- * the azimuth in degrees
- */;_proto.setAzimuth=function setAzimuth(az){this.azimuth=getAngle$1(az);this.computeMatrix();this._getAxes();if(this.type===exports.CameraType.ORBITING||this.type===exports.CameraType.EXPLORING){this._getPosition();}else if(this.type===exports.CameraType.TRACKING){this._getFocalPoint();}this.triggerUpdate();return this;};_proto.getAzimuth=function getAzimuth(){return this.azimuth;}/**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- */;_proto.setElevation=function setElevation(el){this.elevation=getAngle$1(el);this.computeMatrix();this._getAxes();if(this.type===exports.CameraType.ORBITING||this.type===exports.CameraType.EXPLORING){this._getPosition();}else if(this.type===exports.CameraType.TRACKING){this._getFocalPoint();}this.triggerUpdate();return this;};_proto.getElevation=function getElevation(){return this.elevation;}/**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- */;_proto.setRoll=function setRoll(angle){this.roll=getAngle$1(angle);this.computeMatrix();this._getAxes();if(this.type===exports.CameraType.ORBITING||this.type===exports.CameraType.EXPLORING){this._getPosition();}else if(this.type===exports.CameraType.TRACKING){this._getFocalPoint();}this.triggerUpdate();return this;};_proto.getRoll=function getRoll(){return this.roll;}/**
- * 根据相机矩阵重新计算各种相机参数
- */;_proto._update=function _update(){this._getAxes();this._getPosition();this._getDistance();this._getAngles();this._getOrthoMatrix();this.triggerUpdate();}/**
- * 计算相机矩阵
- */;_proto.computeMatrix=function computeMatrix(){// 使用四元数描述 3D 旋转
- // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html
- var rotZ=setAxisAngle(create$4(),[0,0,1],deg2rad(this.roll));identity(this.matrix);// only consider HCS for EXPLORING and ORBITING cameras
- var rotX=setAxisAngle(create$4(),[1,0,0],deg2rad((this.rotateWorld&&this.type!==exports.CameraType.TRACKING||this.type===exports.CameraType.TRACKING?1:-1)*this.elevation));var rotY=setAxisAngle(create$4(),[0,1,0],deg2rad((this.rotateWorld&&this.type!==exports.CameraType.TRACKING||this.type===exports.CameraType.TRACKING?1:-1)*this.azimuth));var rotQ=multiply$2(create$4(),rotY,rotX);rotQ=multiply$2(create$4(),rotQ,rotZ);var rotMatrix=fromQuat(create$1(),rotQ);if(this.type===exports.CameraType.ORBITING||this.type===exports.CameraType.EXPLORING){translate(this.matrix,this.matrix,this.focalPoint);multiply(this.matrix,this.matrix,rotMatrix);translate(this.matrix,this.matrix,[0,0,this.distance]);}else if(this.type===exports.CameraType.TRACKING){translate(this.matrix,this.matrix,this.position);multiply(this.matrix,this.matrix,rotMatrix);}}/**
- * Sets the camera position in the camera matrix
- */;_proto._setPosition=function _setPosition(x,y,z){this.position=createVec3(x,y,z);var m=this.matrix;m[12]=this.position[0];m[13]=this.position[1];m[14]=this.position[2];m[15]=1;this._getOrthoMatrix();}/**
- * Recalculates axes based on the current matrix
- */;_proto._getAxes=function _getAxes(){copy$1(this.right,createVec3(transformMat4$1(create$3(),[1,0,0,0],this.matrix)));copy$1(this.up,createVec3(transformMat4$1(create$3(),[0,1,0,0],this.matrix)));copy$1(this.forward,createVec3(transformMat4$1(create$3(),[0,0,1,0],this.matrix)));normalize(this.right,this.right);normalize(this.up,this.up);normalize(this.forward,this.forward);}/**
- * Recalculates euler angles based on the current state
- */;_proto._getAngles=function _getAngles(){// Recalculates angles
- var x=this.distanceVector[0];var y=this.distanceVector[1];var z=this.distanceVector[2];var r=length(this.distanceVector);// FAST FAIL: If there is no distance we cannot compute angles
- if(r===0){this.elevation=0;this.azimuth=0;return;}if(this.type===exports.CameraType.TRACKING){this.elevation=rad2deg(Math.asin(y/r));this.azimuth=rad2deg(Math.atan2(-x,-z));}else {if(this.rotateWorld){this.elevation=rad2deg(Math.asin(y/r));this.azimuth=rad2deg(Math.atan2(-x,-z));}else {this.elevation=-rad2deg(Math.asin(y/r));this.azimuth=-rad2deg(Math.atan2(-x,-z));}}}/**
- * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化
- */;_proto._getPosition=function _getPosition(){copy$1(this.position,createVec3(transformMat4$1(create$3(),[0,0,0,1],this.matrix)));// 相机位置变化,需要重新计算视距
- this._getDistance();}/**
- * 重新计算视点,只有 TRACKING 模式视点才会发生变化
- */;_proto._getFocalPoint=function _getFocalPoint(){transformMat3(this.distanceVector,[0,0,-this.distance],fromMat4(create(),this.matrix));add$1(this.focalPoint,this.position,this.distanceVector);// 视点变化,需要重新计算视距
- this._getDistance();}/**
- * 重新计算视距
- */;_proto._getDistance=function _getDistance(){this.distanceVector=subtract$1(create$2(),this.focalPoint,this.position);this.distance=length(this.distanceVector);this.dollyingStep=this.distance/100;};_proto._getOrthoMatrix=function _getOrthoMatrix(){if(this.projectionMode!==exports.CameraProjectionMode.ORTHOGRAPHIC){return;}var position=this.position;var rotZ=setAxisAngle(create$4(),[0,0,1],-this.roll*Math.PI/180);fromRotationTranslationScaleOrigin(this.orthoMatrix,rotZ,fromValues$2((this.rright-this.left)/2-position[0],(this.top-this.bottom)/2-position[1],0),fromValues$2(this.zoom,this.zoom,1),position);};_proto.triggerUpdate=function triggerUpdate(){if(this.enableUpdate){// update frustum
- var viewMatrix=this.getViewTransform();var vpMatrix=multiply(create$1(),this.getPerspective(),viewMatrix);this.getFrustum().extractFromVPMatrix(vpMatrix);this.eventEmitter.emit(CameraEvent.UPDATED);}};_proto.rotate=function rotate(azimuth,elevation,roll){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.pan=function pan(tx,ty){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.dolly=function dolly(value){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.createLandmark=function createLandmark(name,params){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.gotoLandmark=function gotoLandmark(name,options){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};_proto.cancelLandmarkAnimation=function cancelLandmarkAnimation(){throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);};return Camera;}();var CircleUpdater=/*#__PURE__*/function(){function CircleUpdater(){}var _proto=CircleUpdater.prototype;_proto.update=function update(parsedStyle,object){var r=parsedStyle.r;var width=r*2;var height=r*2;return {width:width,height:height};};return CircleUpdater;}();var EllipseUpdater=/*#__PURE__*/function(){function EllipseUpdater(){}var _proto=EllipseUpdater.prototype;_proto.update=function update(parsedStyle,object){var rx=parsedStyle.rx,ry=parsedStyle.ry;var width=rx*2;var height=ry*2;return {width:width,height:height};};return EllipseUpdater;}();var LineUpdater=/*#__PURE__*/function(){function LineUpdater(){}var _proto=LineUpdater.prototype;_proto.update=function update(parsedStyle){var x1=parsedStyle.x1,y1=parsedStyle.y1,x2=parsedStyle.x2,y2=parsedStyle.y2;var minX=Math.min(x1,x2);var maxX=Math.max(x1,x2);var minY=Math.min(y1,y2);var maxY=Math.max(y1,y2);var width=maxX-minX;var height=maxY-minY;return {width:width,height:height};};return LineUpdater;}();var PathUpdater=/*#__PURE__*/function(){function PathUpdater(){}var _proto=PathUpdater.prototype;_proto.update=function update(parsedStyle){var path=parsedStyle.path;var _path$rect=path.rect,width=_path$rect.width,height=_path$rect.height;return {width:width,height:height};};return PathUpdater;}();var PolylineUpdater=/*#__PURE__*/function(){function PolylineUpdater(){}var _proto=PolylineUpdater.prototype;_proto.update=function update(parsedStyle){var points=parsedStyle.points.points;// FIXME: account for miter lineJoin
- var minX=Math.min.apply(Math,points.map(function(point){return point[0];}));var maxX=Math.max.apply(Math,points.map(function(point){return point[0];}));var minY=Math.min.apply(Math,points.map(function(point){return point[1];}));var maxY=Math.max.apply(Math,points.map(function(point){return point[1];}));var width=maxX-minX;var height=maxY-minY;return {width:width,height:height};};return PolylineUpdater;}();var RectUpdater=/*#__PURE__*/function(){function RectUpdater(){}var _proto=RectUpdater.prototype;_proto.update=function update(parsedStyle,object){var img=parsedStyle.img,_parsedStyle$width=parsedStyle.width,width=_parsedStyle$width===void 0?0:_parsedStyle$width,_parsedStyle$height=parsedStyle.height,height=_parsedStyle$height===void 0?0:_parsedStyle$height;var contentWidth=width;var contentHeight=height;// resize with HTMLImageElement's size
- if(img&&!isString(img)){if(!contentWidth){contentWidth=img.width;parsedStyle.width=contentWidth;}if(!contentHeight){contentHeight=img.height;parsedStyle.height=contentHeight;}}return {width:contentWidth,height:contentHeight};};return RectUpdater;}();var TextUpdater=/*#__PURE__*/function(){function TextUpdater(globalRuntime){this.globalRuntime=void 0;this.globalRuntime=globalRuntime;}var _proto=TextUpdater.prototype;_proto.isReadyToMeasure=function isReadyToMeasure(parsedStyle,object){var text=parsedStyle.text,textAlign=parsedStyle.textAlign,textBaseline=parsedStyle.textBaseline,fontSize=parsedStyle.fontSize,fontStyle=parsedStyle.fontStyle,fontWeight=parsedStyle.fontWeight,fontVariant=parsedStyle.fontVariant,lineWidth=parsedStyle.lineWidth;return text&&fontSize&&fontStyle&&fontWeight&&fontVariant&&textAlign&&textBaseline&&!isNil(lineWidth);};_proto.update=function update(parsedStyle,object){var _object$ownerDocument,_object$ownerDocument2;var text=parsedStyle.text,textAlign=parsedStyle.textAlign,lineWidth=parsedStyle.lineWidth,textBaseline=parsedStyle.textBaseline,dx=parsedStyle.dx,dy=parsedStyle.dy;var _ref=(object===null||object===void 0?void 0:(_object$ownerDocument=object.ownerDocument)===null||_object$ownerDocument===void 0?void 0:(_object$ownerDocument2=_object$ownerDocument.defaultView)===null||_object$ownerDocument2===void 0?void 0:_object$ownerDocument2.getConfig())||{},offscreenCanvas=_ref.offscreenCanvas;if(!this.isReadyToMeasure(parsedStyle,object)){parsedStyle.metrics={font:'',width:0,height:0,lines:[],lineWidths:[],lineHeight:0,maxLineWidth:0,fontProperties:{ascent:0,descent:0,fontSize:0},lineMetrics:[]};return {width:0,height:0,x:0,y:0,offsetX:0,offsetY:0};}var metrics=this.globalRuntime.textService.measureText(text,parsedStyle,offscreenCanvas);parsedStyle.metrics=metrics;var width=metrics.width,height=metrics.height,lineHeight=metrics.lineHeight,fontProperties=metrics.fontProperties;// anchor is left-top by default
- var halfExtents=[width/2,height/2,0];// default 'left'
- var anchor=[0,1];var lineXOffset=0;if(textAlign==='center'||textAlign==='middle'){lineXOffset=lineWidth/2;anchor=[0.5,1];}else if(textAlign==='right'||textAlign==='end'){lineXOffset=lineWidth;anchor=[1,1];}var lineYOffset=0;if(textBaseline==='middle'){// eslint-disable-next-line prefer-destructuring
- lineYOffset=halfExtents[1];}else if(textBaseline==='top'||textBaseline==='hanging'){lineYOffset=halfExtents[1]*2;}else if(textBaseline==='alphabetic'){// prevent calling getImageData for ascent metrics
- lineYOffset=runtime.enableCSSParsing?lineHeight-fontProperties.ascent:0;}else if(textBaseline==='bottom'||textBaseline==='ideographic'){lineYOffset=0;}// TODO: ideographic & bottom
- if(dx){lineXOffset+=dx;}if(dy){lineYOffset+=dy;}// update anchor
- parsedStyle.anchor=[anchor[0],anchor[1],0];return {width:halfExtents[0]*2,height:halfExtents[1]*2,offsetX:lineXOffset,offsetY:lineYOffset};};return TextUpdater;}();var PROPAGATION_LIMIT=2048;var EventService=/*#__PURE__*/function(){function EventService(globalRuntime,context){var _this=this;this.globalRuntime=void 0;this.context=void 0;this.rootTarget=void 0;this.emitter=new eventemitter3();this.cursor='default';this.mappingTable={};this.mappingState={trackingData:{}};this.eventPool=new Map();this.pickHandler=void 0;this.tmpMatrix=create$1();this.tmpVec3=create$2();this.onPointerDown=function(from){// if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var e=_this.createPointerEvent(from);_this.dispatchEvent(e,'pointerdown');if(e.pointerType==='touch'){_this.dispatchEvent(e,'touchstart');}else if(e.pointerType==='mouse'||e.pointerType==='pen'){var isRightButton=e.button===2;_this.dispatchEvent(e,isRightButton?'rightdown':'mousedown');}var trackingData=_this.trackingData(from.pointerId);trackingData.pressTargetsByButton[from.button]=e.composedPath();_this.freeEvent(e);};this.onPointerUp=function(from){// if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var now=performance.now();var e=_this.createPointerEvent(from,undefined,undefined,_this.context.config.alwaysTriggerPointerEventOnCanvas?_this.rootTarget:undefined);_this.dispatchEvent(e,'pointerup');if(e.pointerType==='touch'){_this.dispatchEvent(e,'touchend');}else if(e.pointerType==='mouse'||e.pointerType==='pen'){var isRightButton=e.button===2;_this.dispatchEvent(e,isRightButton?'rightup':'mouseup');}var trackingData=_this.trackingData(from.pointerId);var pressTarget=_this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);var clickTarget=pressTarget;// pointerupoutside only bubbles. It only bubbles upto the parent that doesn't contain
- // the pointerup location.
- if(pressTarget&&!e.composedPath().includes(pressTarget)){var currentTarget=pressTarget;while(currentTarget&&!e.composedPath().includes(currentTarget)){e.currentTarget=currentTarget;_this.notifyTarget(e,'pointerupoutside');if(e.pointerType==='touch'){_this.notifyTarget(e,'touchendoutside');}else if(e.pointerType==='mouse'||e.pointerType==='pen'){var _isRightButton=e.button===2;_this.notifyTarget(e,_isRightButton?'rightupoutside':'mouseupoutside');}if(Node.isNode(currentTarget)){currentTarget=currentTarget.parentNode;}}delete trackingData.pressTargetsByButton[from.button];// currentTarget is the most specific ancestor holding both the pointerdown and pointerup
- // targets. That is - it's our click target!
- clickTarget=currentTarget;}if(clickTarget){var _e$detail;var clickEvent=_this.clonePointerEvent(e,'click');clickEvent.target=clickTarget;clickEvent.path=[];if(!trackingData.clicksByButton[from.button]){trackingData.clicksByButton[from.button]={clickCount:0,target:clickEvent.target,timeStamp:now};}var clickHistory=trackingData.clicksByButton[from.button];if(clickHistory.target===clickEvent.target&&now-clickHistory.timeStamp<200){++clickHistory.clickCount;}else {clickHistory.clickCount=1;}clickHistory.target=clickEvent.target;clickHistory.timeStamp=now;clickEvent.detail=clickHistory.clickCount;// @see https://github.com/antvis/G/issues/1091
- if(!((_e$detail=e.detail)===null||_e$detail===void 0?void 0:_e$detail.preventClick)){if(!_this.context.config.useNativeClickEvent&&(clickEvent.pointerType==='mouse'||clickEvent.pointerType==='touch')){_this.dispatchEvent(clickEvent,'click');}_this.dispatchEvent(clickEvent,'pointertap');}_this.freeEvent(clickEvent);}_this.freeEvent(e);};this.onPointerMove=function(from){// if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var e=_this.createPointerEvent(from,undefined,undefined,_this.context.config.alwaysTriggerPointerEventOnCanvas?_this.rootTarget:undefined);var isMouse=e.pointerType==='mouse'||e.pointerType==='pen';var trackingData=_this.trackingData(from.pointerId);var outTarget=_this.findMountedTarget(trackingData.overTargets);// First pointerout/pointerleave
- if(trackingData.overTargets&&outTarget!==e.target){// pointerout always occurs on the overTarget when the pointer hovers over another element.
- var outType=from.type==='mousemove'?'mouseout':'pointerout';var outEvent=_this.createPointerEvent(from,outType,outTarget||undefined);_this.dispatchEvent(outEvent,'pointerout');if(isMouse)_this.dispatchEvent(outEvent,'mouseout');// If the pointer exits overTarget and its descendants, then a pointerleave event is also fired. This event
- // is dispatched to all ancestors that no longer capture the pointer.
- if(!e.composedPath().includes(outTarget)){var leaveEvent=_this.createPointerEvent(from,'pointerleave',outTarget||undefined);leaveEvent.eventPhase=leaveEvent.AT_TARGET;while(leaveEvent.target&&!e.composedPath().includes(leaveEvent.target)){leaveEvent.currentTarget=leaveEvent.target;_this.notifyTarget(leaveEvent);if(isMouse){_this.notifyTarget(leaveEvent,'mouseleave');}if(Node.isNode(leaveEvent.target)){leaveEvent.target=leaveEvent.target.parentNode;}}_this.freeEvent(leaveEvent);}_this.freeEvent(outEvent);}// Then pointerover
- if(outTarget!==e.target){// pointerover always occurs on the new overTarget
- var overType=from.type==='mousemove'?'mouseover':'pointerover';var overEvent=_this.clonePointerEvent(e,overType);// clone faster
- _this.dispatchEvent(overEvent,'pointerover');if(isMouse)_this.dispatchEvent(overEvent,'mouseover');// Probe whether the newly hovered Node is an ancestor of the original overTarget.
- var overTargetAncestor=outTarget&&Node.isNode(outTarget)&&outTarget.parentNode;while(overTargetAncestor&&overTargetAncestor!==(Node.isNode(_this.rootTarget)&&_this.rootTarget.parentNode)){if(overTargetAncestor===e.target)break;overTargetAncestor=overTargetAncestor.parentNode;}// The pointer has entered a non-ancestor of the original overTarget. This means we need a pointerentered
- // event.
- var didPointerEnter=!overTargetAncestor||overTargetAncestor===(Node.isNode(_this.rootTarget)&&_this.rootTarget.parentNode);if(didPointerEnter){var enterEvent=_this.clonePointerEvent(e,'pointerenter');enterEvent.eventPhase=enterEvent.AT_TARGET;while(enterEvent.target&&enterEvent.target!==outTarget&&enterEvent.target!==(Node.isNode(_this.rootTarget)&&_this.rootTarget.parentNode)){enterEvent.currentTarget=enterEvent.target;_this.notifyTarget(enterEvent);if(isMouse)_this.notifyTarget(enterEvent,'mouseenter');if(Node.isNode(enterEvent.target)){enterEvent.target=enterEvent.target.parentNode;}}_this.freeEvent(enterEvent);}_this.freeEvent(overEvent);}// Then pointermove
- _this.dispatchEvent(e,'pointermove');if(e.pointerType==='touch')_this.dispatchEvent(e,'touchmove');if(isMouse){_this.dispatchEvent(e,'mousemove');_this.cursor=_this.getCursor(e.target);}trackingData.overTargets=e.composedPath();_this.freeEvent(e);};this.onPointerOut=function(from){// if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData=_this.trackingData(from.pointerId);if(trackingData.overTargets){var isMouse=from.pointerType==='mouse'||from.pointerType==='pen';var outTarget=_this.findMountedTarget(trackingData.overTargets);// pointerout first
- var outEvent=_this.createPointerEvent(from,'pointerout',outTarget||undefined);_this.dispatchEvent(outEvent);if(isMouse)_this.dispatchEvent(outEvent,'mouseout');// pointerleave(s) are also dispatched b/c the pointer must've left rootTarget and its descendants to
- // get an upstream pointerout event (upstream events do not know rootTarget has descendants).
- var leaveEvent=_this.createPointerEvent(from,'pointerleave',outTarget||undefined);leaveEvent.eventPhase=leaveEvent.AT_TARGET;while(leaveEvent.target&&leaveEvent.target!==(Node.isNode(_this.rootTarget)&&_this.rootTarget.parentNode)){leaveEvent.currentTarget=leaveEvent.target;_this.notifyTarget(leaveEvent);if(isMouse){_this.notifyTarget(leaveEvent,'mouseleave');}if(Node.isNode(leaveEvent.target)){leaveEvent.target=leaveEvent.target.parentNode;}}trackingData.overTargets=null;_this.freeEvent(outEvent);_this.freeEvent(leaveEvent);}_this.cursor=null;};this.onPointerOver=function(from){// if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData=_this.trackingData(from.pointerId);var e=_this.createPointerEvent(from);var isMouse=e.pointerType==='mouse'||e.pointerType==='pen';_this.dispatchEvent(e,'pointerover');if(isMouse)_this.dispatchEvent(e,'mouseover');if(e.pointerType==='mouse')_this.cursor=_this.getCursor(e.target);// pointerenter events must be fired since the pointer entered from upstream.
- var enterEvent=_this.clonePointerEvent(e,'pointerenter');enterEvent.eventPhase=enterEvent.AT_TARGET;while(enterEvent.target&&enterEvent.target!==(Node.isNode(_this.rootTarget)&&_this.rootTarget.parentNode)){enterEvent.currentTarget=enterEvent.target;_this.notifyTarget(enterEvent);if(isMouse){// mouseenter should not bubble
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event#usage_notes
- _this.notifyTarget(enterEvent,'mouseenter');}if(Node.isNode(enterEvent.target)){enterEvent.target=enterEvent.target.parentNode;}}trackingData.overTargets=e.composedPath();_this.freeEvent(e);_this.freeEvent(enterEvent);};this.onPointerUpOutside=function(from){// if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData=_this.trackingData(from.pointerId);var pressTarget=_this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);var e=_this.createPointerEvent(from);if(pressTarget){var currentTarget=pressTarget;while(currentTarget){e.currentTarget=currentTarget;_this.notifyTarget(e,'pointerupoutside');if(e.pointerType==='touch');else if(e.pointerType==='mouse'||e.pointerType==='pen'){_this.notifyTarget(e,e.button===2?'rightupoutside':'mouseupoutside');}if(Node.isNode(currentTarget)){currentTarget=currentTarget.parentNode;}}delete trackingData.pressTargetsByButton[from.button];}_this.freeEvent(e);};this.onWheel=function(from){// if (!(from instanceof FederatedWheelEvent)) {
- // return;
- // }
- var wheelEvent=_this.createWheelEvent(from);_this.dispatchEvent(wheelEvent);_this.freeEvent(wheelEvent);};this.onClick=function(from){if(_this.context.config.useNativeClickEvent){var e=_this.createPointerEvent(from);_this.dispatchEvent(e);_this.freeEvent(e);}};this.onPointerCancel=function(from){var e=_this.createPointerEvent(from,undefined,undefined,_this.context.config.alwaysTriggerPointerEventOnCanvas?_this.rootTarget:undefined);_this.dispatchEvent(e);_this.freeEvent(e);};this.globalRuntime=globalRuntime;this.context=context;}var _proto=EventService.prototype;_proto.init=function init(){this.rootTarget=this.context.renderingContext.root.parentNode;// document
- this.addEventMapping('pointerdown',this.onPointerDown);this.addEventMapping('pointerup',this.onPointerUp);this.addEventMapping('pointermove',this.onPointerMove);this.addEventMapping('pointerout',this.onPointerOut);this.addEventMapping('pointerleave',this.onPointerOut);this.addEventMapping('pointercancel',this.onPointerCancel);this.addEventMapping('pointerover',this.onPointerOver);this.addEventMapping('pointerupoutside',this.onPointerUpOutside);this.addEventMapping('wheel',this.onWheel);this.addEventMapping('click',this.onClick);};_proto.destroy=function destroy(){this.emitter.removeAllListeners();this.mappingTable={};this.mappingState={};this.eventPool.clear();};_proto.client2Viewport=function client2Viewport(client){var bbox=this.context.contextService.getBoundingClientRect();return new Point(client.x-((bbox===null||bbox===void 0?void 0:bbox.left)||0),client.y-((bbox===null||bbox===void 0?void 0:bbox.top)||0));};_proto.viewport2Client=function viewport2Client(canvas){var bbox=this.context.contextService.getBoundingClientRect();return new Point(canvas.x+((bbox===null||bbox===void 0?void 0:bbox.left)||0),canvas.y+((bbox===null||bbox===void 0?void 0:bbox.top)||0));};_proto.viewport2Canvas=function viewport2Canvas(_ref){var x=_ref.x,y=_ref.y;var canvas=this.rootTarget.defaultView;var camera=canvas.getCamera();var _this$context$config=this.context.config,width=_this$context$config.width,height=_this$context$config.height;var projectionMatrixInverse=camera.getPerspectiveInverse();var worldMatrix=camera.getWorldTransform();var vpMatrix=multiply(this.tmpMatrix,worldMatrix,projectionMatrixInverse);var viewport=set$1(this.tmpVec3,x/width*2-1,(1-y/height)*2-1,0);transformMat4(viewport,viewport,vpMatrix);return new Point(viewport[0],viewport[1]);};_proto.canvas2Viewport=function canvas2Viewport(canvasP){var canvas=this.rootTarget.defaultView;var camera=canvas.getCamera();// World -> Clip
- var projectionMatrix=camera.getPerspective();var viewMatrix=camera.getViewTransform();var vpMatrix=multiply(this.tmpMatrix,projectionMatrix,viewMatrix);var clip=set$1(this.tmpVec3,canvasP.x,canvasP.y,0);transformMat4(this.tmpVec3,this.tmpVec3,vpMatrix);// Clip -> NDC -> Viewport, flip Y
- var _this$context$config2=this.context.config,width=_this$context$config2.width,height=_this$context$config2.height;return new Point((clip[0]+1)/2*width,(1-(clip[1]+1)/2)*height);};_proto.setPickHandler=function setPickHandler(pickHandler){this.pickHandler=pickHandler;};_proto.addEventMapping=function addEventMapping(type,fn){if(!this.mappingTable[type]){this.mappingTable[type]=[];}this.mappingTable[type].push({fn:fn,priority:0});this.mappingTable[type].sort(function(a,b){return a.priority-b.priority;});};_proto.mapEvent=function mapEvent(e){if(!this.rootTarget){return;}var mappers=this.mappingTable[e.type];if(mappers){for(var i=0,j=mappers.length;i<j;i++){mappers[i].fn(e);}}else {console.warn("[EventService]: Event mapping not defined for "+e.type);}};_proto.dispatchEvent=function dispatchEvent(e,type,skipPropagate){// Canvas should skip
- if(!skipPropagate){e.propagationStopped=false;e.propagationImmediatelyStopped=false;this.propagate(e,type);}else {// target phase
- e.eventPhase=e.AT_TARGET;var canvas=this.rootTarget.defaultView||null;e.currentTarget=canvas;this.notifyListeners(e,type);}this.emitter.emit(type||e.type,e);};_proto.propagate=function propagate(e,type){if(!e.target){return;}// [target, parent, root, Canvas]
- var composedPath=e.composedPath();// event flow: capture -> target -> bubbling
- // capture phase
- e.eventPhase=e.CAPTURING_PHASE;for(var i=composedPath.length-1;i>=1;i--){e.currentTarget=composedPath[i];this.notifyTarget(e,type);if(e.propagationStopped||e.propagationImmediatelyStopped)return;}// target phase
- e.eventPhase=e.AT_TARGET;e.currentTarget=e.target;this.notifyTarget(e,type);if(e.propagationStopped||e.propagationImmediatelyStopped)return;// find current target in composed path
- var index=composedPath.indexOf(e.currentTarget);// bubbling phase
- e.eventPhase=e.BUBBLING_PHASE;for(var _i=index+1;_i<composedPath.length;_i++){e.currentTarget=composedPath[_i];this.notifyTarget(e,type);if(e.propagationStopped||e.propagationImmediatelyStopped)return;}};_proto.propagationPath=function propagationPath(target){var propagationPath=[target];var canvas=this.rootTarget.defaultView||null;if(canvas&&canvas===target){propagationPath.unshift(canvas.document);return propagationPath;}for(var i=0;i<PROPAGATION_LIMIT&&target!==this.rootTarget;i++){// if (Node.isNode(target) && !target.parentNode) {
- // throw new Error('Cannot find propagation path to disconnected target');
- // }
- if(Node.isNode(target)&&target.parentNode){// [target, parent, parent, root]
- propagationPath.push(target.parentNode);target=target.parentNode;}}if(canvas){// @ts-ignore
- propagationPath.push(canvas);}return propagationPath;};_proto.hitTest=function hitTest(position){var viewportX=position.viewportX,viewportY=position.viewportY;var _this$context$config3=this.context.config,width=_this$context$config3.width,height=_this$context$config3.height;// outside canvas
- if(viewportX<0||viewportY<0||viewportX>width||viewportY>height){return null;}return this.pickHandler(position)||this.rootTarget||// return Document
- null;}/**
- * whether the native event trigger came from Canvas,
- * should account for HTML shape
- */;_proto.isNativeEventFromCanvas=function isNativeEventFromCanvas(event){var _event$nativeEvent;var $el=this.context.contextService.getDomElement();var target=(_event$nativeEvent=event.nativeEvent)===null||_event$nativeEvent===void 0?void 0:_event$nativeEvent.target;if(target){// from <canvas>
- if(target===$el){return true;}// from <svg>
- if($el&&$el.contains){return $el.contains(target);}}if(event.nativeEvent.composedPath){return event.nativeEvent.composedPath().indexOf($el)>-1;}// account for Touch
- return false;}/**
- * Find HTML from composed path in native UI event.
- */;_proto.getExistedHTML=function getExistedHTML(event){if(event.nativeEvent.composedPath){for(var _iterator=_createForOfIteratorHelperLoose(event.nativeEvent.composedPath()),_step;!(_step=_iterator()).done;){var eventTarget=_step.value;var existed=runtime.nativeHTMLMap.get(eventTarget);if(existed){return existed;}}}return null;};_proto.pickTarget=function pickTarget(event){return this.hitTest({clientX:event.clientX,clientY:event.clientY,viewportX:event.viewportX,viewportY:event.viewportY,x:event.canvasX,y:event.canvasY});};_proto.createPointerEvent=function createPointerEvent(from,type,target,fallbackTarget){var event=this.allocateEvent(FederatedPointerEvent);this.copyPointerData(from,event);this.copyMouseData(from,event);this.copyData(from,event);event.nativeEvent=from.nativeEvent;event.originalEvent=from;var existedHTML=this.getExistedHTML(event);event.target=target!==null&&target!==void 0?target:existedHTML||this.isNativeEventFromCanvas(event)&&this.pickTarget(event)||fallbackTarget;if(typeof type==='string'){event.type=type;}return event;};_proto.createWheelEvent=function createWheelEvent(from){var event=this.allocateEvent(FederatedWheelEvent);this.copyWheelData(from,event);this.copyMouseData(from,event);this.copyData(from,event);event.nativeEvent=from.nativeEvent;event.originalEvent=from;var existedHTML=this.getExistedHTML(event);event.target=existedHTML||this.isNativeEventFromCanvas(event)&&this.pickTarget(event);return event;};_proto.trackingData=function trackingData(id){if(!this.mappingState.trackingData[id]){this.mappingState.trackingData[id]={pressTargetsByButton:{},clicksByButton:{},overTarget:null};}return this.mappingState.trackingData[id];};_proto.cloneWheelEvent=function cloneWheelEvent(from){var event=this.allocateEvent(FederatedWheelEvent);event.nativeEvent=from.nativeEvent;event.originalEvent=from.originalEvent;this.copyWheelData(from,event);this.copyMouseData(from,event);this.copyData(from,event);event.target=from.target;event.path=from.composedPath().slice();event.type=from.type;return event;};_proto.clonePointerEvent=function clonePointerEvent(from,type){var event=this.allocateEvent(FederatedPointerEvent);event.nativeEvent=from.nativeEvent;event.originalEvent=from.originalEvent;this.copyPointerData(from,event);this.copyMouseData(from,event);this.copyData(from,event);event.target=from.target;event.path=from.composedPath().slice();event.type=type!==null&&type!==void 0?type:event.type;return event;};_proto.copyPointerData=function copyPointerData(from,to){// if (
- // !(
- // from instanceof FederatedPointerEvent &&
- // to instanceof FederatedPointerEvent
- // )
- // )
- // return;
- to.pointerId=from.pointerId;to.width=from.width;to.height=from.height;to.isPrimary=from.isPrimary;to.pointerType=from.pointerType;to.pressure=from.pressure;to.tangentialPressure=from.tangentialPressure;to.tiltX=from.tiltX;to.tiltY=from.tiltY;to.twist=from.twist;};_proto.copyMouseData=function copyMouseData(from,to){// if (
- // !(
- // from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent
- // )
- // )
- // return;
- to.altKey=from.altKey;to.button=from.button;to.buttons=from.buttons;to.ctrlKey=from.ctrlKey;to.metaKey=from.metaKey;to.shiftKey=from.shiftKey;to.client.copyFrom(from.client);to.movement.copyFrom(from.movement);to.canvas.copyFrom(from.canvas);to.screen.copyFrom(from.screen);to.global.copyFrom(from.global);to.offset.copyFrom(from.offset);};_proto.copyWheelData=function copyWheelData(from,to){to.deltaMode=from.deltaMode;to.deltaX=from.deltaX;to.deltaY=from.deltaY;to.deltaZ=from.deltaZ;};_proto.copyData=function copyData(from,to){to.isTrusted=from.isTrusted;to.timeStamp=performance.now();to.type=from.type;to.detail=from.detail;to.view=from.view;to.page.copyFrom(from.page);to.viewport.copyFrom(from.viewport);};_proto.allocateEvent=function allocateEvent(constructor){if(!this.eventPool.has(constructor)){this.eventPool.set(constructor,[]);}// @ts-ignore
- var event=this.eventPool.get(constructor).pop()||new constructor(this);event.eventPhase=event.NONE;event.currentTarget=null;event.path=[];event.target=null;return event;};_proto.freeEvent=function freeEvent(event){if(event.manager!==this)throw new Error('It is illegal to free an event not managed by this EventBoundary!');var constructor=event.constructor;if(!this.eventPool.has(constructor)){this.eventPool.set(constructor,[]);}// @ts-ignore
- this.eventPool.get(constructor).push(event);};_proto.notifyTarget=function notifyTarget(e,type){var _type;type=(_type=type)!==null&&_type!==void 0?_type:e.type;var key=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?type+"capture":type;this.notifyListeners(e,key);if(e.eventPhase===e.AT_TARGET){this.notifyListeners(e,type);}};_proto.notifyListeners=function notifyListeners(e,type){// hack EventEmitter, stops if the `propagationImmediatelyStopped` flag is set
- // @ts-ignore
- var emitter=e.currentTarget.emitter;// @ts-ignore
- var listeners=emitter._events[type];if(!listeners)return;if('fn'in listeners){if(listeners.once){emitter.removeListener(type,listeners.fn,undefined,true);}listeners.fn.call(e.currentTarget||listeners.context,e);// listeners.fn.call(listeners.context, e);
- }else {for(var i=0;i<listeners.length&&!e.propagationImmediatelyStopped;i++){if(listeners[i].once){emitter.removeListener(type,listeners[i].fn,undefined,true);}listeners[i].fn.call(e.currentTarget||listeners[i].context,e);// listeners[i].fn.call(listeners[i].context, e);
- }}}/**
- * some detached nodes may exist in propagation path, need to skip them
- */;_proto.findMountedTarget=function findMountedTarget(propagationPath){if(!propagationPath){return null;}var currentTarget=propagationPath[propagationPath.length-1];for(var i=propagationPath.length-2;i>=0;i--){var target=propagationPath[i];if(target===this.rootTarget||Node.isNode(target)&&target.parentNode===currentTarget){currentTarget=propagationPath[i];}else {break;}}return currentTarget;};_proto.getCursor=function getCursor(target){var tmp=target;while(tmp){var cursor=Element.isElement(tmp)&&tmp.getAttribute('cursor');if(cursor){return cursor;}tmp=Node.isNode(tmp)&&tmp.parentNode;}};return EventService;}();/**
- * used in following scenes:
- * - g `ctx.measureText`
- * - g-plugin-canvas-picker `ctx.isPointInPath`
- * - g-plugin-device-renderer `ctx.createLinearGradient` and generate texture
- *
- * @see https://blog.scottlogic.com/2020/03/19/offscreen-canvas.html
- */var OffscreenCanvasCreator=/*#__PURE__*/function(){function OffscreenCanvasCreator(){this.canvas=void 0;this.context=void 0;}var _proto=OffscreenCanvasCreator.prototype;_proto.getOrCreateCanvas=function getOrCreateCanvas(offscreenCanvas,contextAttributes){if(this.canvas){return this.canvas;}// user-defined offscreen canvas
- if(offscreenCanvas){this.canvas=offscreenCanvas;this.context=this.canvas.getContext('2d',contextAttributes);}else {try{// OffscreenCanvas2D measureText can be up to 40% faster.
- this.canvas=new window.OffscreenCanvas(0,0);this.context=this.canvas.getContext('2d',contextAttributes);if(!this.context||!this.context.measureText){this.canvas=document.createElement('canvas');this.context=this.canvas.getContext('2d');}}catch(ex){this.canvas=document.createElement('canvas');this.context=this.canvas.getContext('2d',contextAttributes);}}this.canvas.width=10;this.canvas.height=10;return this.canvas;};_proto.getOrCreateContext=function getOrCreateContext(offscreenCanvas,contextAttributes){if(this.context){return this.context;}this.getOrCreateCanvas(offscreenCanvas,contextAttributes);return this.context;};return OffscreenCanvasCreator;}();/**
- * why we need re-render
- */(function(RenderReason){RenderReason[RenderReason["CAMERA_CHANGED"]=0]="CAMERA_CHANGED";RenderReason[RenderReason["DISPLAY_OBJECT_CHANGED"]=1]="DISPLAY_OBJECT_CHANGED";RenderReason[RenderReason["NONE"]=2]="NONE";})(exports.RenderReason||(exports.RenderReason={}));/**
- * Use frame renderer implemented by `g-canvas/svg/webgl`, in every frame we do followings:
- * * update & merge dirty rectangles
- * * begin frame
- * * filter by visible
- * * sort by z-index in scene graph
- * * culling with strategies registered in `g-canvas/webgl`
- * * end frame
- */var RenderingService=/*#__PURE__*/function(){function RenderingService(globalRuntime,context){this.globalRuntime=void 0;this.context=void 0;this.inited=false;this.stats={/**
- * total display objects in scenegraph
- */total:0,/**
- * number of display objects need to render in current frame
- */rendered:0};this.zIndexCounter=0;this.hooks={/**
- * called before any frame rendered
- */init:new SyncHook(),initAsync:new AsyncParallelHook(),/**
- * only dirty object which has sth changed will be rendered
- */dirtycheck:new SyncWaterfallHook(),/**
- * do culling
- */cull:new SyncWaterfallHook(),/**
- * called at beginning of each frame, won't get called if nothing to re-render
- */beginFrame:new SyncHook(),/**
- * called before every dirty object get rendered
- */beforeRender:new SyncHook(),/**
- * called when every dirty object rendering even it's culled
- */render:new SyncHook(),/**
- * called after every dirty object get rendered
- */afterRender:new SyncHook(),endFrame:new SyncHook(),destroy:new SyncHook(),/**
- * use async but faster method such as GPU-based picking in `g-plugin-device-renderer`
- */pick:new AsyncSeriesWaterfallHook(),/**
- * Unsafe but sync version of pick.
- */pickSync:new SyncWaterfallHook(),/**
- * used in event system
- */pointerDown:new SyncHook(),pointerUp:new SyncHook(),pointerMove:new SyncHook(),pointerOut:new SyncHook(),pointerOver:new SyncHook(),pointerWheel:new SyncHook(),pointerCancel:new SyncHook(),click:new SyncHook()};this.globalRuntime=globalRuntime;this.context=context;}var _proto=RenderingService.prototype;_proto.init=function init(callback){var _this=this;var context=_extends({},this.globalRuntime,this.context);// register rendering plugins
- this.context.renderingPlugins.forEach(function(plugin){plugin.apply(context,runtime);});this.hooks.init.call();if(this.hooks.initAsync.getCallbacksNum()===0){this.inited=true;callback();}else {this.hooks.initAsync.promise().then(function(){_this.inited=true;callback();});}};_proto.getStats=function getStats(){return this.stats;}/**
- * Meet the following conditions:
- * * disable DirtyRectangleRendering
- * * camera changed
- */;_proto.disableDirtyRectangleRendering=function disableDirtyRectangleRendering(){var renderer=this.context.config.renderer;var _renderer$getConfig=renderer.getConfig(),enableDirtyRectangleRendering=_renderer$getConfig.enableDirtyRectangleRendering;return !enableDirtyRectangleRendering||this.context.renderingContext.renderReasons.has(exports.RenderReason.CAMERA_CHANGED);};_proto.render=function render(canvasConfig,rerenderCallback){var _this2=this;this.stats.total=0;this.stats.rendered=0;this.zIndexCounter=0;var renderingContext=this.context.renderingContext;this.globalRuntime.sceneGraphService.syncHierarchy(renderingContext.root);this.globalRuntime.sceneGraphService.triggerPendingEvents();if(renderingContext.renderReasons.size&&this.inited){this.renderDisplayObject(renderingContext.root,canvasConfig,renderingContext);this.hooks.beginFrame.call();renderingContext.renderListCurrentFrame.forEach(function(object){_this2.hooks.beforeRender.call(object);_this2.hooks.render.call(object);_this2.hooks.afterRender.call(object);});this.hooks.endFrame.call();renderingContext.renderListCurrentFrame=[];renderingContext.renderReasons.clear();rerenderCallback();}// console.log('stats', this.stats);
- };_proto.renderDisplayObject=function renderDisplayObject(displayObject,canvasConfig,renderingContext){var _this3=this;var _canvasConfig$rendere=canvasConfig.renderer.getConfig(),enableDirtyCheck=_canvasConfig$rendere.enableDirtyCheck,enableCulling=_canvasConfig$rendere.enableCulling;// recalc style values
- if(this.globalRuntime.enableCSSParsing){this.globalRuntime.styleValueRegistry.recalc(displayObject);}// TODO: relayout
- // dirtycheck first
- var objectChanged=enableDirtyCheck?this.hooks.dirtycheck.call(displayObject):displayObject;if(objectChanged){var objectToRender=enableCulling?this.hooks.cull.call(objectChanged,this.context.camera):objectChanged;if(objectToRender){this.stats.rendered++;renderingContext.renderListCurrentFrame.push(objectToRender);}}displayObject.renderable.dirty=false;displayObject.sortable.renderOrder=this.zIndexCounter++;this.stats.total++;// sort is very expensive, use cached result if possible
- var sortable=displayObject.sortable;if(sortable.dirty){this.sort(displayObject,sortable);sortable.dirty=false;sortable.dirtyChildren=[];sortable.dirtyReason=undefined;}// recursive rendering its children
- (sortable.sorted||displayObject.childNodes).forEach(function(child){_this3.renderDisplayObject(child,canvasConfig,renderingContext);});};_proto.sort=function sort(displayObject,sortable){if(sortable.sorted&&sortable.dirtyReason!==exports.SortReason.Z_INDEX_CHANGED){// avoid re-sorting the whole children list
- sortable.dirtyChildren.forEach(function(child){var index=displayObject.childNodes.indexOf(child);if(index===-1){// remove from sorted list
- var _index=sortable.sorted.indexOf(child);if(_index>=0){sortable.sorted.splice(_index,1);}}else {if(sortable.sorted.length===0){sortable.sorted.push(child);}else {var _index2=sortedIndex(sortable.sorted,child);sortable.sorted.splice(_index2,0,child);}}});}else {sortable.sorted=displayObject.childNodes.slice().sort(sortByZIndex);}};_proto.destroy=function destroy(){this.inited=false;this.hooks.destroy.call();this.globalRuntime.sceneGraphService.clearPendingEvents();};_proto.dirtify=function dirtify(){// need re-render
- this.context.renderingContext.renderReasons.add(exports.RenderReason.DISPLAY_OBJECT_CHANGED);};return RenderingService;}();var ATTRIBUTE_REGEXP=/\[\s*(.*)=(.*)\s*\]/;/**
- * support the following DOM API:
- * * getElementById
- * * getElementsByClassName
- * * getElementsByName
- * * getElementsByTag
- * * querySelector
- * * querySelectorAll
- */var DefaultSceneGraphSelector=/*#__PURE__*/function(){function DefaultSceneGraphSelector(){}var _proto=DefaultSceneGraphSelector.prototype;_proto.selectOne=function selectOne(query,root){var _this=this;if(query.startsWith('.')){return root.find(function(node){// return !node.shadow && node.id === query.substring(1);
- return ((node===null||node===void 0?void 0:node.classList)||[]).indexOf(_this.getIdOrClassname(query))>-1;});}else if(query.startsWith('#')){// getElementById('id')
- return root.find(function(node){// return !node.shadow && node.id === query.substring(1);
- return node.id===_this.getIdOrClassname(query);});}else if(query.startsWith('[')){var _this$getAttribute=this.getAttribute(query),name=_this$getAttribute.name,value=_this$getAttribute.value;if(name){// getElementByName();
- return root.find(function(node){return root!==node&&(name==='name'?node.name===value:_this.attributeToString(node,name)===value);});}else {return null;}}else {// getElementsByTag('circle');
- return root.find(function(node){return root!==node&&node.nodeName===query;});}};_proto.selectAll=function selectAll(query,root){var _this2=this;// only support `[name="${name}"]` `.className` `#id`
- if(query.startsWith('.')){// getElementsByClassName('className');
- // should not include itself
- return root.findAll(function(node){return root!==node&&((node===null||node===void 0?void 0:node.classList)||[]).indexOf(_this2.getIdOrClassname(query))>-1;});}else if(query.startsWith('#')){return root.findAll(function(node){return root!==node&&node.id===_this2.getIdOrClassname(query);});}else if(query.startsWith('[')){var _this$getAttribute2=this.getAttribute(query),name=_this$getAttribute2.name,value=_this$getAttribute2.value;if(name){// getElementsByName();
- return root.findAll(function(node){return root!==node&&(name==='name'?node.name===value:_this2.attributeToString(node,name)===value);});}else {return [];}}else {// getElementsByTag('circle');
- return root.findAll(function(node){return root!==node&&node.nodeName===query;});}};_proto.is=function is(query,node){// a simple `matches` implementation
- if(query.startsWith('.')){return node.className===this.getIdOrClassname(query);}else if(query.startsWith('#')){return node.id===this.getIdOrClassname(query);}else if(query.startsWith('[')){var _this$getAttribute3=this.getAttribute(query),name=_this$getAttribute3.name,value=_this$getAttribute3.value;return name==='name'?node.name===value:this.attributeToString(node,name)===value;}else {return node.nodeName===query;}};_proto.getIdOrClassname=function getIdOrClassname(query){return query.substring(1);};_proto.getAttribute=function getAttribute(query){var matches=query.match(ATTRIBUTE_REGEXP);var name='';var value='';if(matches&&matches.length>2){name=matches[1].replace(/"/g,'');value=matches[2].replace(/"/g,'');}return {name:name,value:value};};_proto.attributeToString=function attributeToString(node,name){if(!node.getAttribute){return '';}var value=node.getAttribute(name);if(isNil(value)){return '';}if(value.toString){return value.toString();}return '';};return DefaultSceneGraphSelector;}();function markRenderableDirty(e){var renderable=e.renderable;if(renderable){renderable.renderBoundsDirty=true;renderable.boundsDirty=true;}}var reparentEvent=new MutationEvent(exports.ElementEvent.REPARENT,null,'','','',0,'','');/**
- * update transform in scene graph
- *
- * @see https://community.khronos.org/t/scene-graphs/50542/7
- */var DefaultSceneGraphService=/*#__PURE__*/function(){function DefaultSceneGraphService(runtime){var _this=this;this.runtime=void 0;this.pendingEvents=[];this.boundsChangedEvent=new CustomEvent(exports.ElementEvent.BOUNDS_CHANGED);/**
- * rotate in world space
- */this.rotate=function(){var parentInvertRotation=create$4();return function(element,degrees,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof degrees==='number'){degrees=fromValues$2(degrees,y,z);}var transform=element.transformable;if(element.parentNode===null||!element.parentNode.transformable){_this.rotateLocal(element,degrees);}else {var rotation=create$4();fromEuler(rotation,degrees[0],degrees[1],degrees[2]);var rot=_this.getRotation(element);var parentRot=_this.getRotation(element.parentNode);copy$3(parentInvertRotation,parentRot);invert$1(parentInvertRotation,parentInvertRotation);multiply$2(rotation,parentInvertRotation,rotation);multiply$2(transform.localRotation,rotation,rot);normalize$2(transform.localRotation,transform.localRotation);_this.dirtifyLocal(element,transform);}};}();/**
- * rotate in local space
- * @see @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw
- */this.rotateLocal=function(){var rotation=create$4();return function(element,degrees,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof degrees==='number'){degrees=fromValues$2(degrees,y,z);}var transform=element.transformable;fromEuler(rotation,degrees[0],degrees[1],degrees[2]);mul$1(transform.localRotation,transform.localRotation,rotation);_this.dirtifyLocal(element,transform);};}();/**
- * set euler angles(degrees) in world space
- */this.setEulerAngles=function(){var invParentRot=create$4();return function(element,degrees,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof degrees==='number'){degrees=fromValues$2(degrees,y,z);}var transform=element.transformable;if(element.parentNode===null||!element.parentNode.transformable){_this.setLocalEulerAngles(element,degrees);}else {fromEuler(transform.localRotation,degrees[0],degrees[1],degrees[2]);var parentRotation=_this.getRotation(element.parentNode);copy$3(invParentRot,invert$1(create$4(),parentRotation));mul$1(transform.localRotation,transform.localRotation,invParentRot);_this.dirtifyLocal(element,transform);}};}();/**
- * translate in local space
- *
- * @example
- * ```
- * translateLocal(x, y, z)
- * translateLocal(vec3(x, y, z))
- * ```
- */this.translateLocal=function(){return function(element,translation,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof translation==='number'){translation=fromValues$2(translation,y,z);}var transform=element.transformable;if(equals$1(translation,create$2())){return;}transformQuat(translation,translation,transform.localRotation);add$1(transform.localPosition,transform.localPosition,translation);_this.dirtifyLocal(element,transform);};}();/**
- * move to position in world space
- *
- * 对应 g 原版的 move/moveTo
- * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L684-L689
- */this.setPosition=function(){var parentInvertMatrix=create$1();var tmpPosition=create$2();return function(element,position){var transform=element.transformable;tmpPosition[0]=position[0];tmpPosition[1]=position[1];tmpPosition[2]=position[2]||0;if(equals$1(_this.getPosition(element),tmpPosition)){return;}copy$1(transform.position,tmpPosition);if(element.parentNode===null||!element.parentNode.transformable){copy$1(transform.localPosition,tmpPosition);}else {var parentTransform=element.parentNode.transformable;copy(parentInvertMatrix,parentTransform.worldTransform);invert(parentInvertMatrix,parentInvertMatrix);transformMat4(transform.localPosition,tmpPosition,parentInvertMatrix);}_this.dirtifyLocal(element,transform);};}();/**
- * move to position in local space
- */this.setLocalPosition=function(){var tmpPosition=create$2();return function(element,position){var transform=element.transformable;tmpPosition[0]=position[0];tmpPosition[1]=position[1];tmpPosition[2]=position[2]||0;if(equals$1(transform.localPosition,tmpPosition)){return;}copy$1(transform.localPosition,tmpPosition);_this.dirtifyLocal(element,transform);};}();/**
- * translate in world space
- *
- * @example
- * ```
- * translate(x, y, z)
- * translate(vec3(x, y, z))
- * ```
- *
- * 对应 g 原版的 translate 2D
- * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L665-L676
- */this.translate=function(){var zeroVec3=create$2();var tmpVec3=create$2();var tr=create$2();return function(element,translation,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof translation==='number'){translation=set$1(tmpVec3,translation,y,z);}if(equals$1(translation,zeroVec3)){return;}add$1(tr,_this.getPosition(element),translation);_this.setPosition(element,tr);};}();this.setRotation=function(){var parentInvertRotation=create$4();return function(element,rotation,y,z,w){var transform=element.transformable;if(typeof rotation==='number'){rotation=fromValues$4(rotation,y,z,w);}if(element.parentNode===null||!element.parentNode.transformable){_this.setLocalRotation(element,rotation);}else {var parentRot=_this.getRotation(element.parentNode);copy$3(parentInvertRotation,parentRot);invert$1(parentInvertRotation,parentInvertRotation);multiply$2(transform.localRotation,parentInvertRotation,rotation);normalize$2(transform.localRotation,transform.localRotation);_this.dirtifyLocal(element,transform);}};};this.displayObjectDependencyMap=new WeakMap();this.calcLocalTransform=function(){var tmpMat=create$1();var tmpPosition=create$2();var tmpQuat=fromValues$4(0,0,0,1);return function(transform){var hasSkew=transform.localSkew[0]!==0||transform.localSkew[1]!==0;if(hasSkew){fromRotationTranslationScaleOrigin(transform.localTransform,transform.localRotation,transform.localPosition,fromValues$2(1,1,1),transform.origin);// apply skew2D
- if(transform.localSkew[0]!==0||transform.localSkew[1]!==0){var tmpMat4=identity(tmpMat);tmpMat4[4]=Math.tan(transform.localSkew[0]);tmpMat4[1]=Math.tan(transform.localSkew[1]);multiply(transform.localTransform,transform.localTransform,tmpMat4);}var scaling=fromRotationTranslationScaleOrigin(tmpMat,tmpQuat,tmpPosition,transform.localScale,transform.origin);multiply(transform.localTransform,transform.localTransform,scaling);}else {// @see https://github.com/mattdesl/css-mat4/blob/master/index.js
- fromRotationTranslationScaleOrigin(transform.localTransform,transform.localRotation,transform.localPosition,transform.localScale,transform.origin);}};}();this.runtime=runtime;}var _proto=DefaultSceneGraphService.prototype;_proto.matches=function matches(query,root){return this.runtime.sceneGraphSelector.is(query,root);};_proto.querySelector=function querySelector(query,root){return this.runtime.sceneGraphSelector.selectOne(query,root);};_proto.querySelectorAll=function querySelectorAll(query,root){return this.runtime.sceneGraphSelector.selectAll(query,root);// .filter((node) => !node.shadow);
- };_proto.attach=function attach(child,parent,index){var _sortable$sorted,_child$style;var detached=false;if(child.parentNode){detached=child.parentNode!==parent;this.detach(child);}child.parentNode=parent;if(!isNil(index)){child.parentNode.childNodes.splice(index,0,child);}else {child.parentNode.childNodes.push(child);}// parent needs re-sort
- var sortable=parent.sortable;if((sortable===null||sortable===void 0?void 0:(_sortable$sorted=sortable.sorted)===null||_sortable$sorted===void 0?void 0:_sortable$sorted.length)||((_child$style=child.style)===null||_child$style===void 0?void 0:_child$style.zIndex)){if(sortable.dirtyChildren.indexOf(child)===-1){sortable.dirtyChildren.push(child);}// if (sortable) {
- // only child has z-Index
- sortable.dirty=true;sortable.dirtyReason=exports.SortReason.ADDED;}// this.updateGraphDepth(child);
- var transform=child.transformable;if(transform){this.dirtifyWorld(child,transform);}if(transform.frozen){this.unfreezeParentToRoot(child);}if(detached){child.dispatchEvent(reparentEvent);}};_proto.detach=function detach(child){if(child.parentNode){var _sortable$sorted2,_child$style2;var transform=child.transformable;// if (transform) {
- // const worldTransform = this.getWorldTransform(child, transform);
- // mat4.getScaling(transform.localScale, worldTransform);
- // mat4.getTranslation(transform.localPosition, worldTransform);
- // mat4.getRotation(transform.localRotation, worldTransform);
- // transform.localDirtyFlag = true;
- // }
- // parent needs re-sort
- var sortable=child.parentNode.sortable;// if (sortable) {
- if((sortable===null||sortable===void 0?void 0:(_sortable$sorted2=sortable.sorted)===null||_sortable$sorted2===void 0?void 0:_sortable$sorted2.length)||((_child$style2=child.style)===null||_child$style2===void 0?void 0:_child$style2.zIndex)){if(sortable.dirtyChildren.indexOf(child)===-1){sortable.dirtyChildren.push(child);}sortable.dirty=true;sortable.dirtyReason=exports.SortReason.REMOVED;}var index=child.parentNode.childNodes.indexOf(child);if(index>-1){child.parentNode.childNodes.splice(index,1);}if(transform){this.dirtifyWorld(child,transform);}child.parentNode=null;}};_proto.getOrigin=function getOrigin(element){return element.transformable.origin;}/**
- * same as pivot in Pixi.js
- *
- * @see https://stackoverflow.com/questions/40748452/how-to-change-css-transform-origin-but-preserve-transformation
- */;_proto.setOrigin=function setOrigin(element,origin,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof origin==='number'){origin=[origin,y,z];}var transform=element.transformable;if(origin[0]===transform.origin[0]&&origin[1]===transform.origin[1]&&origin[2]===transform.origin[2]){return;}var originVec=transform.origin;// const delta = vec3.subtract(vec3.create(), origin, originVec);
- // vec3.add(transform.localPosition, transform.localPosition, delta);
- // update origin
- originVec[0]=origin[0];originVec[1]=origin[1];originVec[2]=origin[2]||0;this.dirtifyLocal(element,transform);};/**
- * set euler angles(degrees) in local space
- */_proto.setLocalEulerAngles=function setLocalEulerAngles(element,degrees,y,z){if(y===void 0){y=0;}if(z===void 0){z=0;}if(typeof degrees==='number'){degrees=fromValues$2(degrees,y,z);}var transform=element.transformable;fromEuler(transform.localRotation,degrees[0],degrees[1],degrees[2]);this.dirtifyLocal(element,transform);};/**
- * scale in local space
- */_proto.scaleLocal=function scaleLocal(element,scaling){var transform=element.transformable;multiply$1(transform.localScale,transform.localScale,fromValues$2(scaling[0],scaling[1],scaling[2]||1));this.dirtifyLocal(element,transform);};_proto.setLocalScale=function setLocalScale(element,scaling){var transform=element.transformable;var updatedScaling=fromValues$2(scaling[0],scaling[1],scaling[2]||transform.localScale[2]);if(equals$1(updatedScaling,transform.localScale)){return;}copy$1(transform.localScale,updatedScaling);this.dirtifyLocal(element,transform);};_proto.setLocalRotation=function setLocalRotation(element,rotation,y,z,w){if(typeof rotation==='number'){rotation=fromValues$4(rotation,y,z,w);}var transform=element.transformable;copy$3(transform.localRotation,rotation);this.dirtifyLocal(element,transform);};_proto.setLocalSkew=function setLocalSkew(element,skew,y){if(typeof skew==='number'){skew=fromValues$5(skew,y);}var transform=element.transformable;copy$4(transform.localSkew,skew);this.dirtifyLocal(element,transform);};_proto.dirtifyLocal=function dirtifyLocal(element,transform){if(!transform.localDirtyFlag){transform.localDirtyFlag=true;if(!transform.dirtyFlag){this.dirtifyWorld(element,transform);}}};_proto.dirtifyWorld=function dirtifyWorld(element,transform){if(!transform.dirtyFlag){this.unfreezeParentToRoot(element);}this.dirtifyWorldInternal(element,transform);this.dirtifyToRoot(element,true);};_proto.triggerPendingEvents=function triggerPendingEvents(){var _this2=this;var set=new Set();var trigger=function trigger(element,detail){if(element.isConnected&&!set.has(element.entity)){_this2.boundsChangedEvent.detail=detail;_this2.boundsChangedEvent.target=element;if(element.isMutationObserved){element.dispatchEvent(_this2.boundsChangedEvent);}else {element.ownerDocument.defaultView.dispatchEvent(_this2.boundsChangedEvent,true);}set.add(element.entity);}};this.pendingEvents.forEach(function(_ref){var element=_ref[0],detail=_ref[1];if(detail.affectChildren){element.forEach(function(e){trigger(e,detail);});}else {trigger(element,detail);}});this.clearPendingEvents();set.clear();};_proto.clearPendingEvents=function clearPendingEvents(){this.pendingEvents=[];};_proto.dirtifyToRoot=function dirtifyToRoot(element,affectChildren){if(affectChildren===void 0){affectChildren=false;}var p=element;// only need to re-render itself
- if(p.renderable){p.renderable.dirty=true;}while(p){markRenderableDirty(p);p=p.parentNode;}if(affectChildren){element.forEach(function(e){markRenderableDirty(e);});}// inform dependencies
- this.informDependentDisplayObjects(element);// reuse the same custom event
- this.pendingEvents.push([element,{affectChildren:affectChildren}]);};_proto.updateDisplayObjectDependency=function updateDisplayObjectDependency(name,oldPath,newPath,object){// clear ref to old clip path
- if(oldPath&&oldPath!==newPath){var oldDependencyMap=this.displayObjectDependencyMap.get(oldPath);if(oldDependencyMap&&oldDependencyMap[name]){var index=oldDependencyMap[name].indexOf(object);oldDependencyMap[name].splice(index,1);}}if(newPath){var newDependencyMap=this.displayObjectDependencyMap.get(newPath);if(!newDependencyMap){this.displayObjectDependencyMap.set(newPath,{});newDependencyMap=this.displayObjectDependencyMap.get(newPath);}if(!newDependencyMap[name]){newDependencyMap[name]=[];}newDependencyMap[name].push(object);}};_proto.informDependentDisplayObjects=function informDependentDisplayObjects(object){var _this3=this;var dependencyMap=this.displayObjectDependencyMap.get(object);if(dependencyMap){Object.keys(dependencyMap).forEach(function(name){dependencyMap[name].forEach(function(target){_this3.dirtifyToRoot(target,true);target.dispatchEvent(new MutationEvent(exports.ElementEvent.ATTR_MODIFIED,target,_this3,_this3,name,MutationEvent.MODIFICATION,_this3,_this3));if(target.isCustomElement&&target.isConnected){if(target.attributeChangedCallback){target.attributeChangedCallback(name,_this3,_this3);}}});});}};_proto.getPosition=function getPosition(element){var transform=element.transformable;return getTranslation(transform.position,this.getWorldTransform(element,transform));};_proto.getRotation=function getRotation$1(element){var transform=element.transformable;return getRotation(transform.rotation,this.getWorldTransform(element,transform));};_proto.getScale=function getScale(element){var transform=element.transformable;return getScaling(transform.scaling,this.getWorldTransform(element,transform));};_proto.getWorldTransform=function getWorldTransform(element,transform){if(transform===void 0){transform=element.transformable;}if(!transform.localDirtyFlag&&!transform.dirtyFlag){return transform.worldTransform;}if(element.parentNode&&element.parentNode.transformable){this.getWorldTransform(element.parentNode);}this.sync(element,transform);return transform.worldTransform;};_proto.getLocalPosition=function getLocalPosition(element){return element.transformable.localPosition;};_proto.getLocalRotation=function getLocalRotation(element){return element.transformable.localRotation;};_proto.getLocalScale=function getLocalScale(element){return element.transformable.localScale;};_proto.getLocalSkew=function getLocalSkew(element){return element.transformable.localSkew;};_proto.getLocalTransform=function getLocalTransform(element){var transform=element.transformable;if(transform.localDirtyFlag){this.calcLocalTransform(transform);transform.localDirtyFlag=false;}return transform.localTransform;};_proto.setLocalTransform=function setLocalTransform(element,transform){var t=getTranslation(create$2(),transform);var r=getRotation(create$4(),transform);var s=getScaling(create$2(),transform);this.setLocalScale(element,s);this.setLocalPosition(element,t);this.setLocalRotation(element,r);};_proto.resetLocalTransform=function resetLocalTransform(element){this.setLocalScale(element,[1,1,1]);this.setLocalPosition(element,[0,0,0]);this.setLocalEulerAngles(element,[0,0,0]);this.setLocalSkew(element,[0,0]);};_proto.getTransformedGeometryBounds=function getTransformedGeometryBounds(element,render,existedAABB){if(render===void 0){render=false;}var bounds=this.getGeometryBounds(element,render);if(!AABB.isEmpty(bounds)){var aabb=existedAABB||new AABB();aabb.setFromTransformedAABB(bounds,this.getWorldTransform(element));return aabb;}else {return null;}}/**
- * won't account for children
- */;_proto.getGeometryBounds=function getGeometryBounds(element,render){if(render===void 0){render=false;}var geometry=element.geometry;var bounds=render?geometry.renderBounds:geometry.contentBounds||null;// return (bounds && new AABB(bounds.center, bounds.halfExtents)) || new AABB();
- return bounds||new AABB();}/**
- * account for children in world space
- */;_proto.getBounds=function getBounds(element,render){var _this4=this;if(render===void 0){render=false;}var renderable=element.renderable;if(!renderable.boundsDirty&&!render&&renderable.bounds){return renderable.bounds;}if(!renderable.renderBoundsDirty&&render&&renderable.renderBounds){return renderable.renderBounds;}// reuse existed if possible
- var existedAABB=render?renderable.renderBounds:renderable.bounds;// reset with geometry's aabb
- var aabb=this.getTransformedGeometryBounds(element,render,existedAABB);// merge children's aabbs
- var children=element.childNodes;children.forEach(function(child){var childBounds=_this4.getBounds(child,render);if(childBounds){if(!aabb){aabb=existedAABB||new AABB();aabb.update(childBounds.center,childBounds.halfExtents);}else {aabb.add(childBounds);}}});if(render){// FIXME: account for clip path
- var clipped=findClosestClipPathTarget(element);if(clipped){// use bounds under world space
- var clipPathBounds=clipped.parsedStyle.clipPath.getBounds(render);if(!aabb){aabb=clipPathBounds;}else if(clipPathBounds){aabb=clipPathBounds.intersection(aabb);}}}if(!aabb){aabb=new AABB();}if(aabb){if(render){renderable.renderBounds=aabb;}else {renderable.bounds=aabb;}}if(render){renderable.renderBoundsDirty=false;}else {renderable.boundsDirty=false;}return aabb;}/**
- * account for children in local space
- */;_proto.getLocalBounds=function getLocalBounds(element){if(element.parentNode){var parentInvert=create$1();if(element.parentNode.transformable){parentInvert=invert(create$1(),this.getWorldTransform(element.parentNode));}var bounds=this.getBounds(element);if(!AABB.isEmpty(bounds)){var localBounds=new AABB();localBounds.setFromTransformedAABB(bounds,parentInvert);return localBounds;}}return this.getBounds(element);};_proto.getBoundingClientRect=function getBoundingClientRect(element){var _element$ownerDocumen,_element$ownerDocumen2;var aabb;var bounds=this.getGeometryBounds(element);if(!AABB.isEmpty(bounds)){aabb=new AABB();// apply transformation to aabb
- aabb.setFromTransformedAABB(bounds,this.getWorldTransform(element));}// calc context's offset
- var bbox=(_element$ownerDocumen=element.ownerDocument)===null||_element$ownerDocumen===void 0?void 0:(_element$ownerDocumen2=_element$ownerDocumen.defaultView)===null||_element$ownerDocumen2===void 0?void 0:_element$ownerDocumen2.getContextService().getBoundingClientRect();if(aabb){var _aabb$getMin=aabb.getMin(),left=_aabb$getMin[0],top=_aabb$getMin[1];var _aabb$getMax=aabb.getMax(),right=_aabb$getMax[0],bottom=_aabb$getMax[1];return new Rectangle(left+((bbox===null||bbox===void 0?void 0:bbox.left)||0),top+((bbox===null||bbox===void 0?void 0:bbox.top)||0),right-left,bottom-top);}return new Rectangle((bbox===null||bbox===void 0?void 0:bbox.left)||0,(bbox===null||bbox===void 0?void 0:bbox.top)||0,0,0);};_proto.dirtifyWorldInternal=function dirtifyWorldInternal(element,transform){var _this5=this;if(!transform.dirtyFlag){transform.dirtyFlag=true;transform.frozen=false;element.childNodes.forEach(function(child){var childTransform=child.transformable;if(!childTransform.dirtyFlag){_this5.dirtifyWorldInternal(child,childTransform);}});var renderable=element.renderable;if(renderable){renderable.renderBoundsDirty=true;renderable.boundsDirty=true;renderable.dirty=true;}}};_proto.syncHierarchy=function syncHierarchy(element){var transform=element.transformable;if(transform.frozen){return;}transform.frozen=true;if(transform.localDirtyFlag||transform.dirtyFlag){this.sync(element,transform);}var children=element.childNodes;for(var i=0;i<children.length;i++){this.syncHierarchy(children[i]);}};_proto.sync=function sync(element,transform){if(transform.localDirtyFlag){this.calcLocalTransform(transform);transform.localDirtyFlag=false;}if(transform.dirtyFlag){var parent=element.parentNode;var parentTransform=parent&&parent.transformable;if(parent===null||!parentTransform){copy(transform.worldTransform,transform.localTransform);}else {// TODO: should we support scale compensation?
- // @see https://github.com/playcanvas/engine/issues/1077#issuecomment-359765557
- multiply(transform.worldTransform,parentTransform.worldTransform,transform.localTransform);}transform.dirtyFlag=false;}};_proto.unfreezeParentToRoot=function unfreezeParentToRoot(child){var p=child.parentNode;while(p){var transform=p.transformable;if(transform){transform.frozen=false;}p=p.parentNode;}};return DefaultSceneGraphService;}();var TEXT_METRICS={MetricsString:'|ÉqÅ',BaselineSymbol:'M',BaselineMultiplier:1.4,HeightMultiplier:2,Newlines:[0x000a,0x000d// carriage return
- ],BreakingSpaces:[0x0009,0x0020,0x2000,0x2001,0x2002,0x2003,0x2004,0x2005,0x2006,0x2008,0x2009,0x200a,0x205f,0x3000// ideographic space
- ]};var LATIN_REGEX=/[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00f6\u00f8-\u00ff!"#$%&'()*+,-./:;]/;// Line breaking rules in CJK (Kinsoku Shori)
- // Refer from https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
- var regexCannotStartZhCn=/[!%),.:;?\]}¢°·'""†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~]/;var regexCannotEndZhCn=/[$(£¥·'"〈《「『【〔〖〝﹙﹛$(.[{£¥]/;var regexCannotStartZhTw=/[!),.:;?\]}¢·–—'"•"、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、]/;var regexCannotEndZhTw=/[([{£¥'"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏]/;var regexCannotStartJaJp=/[)\]}〕〉》」』】〙〗〟'"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.]/;var regexCannotEndJaJp=/[([{〔〈《「『【〘〖〝'"⦅«—...‥〳〴〵]/;var regexCannotStartKoKr=/[!%),.:;?\]}¢°'"†‡℃〆〈《「『〕!%),.:;?]}]/;var regexCannotEndKoKr=/[$([{£¥'"々〇〉》」〔$([{⦆¥₩#]/;var regexCannotStart=new RegExp(regexCannotStartZhCn.source+"|"+regexCannotStartZhTw.source+"|"+regexCannotStartJaJp.source+"|"+regexCannotStartKoKr.source);var regexCannotEnd=new RegExp(regexCannotEndZhCn.source+"|"+regexCannotEndZhTw.source+"|"+regexCannotEndJaJp.source+"|"+regexCannotEndKoKr.source);/**
- * Borrow from pixi/packages/text/src/TextMetrics.ts
- */var TextService=/*#__PURE__*/function(){function TextService(runtime){var _this=this;this.runtime=void 0;/**
- * font metrics cache
- */this.fontMetricsCache={};this.shouldBreakByKinsokuShorui=function(char,nextChar){if(_this.isBreakingSpace(nextChar))return false;if(char){// Line breaking rules in CJK (Kinsoku Shori)
- if(regexCannotEnd.exec(nextChar)||regexCannotStart.exec(char)){return true;}}return false;};this.trimByKinsokuShorui=function(prev){var next=[].concat(prev);var prevLine=next[next.length-2];if(!prevLine){return prev;}var lastChar=prevLine[prevLine.length-1];next[next.length-2]=prevLine.slice(0,-1);next[next.length-1]=lastChar+next[next.length-1];return next;};this.runtime=runtime;}var _proto=TextService.prototype;/**
- * Calculates the ascent, descent and fontSize of a given font-style.
- */_proto.measureFont=function measureFont(font,offscreenCanvas){// as this method is used for preparing assets, don't recalculate things if we don't need to
- if(this.fontMetricsCache[font]){return this.fontMetricsCache[font];}var properties={ascent:0,descent:0,fontSize:0};var canvas=this.runtime.offscreenCanvas.getOrCreateCanvas(offscreenCanvas);var context=this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas,{willReadFrequently:true});context.font=font;var metricsString=TEXT_METRICS.MetricsString+TEXT_METRICS.BaselineSymbol;var width=Math.ceil(context.measureText(metricsString).width);var baseline=Math.ceil(context.measureText(TEXT_METRICS.BaselineSymbol).width);var height=TEXT_METRICS.HeightMultiplier*baseline;baseline=baseline*TEXT_METRICS.BaselineMultiplier|0;// @ts-ignore
- canvas.width=width;// @ts-ignore
- canvas.height=height;context.fillStyle='#f00';context.fillRect(0,0,width,height);context.font=font;context.textBaseline='alphabetic';context.fillStyle='#000';context.fillText(metricsString,0,baseline);var imagedata=context.getImageData(0,0,width||1,height||1).data;var pixels=imagedata.length;var line=width*4;var i=0;var idx=0;var stop=false;// ascent. scan from top to bottom until we find a non red pixel
- for(i=0;i<baseline;++i){for(var j=0;j<line;j+=4){if(imagedata[idx+j]!==255){stop=true;break;}}if(!stop){idx+=line;}else {break;}}properties.ascent=baseline-i;idx=pixels-line;stop=false;// descent. scan from bottom to top until we find a non red pixel
- for(i=height;i>baseline;--i){for(var _j=0;_j<line;_j+=4){if(imagedata[idx+_j]!==255){stop=true;break;}}if(!stop){idx-=line;}else {break;}}properties.descent=i-baseline;properties.fontSize=properties.ascent+properties.descent;this.fontMetricsCache[font]=properties;return properties;};_proto.measureText=function measureText(text,parsedStyle,offscreenCanvas){var fontSize=parsedStyle.fontSize,wordWrap=parsedStyle.wordWrap,strokeHeight=parsedStyle.lineHeight,lineWidth=parsedStyle.lineWidth,textBaseline=parsedStyle.textBaseline,textAlign=parsedStyle.textAlign,letterSpacing=parsedStyle.letterSpacing,textPath=parsedStyle.textPath,textPathSide=parsedStyle.textPathSide,textPathStartOffset=parsedStyle.textPathStartOffset,_parsedStyle$leading=parsedStyle.leading,leading=_parsedStyle$leading===void 0?0:_parsedStyle$leading;var font=toFontString(parsedStyle);// if (runtime.enableCSSParsing) {
- var fontProperties=this.measureFont(font,offscreenCanvas);// fallback in case UA disallow canvas data extraction
- // (toDataURI, getImageData functions)
- if(fontProperties.fontSize===0){fontProperties.fontSize=fontSize;fontProperties.ascent=fontSize;}// } else {
- // fontProperties = {
- // fontSize,
- // };
- // }
- var context=this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);context.font=font;// no overflowing by default
- parsedStyle.isOverflowing=false;var outputText=wordWrap?this.wordWrap(text,parsedStyle,offscreenCanvas):text;var lines=outputText.split(/(?:\r\n|\r|\n)/);var lineWidths=new Array(lines.length);var maxLineWidth=0;// account for textPath
- if(textPath){var totalPathLength=textPath.getTotalLength();// const startingPoint = textPath.getPoint(0);
- for(var i=0;i<lines.length;i++){var width=context.measureText(lines[i]).width+(lines[i].length-1)*letterSpacing;// for (
- // let i = reverse ? lines[0].length - 1 : 0;
- // reverse ? i >= 0 : i < lines[0].length;
- // reverse ? i-- : i++
- // ) {
- // graphemeInfo = lineBounds[i];
- // if (positionInPath > totalPathLength) {
- // positionInPath %= totalPathLength;
- // } else if (positionInPath < 0) {
- // positionInPath += totalPathLength;
- // }
- // // it would probably much faster to send all the grapheme position for a line
- // // and calculate path position/angle at once.
- // this.setGraphemeOnPath(
- // positionInPath,
- // graphemeInfo,
- // startingPoint
- // );
- // positionInPath += graphemeInfo.kernedWidth;
- // }
- }}else {for(var _i=0;_i<lines.length;_i++){// char width + letterSpacing
- var _lineWidth=context.measureText(lines[_i]).width+(lines[_i].length-1)*letterSpacing;lineWidths[_i]=_lineWidth;maxLineWidth=Math.max(maxLineWidth,_lineWidth);}var _width=maxLineWidth+lineWidth;// if (dropShadow) {
- // width += dropShadowDistance;
- // }
- var lineHeight=strokeHeight||fontProperties.fontSize+lineWidth;var height=Math.max(lineHeight,fontProperties.fontSize+lineWidth)+(lines.length-1)*(lineHeight+leading);// if (dropShadow) {
- // height += dropShadowDistance;
- // }
- lineHeight+=leading;// handle vertical text baseline
- var offsetY=0;if(textBaseline==='middle'){offsetY=-height/2;}else if(textBaseline==='bottom'||textBaseline==='alphabetic'||textBaseline==='ideographic'){offsetY=-height;}else if(textBaseline==='top'||textBaseline==='hanging'){offsetY=0;}return {font:font,width:_width,height:height,lines:lines,lineWidths:lineWidths,lineHeight:lineHeight,maxLineWidth:maxLineWidth,fontProperties:fontProperties,lineMetrics:lineWidths.map(function(width,i){var offsetX=0;// handle horizontal text align
- if(textAlign==='center'||textAlign==='middle'){offsetX-=width/2;}else if(textAlign==='right'||textAlign==='end'){offsetX-=width;}return new Rectangle(offsetX-lineWidth/2,offsetY+i*lineHeight,width+lineWidth,lineHeight);})};}};_proto.setGraphemeOnPath=function setGraphemeOnPath(){};_proto.wordWrap=function wordWrap(text,parsedStyle,offscreenCanvas){var _this2=this;var _parsedStyle$wordWrap=parsedStyle.wordWrapWidth,wordWrapWidth=_parsedStyle$wordWrap===void 0?0:_parsedStyle$wordWrap,letterSpacing=parsedStyle.letterSpacing,_parsedStyle$maxLines=parsedStyle.maxLines,maxLines=_parsedStyle$maxLines===void 0?Infinity:_parsedStyle$maxLines,textOverflow=parsedStyle.textOverflow;var context=this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);var maxWidth=wordWrapWidth+letterSpacing;var ellipsis='';if(textOverflow==='ellipsis'){ellipsis='...';}else if(textOverflow&&textOverflow!=='clip'){ellipsis=textOverflow;}var lines=[];var currentIndex=0;var currentWidth=0;var cache={};var calcWidth=function calcWidth(char){return _this2.getFromCache(char,letterSpacing,cache,context);};var ellipsisWidth=Array.from(ellipsis).reduce(function(prev,cur){return prev+calcWidth(cur);},0);var chars=Array.from(text);for(var i=0;i<chars.length;i++){var char=chars[i];var prevChar=text[i-1];var nextChar=text[i+1];var charWidth=calcWidth(char);if(this.isNewline(char)){currentIndex++;// exceed maxLines, break immediately
- if(currentIndex>=maxLines){parsedStyle.isOverflowing=true;break;}currentWidth=0;lines[currentIndex]='';continue;}if(currentWidth>0&¤tWidth+charWidth>maxWidth){if(currentIndex+1>=maxLines){parsedStyle.isOverflowing=true;// If there is not enough space to display the string itself, it is clipped.
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#values
- if(ellipsisWidth>0&&ellipsisWidth<=maxWidth){// Backspace from line's end.
- var currentLineLength=lines[currentIndex].length;var lastLineWidth=0;var lastLineIndex=currentLineLength;for(var _i2=0;_i2<currentLineLength;_i2++){var width=calcWidth(lines[currentIndex][_i2]);if(lastLineWidth+width+ellipsisWidth>maxWidth){lastLineIndex=_i2;break;}lastLineWidth+=width;}lines[currentIndex]=(lines[currentIndex]||'').slice(0,lastLineIndex)+ellipsis;}break;}currentIndex++;currentWidth=0;lines[currentIndex]='';if(this.isBreakingSpace(char)){continue;}if(!this.canBreakInLastChar(char)){lines=this.trimToBreakable(lines);currentWidth=this.sumTextWidthByCache(lines[currentIndex]||'',cache);}if(this.shouldBreakByKinsokuShorui(char,nextChar)){lines=this.trimByKinsokuShorui(lines);currentWidth+=calcWidth(prevChar||'');}}currentWidth+=charWidth;lines[currentIndex]=(lines[currentIndex]||'')+char;}return lines.join('\n');};_proto.isBreakingSpace=function isBreakingSpace(char){if(typeof char!=='string'){return false;}return TEXT_METRICS.BreakingSpaces.indexOf(char.charCodeAt(0))>=0;};_proto.isNewline=function isNewline(char){if(typeof char!=='string'){return false;}return TEXT_METRICS.Newlines.indexOf(char.charCodeAt(0))>=0;};_proto.trimToBreakable=function trimToBreakable(prev){var next=[].concat(prev);var prevLine=next[next.length-2];var index=this.findBreakableIndex(prevLine);if(index===-1||!prevLine)return next;var trimmedChar=prevLine.slice(index,index+1);var isTrimmedWithSpace=this.isBreakingSpace(trimmedChar);var trimFrom=index+1;var trimTo=index+(isTrimmedWithSpace?0:1);next[next.length-1]+=prevLine.slice(trimFrom,prevLine.length);next[next.length-2]=prevLine.slice(0,trimTo);return next;};_proto.canBreakInLastChar=function canBreakInLastChar(char){if(char&&LATIN_REGEX.test(char))return false;return true;};_proto.sumTextWidthByCache=function sumTextWidthByCache(text,cache){return text.split('').reduce(function(sum,c){if(!cache[c])throw Error('cannot count the word without cache');return sum+cache[c];},0);};_proto.findBreakableIndex=function findBreakableIndex(line){for(var i=line.length-1;i>=0;i--){if(!LATIN_REGEX.test(line[i]))return i;}return -1;};_proto.getFromCache=function getFromCache(key,letterSpacing,cache,context){var width=cache[key];if(typeof width!=='number'){var spacing=key.length*letterSpacing;width=context.measureText(key).width+spacing;cache[key]=width;}return width;};return TextService;}();var runtime={};/**
- * Replace with IoC container
- */var geometryUpdaterFactory=function(){var _ref;var rectUpdater=new RectUpdater();var polylineUpdater=new PolylineUpdater();return _ref={},_ref[exports.Shape.CIRCLE]=new CircleUpdater(),_ref[exports.Shape.ELLIPSE]=new EllipseUpdater(),_ref[exports.Shape.RECT]=rectUpdater,_ref[exports.Shape.IMAGE]=rectUpdater,_ref[exports.Shape.GROUP]=rectUpdater,_ref[exports.Shape.LINE]=new LineUpdater(),_ref[exports.Shape.TEXT]=new TextUpdater(runtime),_ref[exports.Shape.POLYLINE]=polylineUpdater,_ref[exports.Shape.POLYGON]=polylineUpdater,_ref[exports.Shape.PATH]=new PathUpdater(),_ref[exports.Shape.HTML]=null,_ref[exports.Shape.MESH]=null,_ref;}();var CSSPropertySyntaxFactory=function(){var _ref2;var color=new CSSPropertyColor();var length=new CSSPropertyLengthOrPercentage();return _ref2={},_ref2[exports.PropertySyntax.PERCENTAGE]=null,_ref2[exports.PropertySyntax.NUMBER]=new CSSPropertyNumber(),_ref2[exports.PropertySyntax.ANGLE]=new CSSPropertyAngle(),_ref2[exports.PropertySyntax.DEFINED_PATH]=new CSSPropertyClipPath(),_ref2[exports.PropertySyntax.PAINT]=color,_ref2[exports.PropertySyntax.COLOR]=color,_ref2[exports.PropertySyntax.FILTER]=new CSSPropertyFilter(),_ref2[exports.PropertySyntax.LENGTH]=length,_ref2[exports.PropertySyntax.LENGTH_PERCENTAGE]=length,_ref2[exports.PropertySyntax.LENGTH_PERCENTAGE_12]=new CSSPropertyLengthOrPercentage12(),_ref2[exports.PropertySyntax.LENGTH_PERCENTAGE_14]=new CSSPropertyLengthOrPercentage14(),_ref2[exports.PropertySyntax.COORDINATE]=new CSSPropertyLocalPosition(),_ref2[exports.PropertySyntax.OFFSET_DISTANCE]=new CSSPropertyOffsetDistance(),_ref2[exports.PropertySyntax.OPACITY_VALUE]=new CSSPropertyOpacity(),_ref2[exports.PropertySyntax.PATH]=new CSSPropertyPath(),_ref2[exports.PropertySyntax.LIST_OF_POINTS]=new CSSPropertyPoints(),_ref2[exports.PropertySyntax.SHADOW_BLUR]=new CSSPropertyShadowBlur(),_ref2[exports.PropertySyntax.TEXT]=new CSSPropertyText(),_ref2[exports.PropertySyntax.TEXT_TRANSFORM]=new CSSPropertyTextTransform(),_ref2[exports.PropertySyntax.TRANSFORM]=new CSSPropertyTransform(),_ref2[exports.PropertySyntax.TRANSFORM_ORIGIN]=new CSSPropertyTransformOrigin(),_ref2[exports.PropertySyntax.Z_INDEX]=new CSSPropertyZIndex(),_ref2[exports.PropertySyntax.MARKER]=new CSSPropertyMarker(),_ref2;}();var getGlobalThis=function getGlobalThis(){if(typeof globalThis!=='undefined')return globalThis;if(typeof self!=='undefined')return self;if(typeof window!=='undefined')return window;// @ts-ignore
- if(typeof global!=='undefined')return global;throw new Error('Unable to locate global `this`');};/**
- * Camera
- * `g-camera-api` will provide an advanced implementation
- */runtime.CameraContribution=Camera;/**
- * `g-web-animations-api` will provide an AnimationTimeline
- */runtime.AnimationTimeline=null;runtime.EasingFunction=null;runtime.offscreenCanvas=new OffscreenCanvasCreator();runtime.nativeHTMLMap=new WeakMap();runtime.sceneGraphSelector=new DefaultSceneGraphSelector();runtime.sceneGraphService=new DefaultSceneGraphService(runtime);runtime.textService=new TextService(runtime);runtime.geometryUpdaterFactory=geometryUpdaterFactory;runtime.CSSPropertySyntaxFactory=CSSPropertySyntaxFactory;runtime.styleValueRegistry=new DefaultStyleValueRegistry();runtime.layoutRegistry=null;runtime.globalThis=getGlobalThis();runtime.enableCSSParsing=true;runtime.enableDataset=false;runtime.enableStyleSyntax=true;var AbstractRendererPlugin=/*#__PURE__*/function(){function AbstractRendererPlugin(){this.context=void 0;this.plugins=[];}var _proto=AbstractRendererPlugin.prototype;_proto.addRenderingPlugin=function addRenderingPlugin(plugin){this.plugins.push(plugin);this.context.renderingPlugins.push(plugin);};_proto.removeAllRenderingPlugins=function removeAllRenderingPlugins(){var _this=this;this.plugins.forEach(function(plugin){var index=_this.context.renderingPlugins.indexOf(plugin);if(index>=0){_this.context.renderingPlugins.splice(index,1);}});};return AbstractRendererPlugin;}();var AbstractRenderer=/*#__PURE__*/function(){function AbstractRenderer(config){this.plugins=[];this.config=void 0;this.config=_extends({/**
- * only dirty object will cause re-render
- */enableDirtyCheck:true,enableCulling:false,/**
- * enable auto rendering by default
- */enableAutoRendering:true,/**
- * enable dirty rectangle rendering by default
- */enableDirtyRectangleRendering:true,enableDirtyRectangleRenderingDebug:false},config);}var _proto2=AbstractRenderer.prototype;_proto2.registerPlugin=function registerPlugin(plugin){var index=this.plugins.findIndex(function(p){return p===plugin;});if(index===-1){this.plugins.push(plugin);}};_proto2.unregisterPlugin=function unregisterPlugin(plugin){var index=this.plugins.findIndex(function(p){return p===plugin;});if(index>-1){this.plugins.splice(index,1);}};_proto2.getPlugins=function getPlugins(){return this.plugins;};_proto2.getPlugin=function getPlugin(name){return this.plugins.find(function(plugin){return plugin.name===name;});};_proto2.getConfig=function getConfig(){return this.config;};_proto2.setConfig=function setConfig(config){Object.assign(this.config,config);};return AbstractRenderer;}();/**
- * apply following rules:
- * 1. `visibility` in scenegraph node
- * 2. other custom culling strategies, eg. frustum culling
- */var CullingPlugin=/*#__PURE__*/function(){function CullingPlugin(strategies){this.strategies=void 0;this.strategies=strategies;}var _proto=CullingPlugin.prototype;_proto.apply=function apply(context){var camera=context.camera,renderingService=context.renderingService,renderingContext=context.renderingContext;var strategies=this.strategies;renderingService.hooks.cull.tap(CullingPlugin.tag,function(object){if(object){var cullable=object.cullable;// cullable.visible = true;
- // const renderBounds = object.getRenderBounds();
- // if (AABB.isEmpty(renderBounds)) {
- // cullable.visible = false;
- // } else {
- // const isShape2D = shape2D.indexOf(object.nodeName as Shape) > -1;
- // const [p0, p1, p2, p3] = camera.getFrustum().planes;
- // tmpAABB.setMinMax([-p1.distance, -p3.distance, 0], [p0.distance, p2.distance, 0]);
- // cullable.visible = isShape2D ? renderBounds.intersects(tmpAABB) : true;
- // }
- if(strategies.length===0){cullable.visible=renderingContext.unculledEntities.indexOf(object.entity)>-1;}else {// eg. implemented by g-webgl(frustum culling)
- cullable.visible=strategies.every(function(strategy){return strategy.isVisible(camera,object);});}if(!object.isCulled()&&object.isVisible()){return object;}else {// if (this.renderingContext.renderListLastFrame.indexOf(object) > -1) {
- object.dispatchEvent(new CustomEvent(exports.ElementEvent.CULLED));// }
- }return null;}return object;});renderingService.hooks.afterRender.tap(CullingPlugin.tag,function(object){object.cullable.visibilityPlaneMask=-1;});};return CullingPlugin;}();CullingPlugin.tag='Culling';/**
- * Filter dirty renderables and calculate the "dirty rectangle" which will be clear when frame began
- */var DirtyCheckPlugin=/*#__PURE__*/function(){function DirtyCheckPlugin(){}var _proto=DirtyCheckPlugin.prototype;_proto.apply=function apply(context){var renderingService=context.renderingService;renderingService.hooks.dirtycheck.tap(DirtyCheckPlugin.tag,function(object){if(object){var renderable=object.renderable;var isDirty=renderable.dirty||renderingService.disableDirtyRectangleRendering();if(isDirty){return object;}else {return null;}}return object;});};return DirtyCheckPlugin;}();DirtyCheckPlugin.tag='DirtyCheck';/**
- * support mouse & touch events
- * @see https://github.com/pixijs/pixi.js/blob/dev/packages/interaction/README.md
- *
- * also provide some extra events such as `drag`
- */var EventPlugin=/*#__PURE__*/function(){function EventPlugin(){var _this=this;this.autoPreventDefault=false;this.rootPointerEvent=new FederatedPointerEvent(null);this.rootWheelEvent=new FederatedWheelEvent(null);this.context=void 0;this.onPointerMove=function(nativeEvent){var _this$context$renderi,_this$context$renderi2;var canvas=(_this$context$renderi=_this.context.renderingContext.root)===null||_this$context$renderi===void 0?void 0:(_this$context$renderi2=_this$context$renderi.ownerDocument)===null||_this$context$renderi2===void 0?void 0:_this$context$renderi2.defaultView;if(canvas.supportsTouchEvents&&nativeEvent.pointerType==='touch')return;var normalizedEvents=_this.normalizeToPointerEvent(nativeEvent,canvas);for(var _iterator=_createForOfIteratorHelperLoose(normalizedEvents),_step;!(_step=_iterator()).done;){var normalizedEvent=_step.value;var event=_this.bootstrapEvent(_this.rootPointerEvent,normalizedEvent,canvas,nativeEvent);_this.context.eventService.mapEvent(event);}_this.setCursor(_this.context.eventService.cursor);};this.onClick=function(nativeEvent){var _this$context$renderi3,_this$context$renderi4;var canvas=(_this$context$renderi3=_this.context.renderingContext.root)===null||_this$context$renderi3===void 0?void 0:(_this$context$renderi4=_this$context$renderi3.ownerDocument)===null||_this$context$renderi4===void 0?void 0:_this$context$renderi4.defaultView;var normalizedEvents=_this.normalizeToPointerEvent(nativeEvent,canvas);for(var _iterator2=_createForOfIteratorHelperLoose(normalizedEvents),_step2;!(_step2=_iterator2()).done;){var normalizedEvent=_step2.value;var event=_this.bootstrapEvent(_this.rootPointerEvent,normalizedEvent,canvas,nativeEvent);_this.context.eventService.mapEvent(event);}_this.setCursor(_this.context.eventService.cursor);};}var _proto=EventPlugin.prototype;_proto.apply=function apply(context){var _this2=this;this.context=context;var renderingService=context.renderingService;var canvas=this.context.renderingContext.root.ownerDocument.defaultView;this.context.eventService.setPickHandler(function(position){var _this2$context$render=_this2.context.renderingService.hooks.pickSync.call({position:position,picked:[],topmost:true// we only concern the topmost element
- }),picked=_this2$context$render.picked;return picked[0]||null;});renderingService.hooks.pointerWheel.tap(EventPlugin.tag,function(nativeEvent){var wheelEvent=_this2.normalizeWheelEvent(nativeEvent);_this2.context.eventService.mapEvent(wheelEvent);});renderingService.hooks.pointerDown.tap(EventPlugin.tag,function(nativeEvent){if(canvas.supportsTouchEvents&&nativeEvent.pointerType==='touch')return;var events=_this2.normalizeToPointerEvent(nativeEvent,canvas);if(_this2.autoPreventDefault&&events[0].isNormalized){var cancelable=nativeEvent.cancelable||!('cancelable'in nativeEvent);if(cancelable){nativeEvent.preventDefault();}}for(var _iterator3=_createForOfIteratorHelperLoose(events),_step3;!(_step3=_iterator3()).done;){var event=_step3.value;var federatedEvent=_this2.bootstrapEvent(_this2.rootPointerEvent,event,canvas,nativeEvent);_this2.context.eventService.mapEvent(federatedEvent);}_this2.setCursor(_this2.context.eventService.cursor);});renderingService.hooks.pointerUp.tap(EventPlugin.tag,function(nativeEvent){if(canvas.supportsTouchEvents&&nativeEvent.pointerType==='touch')return;// account for element in SVG
- var $element=_this2.context.contextService.getDomElement();var outside='outside';try{outside=$element&&nativeEvent.target&&nativeEvent.target!==$element&&$element.contains&&!$element.contains(nativeEvent.target)?'outside':'';}catch(e){// nativeEvent.target maybe not Node, such as Window
- // @see https://github.com/antvis/G/issues/1235
- }var normalizedEvents=_this2.normalizeToPointerEvent(nativeEvent,canvas);for(var _iterator4=_createForOfIteratorHelperLoose(normalizedEvents),_step4;!(_step4=_iterator4()).done;){var normalizedEvent=_step4.value;var event=_this2.bootstrapEvent(_this2.rootPointerEvent,normalizedEvent,canvas,nativeEvent);event.type+=outside;_this2.context.eventService.mapEvent(event);}_this2.setCursor(_this2.context.eventService.cursor);});renderingService.hooks.pointerMove.tap(EventPlugin.tag,this.onPointerMove);renderingService.hooks.pointerOver.tap(EventPlugin.tag,this.onPointerMove);renderingService.hooks.pointerOut.tap(EventPlugin.tag,this.onPointerMove);renderingService.hooks.click.tap(EventPlugin.tag,this.onClick);renderingService.hooks.pointerCancel.tap(EventPlugin.tag,function(nativeEvent){var normalizedEvents=_this2.normalizeToPointerEvent(nativeEvent,canvas);for(var _iterator5=_createForOfIteratorHelperLoose(normalizedEvents),_step5;!(_step5=_iterator5()).done;){var normalizedEvent=_step5.value;var event=_this2.bootstrapEvent(_this2.rootPointerEvent,normalizedEvent,canvas,nativeEvent);_this2.context.eventService.mapEvent(event);}_this2.setCursor(_this2.context.eventService.cursor);});};_proto.getViewportXY=function getViewportXY(nativeEvent){var x;var y;/**
- * Should account for CSS Transform applied on container.
- * @see https://github.com/antvis/G/issues/1161
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/offsetX
- */var offsetX=nativeEvent.offsetX,offsetY=nativeEvent.offsetY,clientX=nativeEvent.clientX,clientY=nativeEvent.clientY;if(this.context.config.supportsCSSTransform&&!isNil(offsetX)&&!isNil(offsetY)){x=offsetX;y=offsetY;}else {var point=this.context.eventService.client2Viewport(new Point(clientX,clientY));x=point.x;y=point.y;}return {x:x,y:y};};_proto.bootstrapEvent=function bootstrapEvent(event,normalizedEvent,view,nativeEvent){event.view=view;event.originalEvent=null;event.nativeEvent=nativeEvent;event.pointerId=normalizedEvent.pointerId;event.width=normalizedEvent.width;event.height=normalizedEvent.height;event.isPrimary=normalizedEvent.isPrimary;event.pointerType=normalizedEvent.pointerType;event.pressure=normalizedEvent.pressure;event.tangentialPressure=normalizedEvent.tangentialPressure;event.tiltX=normalizedEvent.tiltX;event.tiltY=normalizedEvent.tiltY;event.twist=normalizedEvent.twist;this.transferMouseData(event,normalizedEvent);var _this$getViewportXY=this.getViewportXY(normalizedEvent),x=_this$getViewportXY.x,y=_this$getViewportXY.y;event.viewport.x=x;event.viewport.y=y;var _this$context$eventSe=this.context.eventService.viewport2Canvas(event.viewport),canvasX=_this$context$eventSe.x,canvasY=_this$context$eventSe.y;event.canvas.x=canvasX;event.canvas.y=canvasY;event.global.copyFrom(event.canvas);event.offset.copyFrom(event.canvas);event.isTrusted=nativeEvent.isTrusted;if(event.type==='pointerleave'){event.type='pointerout';}if(event.type.startsWith('mouse')){event.type=event.type.replace('mouse','pointer');}if(event.type.startsWith('touch')){event.type=TOUCH_TO_POINTER[event.type]||event.type;}return event;};_proto.normalizeWheelEvent=function normalizeWheelEvent(nativeEvent){var event=this.rootWheelEvent;this.transferMouseData(event,nativeEvent);event.deltaMode=nativeEvent.deltaMode;event.deltaX=nativeEvent.deltaX;event.deltaY=nativeEvent.deltaY;event.deltaZ=nativeEvent.deltaZ;var _this$getViewportXY2=this.getViewportXY(nativeEvent),x=_this$getViewportXY2.x,y=_this$getViewportXY2.y;event.viewport.x=x;event.viewport.y=y;var _this$context$eventSe2=this.context.eventService.viewport2Canvas(event.viewport),canvasX=_this$context$eventSe2.x,canvasY=_this$context$eventSe2.y;event.canvas.x=canvasX;event.canvas.y=canvasY;event.global.copyFrom(event.canvas);event.offset.copyFrom(event.canvas);event.nativeEvent=nativeEvent;event.type=nativeEvent.type;return event;}/**
- * Transfers base & mouse event data from the nativeEvent to the federated event.
- */;_proto.transferMouseData=function transferMouseData(event,nativeEvent){event.isTrusted=nativeEvent.isTrusted;event.srcElement=nativeEvent.srcElement;event.timeStamp=performance.now();event.type=nativeEvent.type;event.altKey=nativeEvent.altKey;event.metaKey=nativeEvent.metaKey;event.shiftKey=nativeEvent.shiftKey;event.ctrlKey=nativeEvent.ctrlKey;event.button=nativeEvent.button;event.buttons=nativeEvent.buttons;event.client.x=nativeEvent.clientX;event.client.y=nativeEvent.clientY;event.movement.x=nativeEvent.movementX;event.movement.y=nativeEvent.movementY;event.page.x=nativeEvent.pageX;event.page.y=nativeEvent.pageY;event.screen.x=nativeEvent.screenX;event.screen.y=nativeEvent.screenY;event.relatedTarget=null;};_proto.setCursor=function setCursor(cursor){this.context.contextService.applyCursorStyle(cursor||this.context.config.cursor||'default');};_proto.normalizeToPointerEvent=function normalizeToPointerEvent(event,canvas){var normalizedEvents=[];if(canvas.isTouchEvent(event)){for(var i=0;i<event.changedTouches.length;i++){var touch=event.changedTouches[i];// use changedTouches instead of touches since touchend has no touches
- // @see https://stackoverflow.com/a/10079076
- if(isUndefined(touch.button))touch.button=0;if(isUndefined(touch.buttons))touch.buttons=1;if(isUndefined(touch.isPrimary)){touch.isPrimary=event.touches.length===1&&event.type==='touchstart';}if(isUndefined(touch.width))touch.width=touch.radiusX||1;if(isUndefined(touch.height))touch.height=touch.radiusY||1;if(isUndefined(touch.tiltX))touch.tiltX=0;if(isUndefined(touch.tiltY))touch.tiltY=0;if(isUndefined(touch.pointerType))touch.pointerType='touch';// @see https://developer.mozilla.org/zh-CN/docs/Web/API/Touch/identifier
- if(isUndefined(touch.pointerId))touch.pointerId=touch.identifier||0;if(isUndefined(touch.pressure))touch.pressure=touch.force||0.5;if(isUndefined(touch.twist))touch.twist=0;if(isUndefined(touch.tangentialPressure))touch.tangentialPressure=0;touch.isNormalized=true;touch.type=event.type;normalizedEvents.push(touch);}}else if(canvas.isMouseEvent(event)){var tempEvent=event;if(isUndefined(tempEvent.isPrimary))tempEvent.isPrimary=true;if(isUndefined(tempEvent.width))tempEvent.width=1;if(isUndefined(tempEvent.height))tempEvent.height=1;if(isUndefined(tempEvent.tiltX))tempEvent.tiltX=0;if(isUndefined(tempEvent.tiltY))tempEvent.tiltY=0;if(isUndefined(tempEvent.pointerType))tempEvent.pointerType='mouse';if(isUndefined(tempEvent.pointerId))tempEvent.pointerId=MOUSE_POINTER_ID;if(isUndefined(tempEvent.pressure))tempEvent.pressure=0.5;if(isUndefined(tempEvent.twist))tempEvent.twist=0;if(isUndefined(tempEvent.tangentialPressure))tempEvent.tangentialPressure=0;tempEvent.isNormalized=true;normalizedEvents.push(tempEvent);}else {normalizedEvents.push(event);}return normalizedEvents;};return EventPlugin;}();EventPlugin.tag='Event';// group is not a 2d shape
- var shape2D=[exports.Shape.CIRCLE,exports.Shape.ELLIPSE,exports.Shape.IMAGE,exports.Shape.RECT,exports.Shape.LINE,exports.Shape.POLYLINE,exports.Shape.POLYGON,exports.Shape.TEXT,exports.Shape.PATH,exports.Shape.HTML];var FrustumCullingStrategy=/*#__PURE__*/function(){function FrustumCullingStrategy(){}var _proto=FrustumCullingStrategy.prototype;_proto.isVisible=function isVisible(camera,object){var _object$parentNode,_object$parentNode$cu;// return true;
- var cullable=object.cullable;if(!cullable.enable){return true;}var renderBounds=object.getRenderBounds();if(AABB.isEmpty(renderBounds)){return false;}// get VP matrix from camera
- var frustum=camera.getFrustum();var parentVisibilityPlaneMask=(_object$parentNode=object.parentNode)===null||_object$parentNode===void 0?void 0:(_object$parentNode$cu=_object$parentNode.cullable)===null||_object$parentNode$cu===void 0?void 0:_object$parentNode$cu.visibilityPlaneMask;cullable.visibilityPlaneMask=this.computeVisibilityWithPlaneMask(object,renderBounds,parentVisibilityPlaneMask||exports.Mask.INDETERMINATE,frustum.planes);cullable.visible=cullable.visibilityPlaneMask!==exports.Mask.OUTSIDE;return cullable.visible;}/**
- *
- * @see「Optimized View Frustum Culling Algorithms for Bounding Boxes」
- * @see https://github.com/antvis/GWebGPUEngine/issues/3
- *
- * * 基础相交测试 the basic intersection test
- * * 标记 masking @see https://cesium.com/blog/2015/08/04/fast-hierarchical-culling/
- * * TODO: 平面一致性测试 the plane-coherency test
- * * TODO: 支持 mesh 指定自身的剔除策略,参考 Babylon.js @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
- *
- * @param aabb aabb
- * @param parentPlaneMask mask of parent
- * @param planes planes of frustum
- */;_proto.computeVisibilityWithPlaneMask=function computeVisibilityWithPlaneMask(object,aabb,parentPlaneMask,planes){if(parentPlaneMask===exports.Mask.OUTSIDE||parentPlaneMask===exports.Mask.INSIDE){// 父节点完全位于视锥内或者外部,直接返回
- return parentPlaneMask;}// Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
- // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
- var mask=exports.Mask.INSIDE;var isShape2D=shape2D.indexOf(object.nodeName)>-1;// Use viewport culling for 2D shapes
- // @see https://github.com/antvis/g/issues/914
- for(var k=0,len=planes.length;k<len;++k){// For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.
- var flag=1<<k;if((parentPlaneMask&flag)===0){// 父节点处于当前面内部,可以跳过
- continue;}// skip near & far planes when testing 2D shapes
- if(isShape2D&&(k===4||k===5)){continue;}// p-vertex n-vertex <-|plane p-vertex n-vertex
- // 使用 p-vertex 和 n-vertex 加速,避免进行平面和 aabb 全部顶点的相交检测
- var _planes$k=planes[k],normal=_planes$k.normal,distance=_planes$k.distance;if(dot(normal,aabb.getPositiveFarPoint(planes[k]))+distance<0){return exports.Mask.OUTSIDE;}if(dot(normal,aabb.getNegativeFarPoint(planes[k]))+distance<0){// 和当前面相交,对应位置为1,继续检测下一个面
- mask|=flag;}}return mask;};return FrustumCullingStrategy;}();var PrepareRendererPlugin=/*#__PURE__*/function(){function PrepareRendererPlugin(){this.rBush=void 0;/**
- * sync to RBush later
- */this.toSync=new Set();}var _proto=PrepareRendererPlugin.prototype;// private isFirstTimeRendering = true;
- // private syncing = false;
- _proto.apply=function apply(context){var _this=this;var renderingService=context.renderingService,renderingContext=context.renderingContext,rBushRoot=context.rBushRoot;var canvas=renderingContext.root.ownerDocument.defaultView;this.rBush=rBushRoot;var handleAttributeChanged=function handleAttributeChanged(e){var object=e.target;object.renderable.dirty=true;renderingService.dirtify();};var handleBoundsChanged=function handleBoundsChanged(e){var affectChildren=e.detail.affectChildren;var object=e.target;if(affectChildren){object.forEach(function(node){_this.toSync.add(node);});}var p=object;while(p){if(p.renderable){_this.toSync.add(p);}p=p.parentElement;}// this.pushToSync(e.composedPath().slice(0, -2) as DisplayObject[]);
- renderingService.dirtify();};var handleMounted=function handleMounted(e){var object=e.target;if(runtime.enableCSSParsing){// recalc style values
- runtime.styleValueRegistry.recalc(object);}runtime.sceneGraphService.dirtifyToRoot(object);renderingService.dirtify();};var handleUnmounted=function handleUnmounted(e){var object=e.target;var rBushNode=object.rBushNode;if(rBushNode.aabb){_this.rBush.remove(rBushNode.aabb);}_this.toSync.delete(object);runtime.sceneGraphService.dirtifyToRoot(object);renderingService.dirtify();};renderingService.hooks.init.tap(PrepareRendererPlugin.tag,function(){canvas.addEventListener(exports.ElementEvent.MOUNTED,handleMounted);canvas.addEventListener(exports.ElementEvent.UNMOUNTED,handleUnmounted);canvas.addEventListener(exports.ElementEvent.ATTR_MODIFIED,handleAttributeChanged);canvas.addEventListener(exports.ElementEvent.BOUNDS_CHANGED,handleBoundsChanged);});renderingService.hooks.destroy.tap(PrepareRendererPlugin.tag,function(){canvas.removeEventListener(exports.ElementEvent.MOUNTED,handleMounted);canvas.removeEventListener(exports.ElementEvent.UNMOUNTED,handleUnmounted);canvas.removeEventListener(exports.ElementEvent.ATTR_MODIFIED,handleAttributeChanged);canvas.removeEventListener(exports.ElementEvent.BOUNDS_CHANGED,handleBoundsChanged);_this.toSync.clear();});renderingService.hooks.endFrame.tap(PrepareRendererPlugin.tag,function(){// if (this.isFirstTimeRendering) {
- // this.isFirstTimeRendering = false;
- // this.syncing = true;
- // // @see https://github.com/antvis/G/issues/1117
- // setTimeout(() => {
- // this.syncRTree();
- // console.log('fcp...');
- // });
- // } else {
- // console.log('next...');
- _this.syncRTree();// }
- });};_proto.syncRTree=function syncRTree(){var _this2=this;// if (this.syncing) {
- // return;
- // }
- // bounds changed, need re-inserting its children
- var bulk=[];Array.from(this.toSync)// some objects may be removed since last frame
- .filter(function(object){return object.isConnected;}).forEach(function(node){var rBushNode=node.rBushNode;// clear dirty node
- if(rBushNode&&rBushNode.aabb){_this2.rBush.remove(rBushNode.aabb);}var renderBounds=node.getRenderBounds();if(renderBounds){var _renderBounds$getMin=renderBounds.getMin(),minX=_renderBounds$getMin[0],minY=_renderBounds$getMin[1];var _renderBounds$getMax=renderBounds.getMax(),maxX=_renderBounds$getMax[0],maxY=_renderBounds$getMax[1];if(!rBushNode.aabb){rBushNode.aabb={};}rBushNode.aabb.displayObject=node;rBushNode.aabb.minX=minX;rBushNode.aabb.minY=minY;rBushNode.aabb.maxX=maxX;rBushNode.aabb.maxY=maxY;}if(rBushNode.aabb){// TODO: NaN occurs when width/height of Rect is 0
- if(!isNaN(rBushNode.aabb.maxX)&&!isNaN(rBushNode.aabb.maxX)&&!isNaN(rBushNode.aabb.minX)&&!isNaN(rBushNode.aabb.minY)){bulk.push(rBushNode.aabb);}}});// use bulk inserting, which is ~2-3 times faster
- // @see https://github.com/mourner/rbush#bulk-inserting-data
- this.rBush.load(bulk);bulk.length=0;this.toSync.clear();// this.syncing = false;
- };return PrepareRendererPlugin;}();PrepareRendererPlugin.tag='Prepare';function isCanvas(value){return !!value.document;}(function(CanvasEvent){CanvasEvent["READY"]="ready";CanvasEvent["BEFORE_RENDER"]="beforerender";CanvasEvent["RERENDER"]="rerender";CanvasEvent["AFTER_RENDER"]="afterrender";CanvasEvent["BEFORE_DESTROY"]="beforedestroy";CanvasEvent["AFTER_DESTROY"]="afterdestroy";CanvasEvent["RESIZE"]="resize";CanvasEvent["DIRTY_RECTANGLE"]="dirtyrectangle";CanvasEvent["RENDERER_CHANGED"]="rendererchanged";})(exports.CanvasEvent||(exports.CanvasEvent={}));var DEFAULT_CAMERA_Z=500;var DEFAULT_CAMERA_NEAR=0.1;var DEFAULT_CAMERA_FAR=1000;/**
- * reuse custom event preventing from re-create them in every frame
- */var mountedEvent=new CustomEvent(exports.ElementEvent.MOUNTED);var unmountedEvent=new CustomEvent(exports.ElementEvent.UNMOUNTED);var beforeRenderEvent=new CustomEvent(exports.CanvasEvent.BEFORE_RENDER);var rerenderEvent=new CustomEvent(exports.CanvasEvent.RERENDER);var afterRenderEvent=new CustomEvent(exports.CanvasEvent.AFTER_RENDER);/**
- * can be treated like Window in DOM
- * provide some extra methods like `window`, such as:
- * * `window.requestAnimationFrame`
- * * `window.devicePixelRatio`
- *
- * prototype chains: Canvas(Window) -> EventTarget
- */var Canvas=/*#__PURE__*/function(_EventTarget){_inheritsLoose(Canvas,_EventTarget);function Canvas(config){var _this;_this=_EventTarget.call(this)||this;// create document
- /**
- * window.document
- */_this.document=void 0;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
- */_this.customElements=void 0;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
- */_this.requestAnimationFrame=void 0;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
- */_this.cancelAnimationFrame=void 0;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
- */_this.devicePixelRatio=void 0;/**
- * whether the runtime supports PointerEvent?
- * if not, the event system won't trigger pointer events like `pointerdown`
- */_this.supportsPointerEvents=void 0;/**
- * whether the runtime supports TouchEvent?
- * if not, the event system won't trigger touch events like `touchstart`
- */_this.supportsTouchEvents=void 0;/**
- * is this native event a TouchEvent?
- */_this.isTouchEvent=void 0;/**
- * is this native event a MouseEvent?
- */_this.isMouseEvent=void 0;/**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element
- */_this.Element=DisplayObject;/**
- * rAF in auto rendering
- */_this.frameId=void 0;_this.inited=false;_this.readyPromise=void 0;_this.resolveReadyPromise=void 0;_this.context={};_this.document=new Document();_this.document.defaultView=_assertThisInitialized(_this);// create registry of custom elements
- _this.customElements=new CustomElementRegistry();var container=config.container,canvas=config.canvas,offscreenCanvas=config.offscreenCanvas,width=config.width,height=config.height,devicePixelRatio=config.devicePixelRatio,renderer=config.renderer,background=config.background,cursor=config.cursor,document=config.document,requestAnimationFrame=config.requestAnimationFrame,cancelAnimationFrame=config.cancelAnimationFrame,createImage=config.createImage,supportsPointerEvents=config.supportsPointerEvents,supportsTouchEvents=config.supportsTouchEvents,supportsCSSTransform=config.supportsCSSTransform,useNativeClickEvent=config.useNativeClickEvent,alwaysTriggerPointerEventOnCanvas=config.alwaysTriggerPointerEventOnCanvas,isTouchEvent=config.isTouchEvent,isMouseEvent=config.isMouseEvent;cleanExistedCanvas(container,_assertThisInitialized(_this));var canvasWidth=width;var canvasHeight=height;var dpr=devicePixelRatio;// use user-defined <canvas> or OffscreenCanvas
- if(canvas){// infer width & height with dpr
- dpr=devicePixelRatio||isBrowser&&window.devicePixelRatio||1;dpr=dpr>=1?Math.ceil(dpr):1;canvasWidth=width||getWidth(canvas)||canvas.width/dpr;canvasHeight=height||getHeight(canvas)||canvas.height/dpr;}/**
- * implements `Window` interface
- */_this.devicePixelRatio=dpr;_this.requestAnimationFrame=requestAnimationFrame!==null&&requestAnimationFrame!==void 0?requestAnimationFrame:raf.bind(runtime.globalThis);_this.cancelAnimationFrame=cancelAnimationFrame!==null&&cancelAnimationFrame!==void 0?cancelAnimationFrame:caf.bind(runtime.globalThis);/**
- * limits query
- */ // the following feature-detect from hammer.js
- // @see https://github.com/hammerjs/hammer.js/blob/master/src/inputjs/input-consts.js#L5
- _this.supportsTouchEvents=supportsTouchEvents!==null&&supportsTouchEvents!==void 0?supportsTouchEvents:'ontouchstart'in runtime.globalThis;_this.supportsPointerEvents=supportsPointerEvents!==null&&supportsPointerEvents!==void 0?supportsPointerEvents:!!runtime.globalThis.PointerEvent;_this.isTouchEvent=isTouchEvent!==null&&isTouchEvent!==void 0?isTouchEvent:function(event){return _this.supportsTouchEvents&&event instanceof runtime.globalThis.TouchEvent;};_this.isMouseEvent=isMouseEvent!==null&&isMouseEvent!==void 0?isMouseEvent:function(event){return !runtime.globalThis.MouseEvent||event instanceof runtime.globalThis.MouseEvent&&(!_this.supportsPointerEvents||!(event instanceof runtime.globalThis.PointerEvent));};_this.initRenderingContext({container:container,canvas:canvas,width:canvasWidth,height:canvasHeight,renderer:renderer,offscreenCanvas:offscreenCanvas,devicePixelRatio:dpr,cursor:cursor||'default',background:background||'transparent',createImage:createImage,document:document,supportsCSSTransform:supportsCSSTransform,useNativeClickEvent:useNativeClickEvent,alwaysTriggerPointerEventOnCanvas:alwaysTriggerPointerEventOnCanvas});_this.initDefaultCamera(canvasWidth,canvasHeight);_this.initRenderer(renderer,true);return _this;}var _proto=Canvas.prototype;_proto.initRenderingContext=function initRenderingContext(mergedConfig){this.context.config=mergedConfig;// bind rendering context, shared by all renderers
- this.context.renderingContext={/**
- * the root node in scene graph
- */root:this.document.documentElement,renderListCurrentFrame:[],unculledEntities:[],renderReasons:new Set(),force:false,dirty:false};};_proto.initDefaultCamera=function initDefaultCamera(width,height){var _this2=this;// set a default ortho camera
- var camera=new runtime.CameraContribution();camera.setType(exports.CameraType.EXPLORING,exports.CameraTrackingMode.DEFAULT).setPosition(width/2,height/2,DEFAULT_CAMERA_Z).setFocalPoint(width/2,height/2,0).setOrthographic(width/-2,width/2,height/2,height/-2,DEFAULT_CAMERA_NEAR,DEFAULT_CAMERA_FAR);// keep ref since it will use raf in camera animation
- camera.canvas=this;// redraw when camera changed
- camera.eventEmitter.on(CameraEvent.UPDATED,function(){_this2.context.renderingContext.renderReasons.add(exports.RenderReason.CAMERA_CHANGED);});// bind camera
- this.context.camera=camera;};_proto.getConfig=function getConfig(){return this.context.config;}/**
- * get the root displayObject in scenegraph
- * @alias this.document.documentElement
- */;_proto.getRoot=function getRoot(){return this.document.documentElement;}/**
- * get the camera of canvas
- */;_proto.getCamera=function getCamera(){return this.context.camera;};_proto.getContextService=function getContextService(){return this.context.contextService;};_proto.getEventService=function getEventService(){return this.context.eventService;};_proto.getRenderingService=function getRenderingService(){return this.context.renderingService;};_proto.getRenderingContext=function getRenderingContext(){return this.context.renderingContext;};_proto.getStats=function getStats(){return this.getRenderingService().getStats();}// /**
- // * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
- // */
- // getComputedStyle(node: DisplayObject) {
- // return node.computedStyle;
- // }
- ;/**
- * `cleanUp` means clean all the internal services of Canvas which happens when calling `canvas.destroy()`.
- */_proto.destroy=function destroy(cleanUp,skipTriggerEvent){if(cleanUp===void 0){cleanUp=true;}if(skipTriggerEvent===void 0){skipTriggerEvent=false;}if(!skipTriggerEvent){this.dispatchEvent(new CustomEvent(exports.CanvasEvent.BEFORE_DESTROY));}if(this.frameId){var cancelRAF=this.getConfig().cancelAnimationFrame||cancelAnimationFrame;cancelRAF(this.frameId);}// unmount all children
- var root=this.getRoot();this.unmountChildren(root);if(cleanUp){// destroy Document
- this.document.destroy();this.getEventService().destroy();}// destroy services
- this.getRenderingService().destroy();this.getContextService().destroy();// clear root after renderservice destroyed
- if(cleanUp&&this.context.rBushRoot){// clear rbush
- this.context.rBushRoot.clear();this.context.rBushRoot=null;this.context.renderingContext.root=null;}if(!skipTriggerEvent){this.dispatchEvent(new CustomEvent(exports.CanvasEvent.AFTER_DESTROY));}}/**
- * compatible with G 3.0
- * @deprecated
- * @alias resize
- */;_proto.changeSize=function changeSize(width,height){this.resize(width,height);};_proto.resize=function resize(width,height){// update canvas' config
- var canvasConfig=this.context.config;canvasConfig.width=width;canvasConfig.height=height;// resize context
- this.getContextService().resize(width,height);// resize camera
- var camera=this.context.camera;var projectionMode=camera.getProjectionMode();camera.setPosition(width/2,height/2,DEFAULT_CAMERA_Z).setFocalPoint(width/2,height/2,0);if(projectionMode===exports.CameraProjectionMode.ORTHOGRAPHIC){camera.setOrthographic(width/-2,width/2,height/2,height/-2,camera.getNear(),camera.getFar());}else {camera.setAspect(width/height);}this.dispatchEvent(new CustomEvent(exports.CanvasEvent.RESIZE,{width:width,height:height}));}// proxy to document.documentElement
- ;_proto.appendChild=function appendChild(child,index){return this.document.documentElement.appendChild(child,index);};_proto.insertBefore=function insertBefore(newChild,refChild){return this.document.documentElement.insertBefore(newChild,refChild);};_proto.removeChild=function removeChild(child){return this.document.documentElement.removeChild(child);}/**
- * Remove all children which can be appended to its original parent later again.
- */;_proto.removeChildren=function removeChildren(){this.document.documentElement.removeChildren();}/**
- * Recursively destroy all children which can not be appended to its original parent later again.
- * But the canvas remains running which means display objects can be appended later.
- */;_proto.destroyChildren=function destroyChildren(){this.document.documentElement.destroyChildren();};_proto.render=function render(){var _this3=this;this.dispatchEvent(beforeRenderEvent);var renderingService=this.getRenderingService();renderingService.render(this.getConfig(),function(){// trigger actual rerender event
- // @see https://github.com/antvis/G/issues/1268
- _this3.dispatchEvent(rerenderEvent);});this.dispatchEvent(afterRenderEvent);};_proto.run=function run(){var _this4=this;var tick=function tick(){_this4.render();_this4.frameId=_this4.requestAnimationFrame(tick);};tick();};_proto.initRenderer=function initRenderer(renderer,firstContentfullPaint){var _this5=this;if(firstContentfullPaint===void 0){firstContentfullPaint=false;}if(!renderer){throw new Error('Renderer is required.');}// reset
- this.inited=false;this.readyPromise=undefined;// FIXME: should re-create here?
- this.context.rBushRoot=new rbush();// reset rendering plugins
- this.context.renderingPlugins=[];this.context.renderingPlugins.push(new EventPlugin(),new PrepareRendererPlugin(),new DirtyCheckPlugin(),new CullingPlugin([new FrustumCullingStrategy()]));//
- this.loadRendererContainerModule(renderer);// init context service
- this.context.contextService=new this.context.ContextService(_extends({},runtime,this.context));// init rendering service
- this.context.renderingService=new RenderingService(runtime,this.context);// init event service
- this.context.eventService=new EventService(runtime,this.context);this.context.eventService.init();if(this.context.contextService.init){this.context.contextService.init();this.initRenderingService(renderer,firstContentfullPaint,true);}else {this.context.contextService.initAsync().then(function(){_this5.initRenderingService(renderer,firstContentfullPaint);});}};_proto.initRenderingService=function initRenderingService(renderer,firstContentfullPaint,async){var _this6=this;if(firstContentfullPaint===void 0){firstContentfullPaint=false;}if(async===void 0){async=false;}this.context.renderingService.init(function(){_this6.inited=true;if(firstContentfullPaint){if(async){_this6.requestAnimationFrame(function(){_this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.READY));});}else {_this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.READY));}if(_this6.readyPromise){_this6.resolveReadyPromise();}}else {_this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.RENDERER_CHANGED));}if(!firstContentfullPaint){_this6.getRoot().forEach(function(node){var renderable=node.renderable;if(renderable){renderable.renderBoundsDirty=true;renderable.boundsDirty=true;renderable.dirty=true;}});}// keep current scenegraph unchanged, just trigger mounted event
- _this6.mountChildren(_this6.getRoot());if(renderer.getConfig().enableAutoRendering){_this6.run();}});};_proto.loadRendererContainerModule=function loadRendererContainerModule(renderer){var _this7=this;// load other container modules provided by g-canvas/g-svg/g-webgl
- var plugins=renderer.getPlugins();plugins.forEach(function(plugin){plugin.context=_this7.context;plugin.init(runtime);});};_proto.setRenderer=function setRenderer(renderer){// update canvas' config
- var canvasConfig=this.getConfig();if(canvasConfig.renderer===renderer){return;}var oldRenderer=canvasConfig.renderer;canvasConfig.renderer=renderer;// keep all children undestroyed
- this.destroy(false,true);// destroy all plugins, reverse will mutate origin array
- [].concat(oldRenderer===null||oldRenderer===void 0?void 0:oldRenderer.getPlugins()).reverse().forEach(function(plugin){plugin.destroy(runtime);});this.initRenderer(renderer);};_proto.setCursor=function setCursor(cursor){var canvasConfig=this.getConfig();canvasConfig.cursor=cursor;this.getContextService().applyCursorStyle(cursor);};_proto.unmountChildren=function unmountChildren(parent){var _this8=this;// unmountChildren recursively
- parent.childNodes.forEach(function(child){_this8.unmountChildren(child);});if(this.inited){if(parent.isMutationObserved){parent.dispatchEvent(unmountedEvent);}else {unmountedEvent.target=parent;this.dispatchEvent(unmountedEvent,true);}// skip document.documentElement
- if(parent!==this.document.documentElement){parent.ownerDocument=null;}parent.isConnected=false;}// trigger after unmounted
- if(parent.isCustomElement){if(parent.disconnectedCallback){parent.disconnectedCallback();}}};_proto.mountChildren=function mountChildren(parent){var _this9=this;if(this.inited){if(!parent.isConnected){parent.ownerDocument=this.document;parent.isConnected=true;if(parent.isMutationObserved){parent.dispatchEvent(mountedEvent);}else {mountedEvent.target=parent;this.dispatchEvent(mountedEvent,true);}}}else {console.warn("[g]: You are trying to call `canvas.appendChild` before canvas' initialization finished. You can either await `canvas.ready` or listen to `CanvasEvent.READY` manually.",'appended child: ',parent.nodeName);}// recursively mount children
- parent.childNodes.forEach(function(child){_this9.mountChildren(child);});// trigger after mounted
- if(parent.isCustomElement){if(parent.connectedCallback){parent.connectedCallback();}}};_proto.client2Viewport=function client2Viewport(client){return this.getEventService().client2Viewport(client);};_proto.viewport2Client=function viewport2Client(canvas){return this.getEventService().viewport2Client(canvas);};_proto.viewport2Canvas=function viewport2Canvas(viewport){return this.getEventService().viewport2Canvas(viewport);};_proto.canvas2Viewport=function canvas2Viewport(canvas){return this.getEventService().canvas2Viewport(canvas);}/**
- * @deprecated
- * @alias client2Viewport
- */;_proto.getPointByClient=function getPointByClient(clientX,clientY){return this.client2Viewport({x:clientX,y:clientY});}/**
- * @deprecated
- * @alias viewport2Client
- */;_proto.getClientByPoint=function getClientByPoint(x,y){return this.viewport2Client({x:x,y:y});};_createClass(Canvas,[{key:"ready",get:function get(){var _this10=this;if(!this.readyPromise){this.readyPromise=new Promise(function(resolve){_this10.resolveReadyPromise=function(){resolve(_this10);};});if(this.inited){this.resolveReadyPromise();}}return this.readyPromise;}}]);return Canvas;}(EventTarget);
- function _inheritsLoose$1(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$1(subClass, superClass);
- }
- function _setPrototypeOf$1(o, p) {
- _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf$1(o, p);
- }
- /**
- * Provides camera action & animation.
- */
- var AdvancedCamera = /*#__PURE__*/function (_Camera) {
- _inheritsLoose$1(AdvancedCamera, _Camera);
- function AdvancedCamera() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _Camera.call.apply(_Camera, [this].concat(args)) || this;
- /**
- * switch between multiple landmarks
- */
- _this.landmarks = [];
- _this.landmarkAnimationID = void 0;
- return _this;
- }
- var _proto = AdvancedCamera.prototype;
- /**
- * Changes the azimuth and elevation with respect to the current camera axes
- * @param {Number} azimuth the relative azimuth
- * @param {Number} elevation the relative elevation
- * @param {Number} roll the relative roll
- */
- _proto.rotate = function rotate(azimuth, elevation, roll) {
- this.relElevation = getAngle$1(elevation);
- this.relAzimuth = getAngle$1(azimuth);
- this.relRoll = getAngle$1(roll);
- this.elevation += this.relElevation;
- this.azimuth += this.relAzimuth;
- this.roll += this.relRoll;
- if (this.type === exports.CameraType.EXPLORING) {
- var rotX = setAxisAngle(create$4(), [1, 0, 0], deg2rad((this.rotateWorld ? 1 : -1) * this.relElevation));
- var rotY = setAxisAngle(create$4(), [0, 1, 0], deg2rad((this.rotateWorld ? 1 : -1) * this.relAzimuth));
- var rotZ = setAxisAngle(create$4(), [0, 0, 1], deg2rad(this.relRoll));
- var rotQ = multiply$2(create$4(), rotY, rotX);
- rotQ = multiply$2(create$4(), rotQ, rotZ);
- var rotMatrix = fromQuat(create$1(), rotQ);
- translate(this.matrix, this.matrix, [0, 0, -this.distance]);
- multiply(this.matrix, this.matrix, rotMatrix);
- translate(this.matrix, this.matrix, [0, 0, this.distance]);
- } else {
- if (Math.abs(this.elevation) > 90) {
- return this;
- }
- this.computeMatrix();
- }
- this._getAxes();
- if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === exports.CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this._update();
- return this;
- }
- /**
- * 沿水平(right) & 垂直(up)平移相机
- */;
- _proto.pan = function pan(tx, ty) {
- var coords = createVec3(tx, ty, 0);
- var pos = clone$1(this.position);
- add$1(pos, pos, scale$1(create$2(), this.right, coords[0]));
- add$1(pos, pos, scale$1(create$2(), this.up, coords[1]));
- this._setPosition(pos);
- this.triggerUpdate();
- return this;
- }
- /**
- * 沿 n 轴移动,当距离视点远时移动速度较快,离视点越近速度越慢
- */;
- _proto.dolly = function dolly(value) {
- var n = this.forward;
- var pos = clone$1(this.position);
- var step = value * this.dollyingStep;
- var updatedDistance = this.distance + value * this.dollyingStep;
- // 限制视点距离范围
- step = Math.max(Math.min(updatedDistance, this.maxDistance), this.minDistance) - this.distance;
- pos[0] += step * n[0];
- pos[1] += step * n[1];
- pos[2] += step * n[2];
- this._setPosition(pos);
- if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
- // 重新计算视点距离
- this._getDistance();
- } else if (this.type === exports.CameraType.TRACKING) {
- // 保持视距,移动视点位置
- add$1(this.focalPoint, pos, this.distanceVector);
- }
- this.triggerUpdate();
- return this;
- };
- _proto.cancelLandmarkAnimation = function cancelLandmarkAnimation() {
- if (this.landmarkAnimationID !== undefined) {
- this.canvas.cancelAnimationFrame(this.landmarkAnimationID);
- }
- };
- _proto.createLandmark = function createLandmark(name, params) {
- var _position$, _position$2, _focalPoint$, _focalPoint$2;
- if (params === void 0) {
- params = {};
- }
- var _params = params,
- _params$position = _params.position,
- position = _params$position === void 0 ? this.position : _params$position,
- _params$focalPoint = _params.focalPoint,
- focalPoint = _params$focalPoint === void 0 ? this.focalPoint : _params$focalPoint,
- roll = _params.roll,
- zoom = _params.zoom;
- var camera = new runtime.CameraContribution();
- camera.setType(this.type, undefined);
- camera.setPosition(position[0], (_position$ = position[1]) !== null && _position$ !== void 0 ? _position$ : this.position[1], (_position$2 = position[2]) !== null && _position$2 !== void 0 ? _position$2 : this.position[2]);
- camera.setFocalPoint(focalPoint[0], (_focalPoint$ = focalPoint[1]) !== null && _focalPoint$ !== void 0 ? _focalPoint$ : this.focalPoint[1], (_focalPoint$2 = focalPoint[2]) !== null && _focalPoint$2 !== void 0 ? _focalPoint$2 : this.focalPoint[2]);
- camera.setRoll(roll !== null && roll !== void 0 ? roll : this.roll);
- camera.setZoom(zoom !== null && zoom !== void 0 ? zoom : this.zoom);
- var landmark = {
- name: name,
- matrix: clone(camera.getWorldTransform()),
- right: clone$1(camera.right),
- up: clone$1(camera.up),
- forward: clone$1(camera.forward),
- position: clone$1(camera.getPosition()),
- focalPoint: clone$1(camera.getFocalPoint()),
- distanceVector: clone$1(camera.getDistanceVector()),
- distance: camera.getDistance(),
- dollyingStep: camera.getDollyingStep(),
- azimuth: camera.getAzimuth(),
- elevation: camera.getElevation(),
- roll: camera.getRoll(),
- relAzimuth: camera.relAzimuth,
- relElevation: camera.relElevation,
- relRoll: camera.relRoll,
- zoom: camera.getZoom()
- };
- this.landmarks.push(landmark);
- return landmark;
- };
- _proto.gotoLandmark = function gotoLandmark(name, options) {
- var _this2 = this;
- if (options === void 0) {
- options = {};
- }
- var landmark = isString(name) ? this.landmarks.find(function (l) {
- return l.name === name;
- }) : name;
- if (landmark) {
- var _ref = isNumber(options) ? {
- duration: options
- } : options,
- _ref$easing = _ref.easing,
- easing = _ref$easing === void 0 ? 'linear' : _ref$easing,
- _ref$duration = _ref.duration,
- duration = _ref$duration === void 0 ? 100 : _ref$duration,
- _ref$easingFunction = _ref.easingFunction,
- easingFunction = _ref$easingFunction === void 0 ? undefined : _ref$easingFunction,
- _ref$onfinish = _ref.onfinish,
- onfinish = _ref$onfinish === void 0 ? undefined : _ref$onfinish;
- var epsilon = 0.01;
- if (duration === 0) {
- this.syncFromLandmark(landmark);
- if (onfinish) {
- onfinish();
- }
- return;
- }
- // cancel ongoing animation
- this.cancelLandmarkAnimation();
- var destPosition = landmark.position;
- var destFocalPoint = landmark.focalPoint;
- var destZoom = landmark.zoom;
- var destRoll = landmark.roll;
- var easingFunc = easingFunction || runtime.EasingFunction(easing);
- var timeStart;
- var endAnimation = function endAnimation() {
- _this2.setFocalPoint(destFocalPoint);
- _this2.setPosition(destPosition);
- _this2.setRoll(destRoll);
- _this2.setZoom(destZoom);
- _this2.computeMatrix();
- _this2.triggerUpdate();
- if (onfinish) {
- onfinish();
- }
- };
- var animate = function animate(timestamp) {
- if (timeStart === undefined) {
- timeStart = timestamp;
- }
- var elapsed = timestamp - timeStart;
- if (elapsed > duration) {
- endAnimation();
- return;
- }
- // use the same ease function in animation system
- var t = easingFunc(elapsed / duration);
- var interFocalPoint = create$2();
- var interPosition = create$2();
- var interZoom = 1;
- var interRoll = 0;
- lerp(interFocalPoint, _this2.focalPoint, destFocalPoint, t);
- lerp(interPosition, _this2.position, destPosition, t);
- interRoll = _this2.roll * (1 - t) + destRoll * t;
- interZoom = _this2.zoom * (1 - t) + destZoom * t;
- _this2.setFocalPoint(interFocalPoint);
- _this2.setPosition(interPosition);
- _this2.setRoll(interRoll);
- _this2.setZoom(interZoom);
- var dist$1 = dist(interFocalPoint, destFocalPoint) + dist(interPosition, destPosition);
- if (dist$1 <= epsilon && destZoom == undefined && destRoll == undefined) {
- endAnimation();
- return;
- }
- _this2.computeMatrix();
- _this2.triggerUpdate();
- if (elapsed < duration) {
- _this2.landmarkAnimationID = _this2.canvas.requestAnimationFrame(animate);
- }
- };
- this.canvas.requestAnimationFrame(animate);
- }
- };
- _proto.syncFromLandmark = function syncFromLandmark(landmark) {
- this.matrix = copy(this.matrix, landmark.matrix);
- this.right = copy$1(this.right, landmark.right);
- this.up = copy$1(this.up, landmark.up);
- this.forward = copy$1(this.forward, landmark.forward);
- this.position = copy$1(this.position, landmark.position);
- this.focalPoint = copy$1(this.focalPoint, landmark.focalPoint);
- this.distanceVector = copy$1(this.distanceVector, landmark.distanceVector);
- this.azimuth = landmark.azimuth;
- this.elevation = landmark.elevation;
- this.roll = landmark.roll;
- this.relAzimuth = landmark.relAzimuth;
- this.relElevation = landmark.relElevation;
- this.relRoll = landmark.relRoll;
- this.dollyingStep = landmark.dollyingStep;
- this.distance = landmark.distance;
- this.zoom = landmark.zoom;
- };
- return AdvancedCamera;
- }(Camera);
- runtime.CameraContribution = AdvancedCamera;
- var MutationRecord = /*#__PURE__*/function () {
- MutationRecord.copy = function copy(original) {
- var record = new MutationRecord(original.type, original.target);
- record.addedNodes = original.addedNodes.slice();
- record.removedNodes = original.removedNodes.slice();
- record.previousSibling = original.previousSibling;
- record.nextSibling = original.nextSibling;
- record.attributeName = original.attributeName;
- record.attributeNamespace = original.attributeNamespace;
- record.oldValue = original.oldValue;
- return record;
- };
- function MutationRecord(type, target) {
- this.type = void 0;
- this.target = void 0;
- this.addedNodes = [];
- this.attributeName = null;
- this.attributeNamespace = null;
- this.nextSibling = null;
- this.oldValue = null;
- this.previousSibling = null;
- this.removedNodes = [];
- this.type = type;
- this.target = target;
- }
- return MutationRecord;
- }();
- var uidCounter = 0;
- var registrationsTable = new WeakMap();
- var Registration = /*#__PURE__*/function () {
- function Registration(observer, target, options) {
- this.observer = void 0;
- this.target = void 0;
- this.options = void 0;
- this.transientObservedNodes = [];
- this.observer = observer;
- this.target = target;
- this.options = options;
- }
- var _proto = Registration.prototype;
- _proto.enqueue = function enqueue(record) {
- var records = this.observer.records;
- var length = records.length;
- // There are cases where we replace the last record with the new record.
- // For example if the record represents the same mutation we need to use
- // the one with the oldValue. If we get same record (this can happen as we
- // walk up the tree) we ignore the new record.
- if (records.length > 0) {
- var lastRecord = records[length - 1];
- var recordToReplaceLast = selectRecord(lastRecord, record);
- if (recordToReplaceLast) {
- records[length - 1] = recordToReplaceLast;
- return;
- }
- } else {
- scheduleCallback(this.observer);
- }
- records[length] = record;
- };
- _proto.addListeners = function addListeners() {
- this.addListeners_(this.target);
- };
- _proto.addListeners_ = function addListeners_(node) {
- var options = this.options;
- if (options.attributes) node.addEventListener(exports.ElementEvent.ATTR_MODIFIED, this, true);
- // if (options.characterData) node.addEventListener('DOMCharacterDataModified', this, true);
- if (options.childList) node.addEventListener(exports.ElementEvent.INSERTED, this, true);
- if (options.childList || options.subtree) node.addEventListener(exports.ElementEvent.REMOVED, this, true);
- };
- _proto.removeListeners = function removeListeners() {
- this.removeListeners_(this.target);
- };
- _proto.removeListeners_ = function removeListeners_(node) {
- var options = this.options;
- if (options.attributes) node.removeEventListener(exports.ElementEvent.ATTR_MODIFIED, this, true);
- // if (options.characterData) node.removeEventListener('DOMCharacterDataModified', this, true);
- if (options.childList) node.removeEventListener(exports.ElementEvent.INSERTED, this, true);
- if (options.childList || options.subtree) node.removeEventListener(exports.ElementEvent.REMOVED, this, true);
- }
- /**
- * Adds a transient observer on node. The transient observer gets removed
- * next time we deliver the change records.
- */
- // addTransientObserver(node: IElement) {
- // // Don't add transient observers on the target itself. We already have all
- // // the required listeners set up on the target.
- // if (node === this.target) return;
- // this.addListeners_(node);
- // this.transientObservedNodes.push(node);
- // let registrations = registrationsTable.get(node);
- // if (!registrations) registrationsTable.set(node, (registrations = []));
- // // We know that registrations does not contain this because we already
- // // checked if node === this.target.
- // registrations.push(this);
- // }
- ;
- _proto.removeTransientObservers = function removeTransientObservers() {
- var transientObservedNodes = this.transientObservedNodes;
- this.transientObservedNodes = [];
- transientObservedNodes.forEach(function (node) {
- // Transient observers are never added to the target.
- this.removeListeners_(node);
- var registrations = registrationsTable.get(node);
- for (var i = 0; i < registrations.length; i++) {
- if (registrations[i] === this) {
- registrations.splice(i, 1);
- // Each node can only have one registered observer associated with
- // this observer.
- break;
- }
- }
- }, this);
- };
- _proto.handleEvent = function handleEvent(e) {
- // Stop propagation since we are managing the propagation manually.
- // This means that other mutation events on the page will not work
- // correctly but that is by design.
- e.stopImmediatePropagation();
- var record;
- var target;
- switch (e.type) {
- case exports.ElementEvent.ATTR_MODIFIED:
- // http://dom.spec.whatwg.org/#concept-mo-queue-attributes
- var name = e.attrName;
- // @ts-ignore
- var namespace = e.relatedNode.namespaceURI;
- target = e.target;
- // 1.
- record = getRecord('attributes', target);
- record.attributeName = name;
- record.attributeNamespace = namespace;
- // 2.
- var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue;
- forEachAncestorAndObserverEnqueueRecord(target, function (options) {
- // 3.1, 4.2
- if (!options.attributes) return;
- // 3.2, 4.3
- if (options.attributeFilter && options.attributeFilter.length && options.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(namespace) === -1) {
- return;
- }
- // 3.3, 4.4
- if (options.attributeOldValue) return getRecordWithOldValue(oldValue);
- // 3.4, 4.5
- return record;
- });
- break;
- // case 'DOMCharacterDataModified':
- // // http://dom.spec.whatwg.org/#concept-mo-queue-characterdata
- // var target = e.target;
- // // 1.
- // var record = getRecord('characterData', target);
- // // 2.
- // var oldValue = e.prevValue;
- // forEachAncestorAndObserverEnqueueRecord(target, function(options) {
- // // 3.1, 4.2
- // if (!options.characterData)
- // return;
- // // 3.2, 4.3
- // if (options.characterDataOldValue)
- // return getRecordWithOldValue(oldValue);
- // // 3.3, 4.4
- // return record;
- // });
- // break;
- case exports.ElementEvent.REMOVED:
- // this.addTransientObserver(e.target as IElement);
- // Fall through.
- case exports.ElementEvent.INSERTED:
- // http://dom.spec.whatwg.org/#concept-mo-queue-childlist
- target = e.relatedNode;
- var changedNode = e.target;
- var addedNodes;
- var removedNodes;
- if (e.type === exports.ElementEvent.INSERTED) {
- addedNodes = [changedNode];
- removedNodes = [];
- } else {
- addedNodes = [];
- removedNodes = [changedNode];
- }
- var previousSibling = changedNode.previousSibling;
- var nextSibling = changedNode.nextSibling;
- // 1.
- record = getRecord('childList', target);
- record.addedNodes = addedNodes;
- record.removedNodes = removedNodes;
- record.previousSibling = previousSibling;
- record.nextSibling = nextSibling;
- forEachAncestorAndObserverEnqueueRecord(target, function (options) {
- // 2.1, 3.2
- if (!options.childList) return;
- // 2.2, 3.3
- return record;
- });
- }
- clearRecords();
- };
- return Registration;
- }();
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
- * @see https://github.com/googlearchive/MutationObservers/blob/master/MutationObserver.js
- */
- var MutationObserver = /*#__PURE__*/function () {
- function MutationObserver(callback) {
- this.callback = void 0;
- this.nodes = [];
- this.records = [];
- this.uid = uidCounter++;
- this.callback = callback;
- }
- var _proto2 = MutationObserver.prototype;
- _proto2.observe = function observe(target, options) {
- // 1.1
- if (!options.childList && !options.attributes && !options.characterData ||
- // 1.2
- options.attributeOldValue && !options.attributes ||
- // 1.3
- options.attributeFilter && options.attributeFilter.length && !options.attributes ||
- // 1.4
- options.characterDataOldValue && !options.characterData) {
- throw new SyntaxError();
- }
- var registrations = registrationsTable.get(target);
- if (!registrations) registrationsTable.set(target, registrations = []);
- // 2
- // If target's list of registered observers already includes a registered
- // observer associated with the context object, replace that registered
- // observer's options with options.
- var registration;
- for (var i = 0; i < registrations.length; i++) {
- if (registrations[i].observer === this) {
- registration = registrations[i];
- registration.removeListeners();
- registration.options = options;
- break;
- }
- }
- // 3.
- // Otherwise, add a new registered observer to target's list of registered
- // observers with the context object as the observer and options as the
- // options, and add target to context object's list of nodes on which it
- // is registered.
- if (!registration) {
- registration = new Registration(this, target, options);
- registrations.push(registration);
- this.nodes.push(target);
- }
- registration.addListeners();
- };
- _proto2.disconnect = function disconnect() {
- var _this = this;
- this.nodes.forEach(function (node) {
- var registrations = registrationsTable.get(node);
- for (var i = 0; i < registrations.length; i++) {
- var registration = registrations[i];
- if (registration.observer === _this) {
- registration.removeListeners();
- registrations.splice(i, 1);
- // Each node can only have one registered observer associated with
- // this observer.
- break;
- }
- }
- }, this);
- this.records = [];
- };
- _proto2.takeRecords = function takeRecords() {
- var copyOfRecords = this.records;
- this.records = [];
- return copyOfRecords;
- };
- return MutationObserver;
- }();
- // We keep track of the two (possibly one) records used in a single mutation.
- var currentRecord;
- var recordWithOldValue;
- /**
- * Creates a record without |oldValue| and caches it as |currentRecord| for
- * later use.
- */
- function getRecord(type, target) {
- return currentRecord = new MutationRecord(type, target);
- }
- /**
- * Gets or creates a record with |oldValue| based in the |currentRecord|
- */
- function getRecordWithOldValue(oldValue) {
- if (recordWithOldValue) return recordWithOldValue;
- recordWithOldValue = MutationRecord.copy(currentRecord);
- recordWithOldValue.oldValue = oldValue;
- return recordWithOldValue;
- }
- function clearRecords() {
- currentRecord = recordWithOldValue = undefined;
- }
- /**
- * Whether the record represents a record from the current
- * mutation event.
- */
- function recordRepresentsCurrentMutation(record) {
- return record === recordWithOldValue || record === currentRecord;
- }
- /**
- * Selects which record, if any, to replace the last record in the queue.
- * This returns |null| if no record should be replaced.
- */
- function selectRecord(lastRecord, newRecord) {
- if (lastRecord === newRecord) return lastRecord;
- // Check if the the record we are adding represents the same record. If
- // so, we keep the one with the oldValue in it.
- if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) return recordWithOldValue;
- return null;
- }
- function removeTransientObserversFor(observer) {
- observer.nodes.forEach(function (node) {
- var registrations = registrationsTable.get(node);
- if (!registrations) return;
- registrations.forEach(function (registration) {
- if (registration.observer === observer) registration.removeTransientObservers();
- });
- });
- }
- /**
- * This function is used for the "For each registered observer observer (with
- * observer's options as options) in target's list of registered observers,
- * run these substeps:" and the "For each ancestor ancestor of target, and for
- * each registered observer observer (with options options) in ancestor's list
- * of registered observers, run these substeps:" part of the algorithms. The
- * |options.subtree| is checked to ensure that the callback is called
- * correctly.
- *
- * @param {Node} target
- * @param {function(MutationObserverInit):MutationRecord} callback
- */
- function forEachAncestorAndObserverEnqueueRecord(target, callback) {
- for (var node = target; node; node = node.parentNode) {
- var registrations = registrationsTable.get(node);
- if (registrations) {
- for (var j = 0; j < registrations.length; j++) {
- var registration = registrations[j];
- var options = registration.options;
- // Only target ignores subtree.
- if (node !== target && !options.subtree) continue;
- var record = callback(options);
- if (record) registration.enqueue(record);
- }
- }
- }
- }
- // This is used to ensure that we never schedule 2 callas to setImmediate
- var isScheduled = false;
- // Keep track of observers that needs to be notified next time.
- var scheduledObservers = [];
- /**
- * Schedules |dispatchCallback| to be called in the future.
- */
- function scheduleCallback(observer) {
- scheduledObservers.push(observer);
- if (!isScheduled) {
- isScheduled = true;
- // setImmediate(dispatchCallbacks);
- if (typeof runtime.globalThis !== 'undefined') {
- runtime.globalThis.setTimeout(dispatchCallbacks);
- } else {
- dispatchCallbacks();
- }
- }
- }
- function dispatchCallbacks() {
- // http://dom.spec.whatwg.org/#mutation-observers
- isScheduled = false; // Used to allow a new setImmediate call above.
- var observers = scheduledObservers;
- scheduledObservers = [];
- // Sort observers based on their creation UID (incremental).
- observers.sort(function (o1, o2) {
- return o1.uid - o2.uid;
- });
- var anyNonEmpty = false;
- observers.forEach(function (observer) {
- // 2.1, 2.2
- var queue = observer.takeRecords();
- // 2.3. Remove all transient registered observers whose observer is mo.
- removeTransientObserversFor(observer);
- // 2.4
- if (queue.length) {
- // @ts-ignore
- observer.callback(queue, observer);
- anyNonEmpty = true;
- }
- });
- // 3.
- if (anyNonEmpty) dispatchCallbacks();
- }
- function _defineProperties$1(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, _toPropertyKey$1(descriptor.key), descriptor);
- }
- }
- function _createClass$1(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties$1(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", {
- writable: false
- });
- return Constructor;
- }
- function _inheritsLoose$2(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf$2(subClass, superClass);
- }
- function _setPrototypeOf$2(o, p) {
- _setPrototypeOf$2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf$2(o, p);
- }
- function _toPrimitive$1(input, hint) {
- if (typeof input !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (typeof res !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return (hint === "string" ? String : Number)(input);
- }
- function _toPropertyKey$1(arg) {
- var key = _toPrimitive$1(arg, "string");
- return typeof key === "symbol" ? key : String(key);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationPlaybackEvent
- */
- var AnimationEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose$2(AnimationEvent, _FederatedEvent);
- function AnimationEvent(manager, target, currentTime, timelineTime) {
- var _this;
- _this = _FederatedEvent.call(this, manager) || this;
- _this.currentTime = void 0;
- _this.timelineTime = void 0;
- _this.currentTime = currentTime;
- _this.timelineTime = timelineTime;
- // @ts-ignore
- _this.target = target;
- _this.type = 'finish';
- _this.bubbles = false;
- // @ts-ignore
- _this.currentTarget = target;
- _this.defaultPrevented = false;
- _this.eventPhase = _this.AT_TARGET;
- _this.timeStamp = Date.now();
- _this.currentTime = currentTime;
- _this.timelineTime = timelineTime;
- return _this;
- }
- return AnimationEvent;
- }(FederatedEvent);
- var sequenceNumber = 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/Animation
- */
- var Animation = /*#__PURE__*/function () {
- function Animation(effect, timeline) {
- var _this$effect;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/effect
- */
- this.effect = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/timeline
- */
- this.timeline = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/id
- */
- this.id = void 0;
- this.currentTimePending = false;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/playState
- */
- // playState: AnimationPlayState;
- this._idle = true;
- this._paused = false;
- this._finishedFlag = true;
- /**
- * record previos state
- */
- this.oldPlayState = void 0;
- this._holdTime = void 0;
- this.readyPromise = void 0;
- this.finishedPromise = void 0;
- // eslint-disable-next-line @typescript-eslint/ban-types
- this.resolveReadyPromise = void 0;
- // eslint-disable-next-line @typescript-eslint/ban-types
- this.rejectReadyPromise = void 0;
- // eslint-disable-next-line @typescript-eslint/ban-types
- this.resolveFinishedPromise = void 0;
- // eslint-disable-next-line @typescript-eslint/ban-types
- this.rejectFinishedPromise = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/onfinish
- */
- this.onfinish = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/oncancel
- */
- this.oncancel = void 0;
- /**
- * get called after each frame when running
- */
- this.onframe = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime
- */
- this._currentTime = 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/startTime
- */
- this._startTime = void 0;
- this._playbackRate = 1;
- this._totalDuration = void 0;
- this._inEffect = void 0;
- this._inTimeline = true;
- this.onremove = void 0;
- this.effect = effect;
- effect.animation = this;
- this.timeline = timeline;
- this.id = "" + sequenceNumber++;
- this._inEffect = !!this.effect.update(0);
- this._totalDuration = Number((_this$effect = this.effect) === null || _this$effect === void 0 ? void 0 : _this$effect.getComputedTiming().endTime);
- this._holdTime = 0;
- this._paused = false;
- this.oldPlayState = 'idle';
- this.updatePromises();
- }
- /**
- * state machine,
- * resolve/reject ready/finished Promise according to current state
- */
- var _proto = Animation.prototype;
- _proto.updatePromises = function updatePromises() {
- var oldPlayState = this.oldPlayState;
- var newPlayState = this.pending ? 'pending' : this.playState;
- if (this.readyPromise && newPlayState !== oldPlayState) {
- if (newPlayState === 'idle') {
- this.rejectReadyPromise();
- this.readyPromise = undefined;
- } else if (oldPlayState === 'pending') {
- this.resolveReadyPromise();
- } else if (newPlayState === 'pending') {
- this.readyPromise = undefined;
- }
- }
- if (this.finishedPromise && newPlayState !== oldPlayState) {
- if (newPlayState === 'idle') {
- this.rejectFinishedPromise();
- this.finishedPromise = undefined;
- } else if (newPlayState === 'finished') {
- this.resolveFinishedPromise();
- } else if (oldPlayState === 'finished') {
- this.finishedPromise = undefined;
- }
- }
- this.oldPlayState = newPlayState;
- return this.readyPromise || this.finishedPromise;
- };
- _proto.play = function play() {
- this.updatePromises();
- this._paused = false;
- if (this._isFinished || this._idle) {
- this.rewind();
- this._startTime = null;
- }
- this._finishedFlag = false;
- this._idle = false;
- this.ensureAlive();
- this.timeline.applyDirtiedAnimation(this);
- if (this.timeline.animations.indexOf(this) === -1) {
- this.timeline.animations.push(this);
- }
- this.updatePromises();
- };
- _proto.pause = function pause() {
- this.updatePromises();
- if (this.currentTime) {
- this._holdTime = this.currentTime;
- }
- if (!this._isFinished && !this._paused && !this._idle) {
- this.currentTimePending = true;
- } else if (this._idle) {
- this.rewind();
- this._idle = false;
- }
- this._startTime = null;
- this._paused = true;
- this.updatePromises();
- };
- _proto.finish = function finish() {
- this.updatePromises();
- if (this._idle) return;
- this.currentTime = this._playbackRate > 0 ? this._totalDuration : 0;
- this._startTime = this._totalDuration - this.currentTime;
- this.currentTimePending = false;
- this.timeline.applyDirtiedAnimation(this);
- this.updatePromises();
- };
- _proto.cancel = function cancel() {
- var _this = this;
- this.updatePromises();
- if (!this._inEffect) return;
- this._inEffect = false;
- this._idle = true;
- this._paused = false;
- this._finishedFlag = true;
- this._currentTime = 0;
- this._startTime = null;
- this.effect.update(null);
- // effects are invalid after cancellation as the animation state
- // needs to un-apply.
- this.timeline.applyDirtiedAnimation(this);
- this.updatePromises();
- /**
- * 1. Reject the current finished promise with a DOMException named "AbortError".
- * 2. Let current finished promise be a new promise
- * @see https://w3c.github.io/csswg-drafts/web-animations-1/#canceling-an-animation-section
- */
- // if (this.finishedPromise) {
- // this.rejectFinishedPromise();
- // this.finishedPromise = undefined;
- // }
- if (this.oncancel) {
- var event = new AnimationEvent(null, this, this.currentTime, null);
- setTimeout(function () {
- _this.oncancel(event);
- });
- }
- };
- _proto.reverse = function reverse() {
- this.updatePromises();
- var oldCurrentTime = this.currentTime;
- this.playbackRate *= -1;
- this.play();
- if (oldCurrentTime !== null) {
- this.currentTime = oldCurrentTime;
- }
- this.updatePromises();
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/updatePlaybackRate
- */;
- _proto.updatePlaybackRate = function updatePlaybackRate(playbackRate) {
- this.playbackRate = playbackRate;
- };
- _proto.targetAnimations = function targetAnimations() {
- var _this$effect2;
- var target = (_this$effect2 = this.effect) === null || _this$effect2 === void 0 ? void 0 : _this$effect2.target;
- return target.getAnimations();
- };
- _proto.markTarget = function markTarget() {
- var animations = this.targetAnimations();
- if (animations.indexOf(this) === -1) {
- animations.push(this);
- }
- };
- _proto.unmarkTarget = function unmarkTarget() {
- var animations = this.targetAnimations();
- var index = animations.indexOf(this);
- if (index !== -1) {
- animations.splice(index, 1);
- }
- };
- _proto.tick = function tick(timelineTime, isAnimationFrame) {
- if (!this._idle && !this._paused) {
- if (this._startTime === null) {
- if (isAnimationFrame) {
- this.startTime = timelineTime - this._currentTime / this.playbackRate;
- }
- } else if (!this._isFinished) {
- this.tickCurrentTime((timelineTime - this._startTime) * this.playbackRate);
- }
- }
- if (isAnimationFrame) {
- this.currentTimePending = false;
- this.fireEvents(timelineTime);
- }
- };
- _proto.rewind = function rewind() {
- if (this.playbackRate >= 0) {
- this.currentTime = 0;
- } else if (this._totalDuration < Infinity) {
- this.currentTime = this._totalDuration;
- } else {
- throw new Error('Unable to rewind negative playback rate animation with infinite duration');
- }
- };
- _proto.persist = function persist() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.addEventListener = function addEventListener(type, listener, options) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.removeEventListener = function removeEventListener(type, listener, options) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.dispatchEvent = function dispatchEvent(event) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- // replaceState: AnimationReplaceState;
- _proto.commitStyles = function commitStyles() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.ensureAlive = function ensureAlive() {
- // If an animation is playing backwards and is not fill backwards/both
- // then it should go out of effect when it reaches the start of its
- // active interval (currentTime === 0).
- if (this.playbackRate < 0 && this.currentTime === 0) {
- var _this$effect3;
- this._inEffect = !!((_this$effect3 = this.effect) === null || _this$effect3 === void 0 ? void 0 : _this$effect3.update(-1));
- } else {
- var _this$effect4;
- this._inEffect = !!((_this$effect4 = this.effect) === null || _this$effect4 === void 0 ? void 0 : _this$effect4.update(this.currentTime));
- }
- if (!this._inTimeline && (this._inEffect || !this._finishedFlag)) {
- this._inTimeline = true;
- this.timeline.animations.push(this);
- }
- };
- _proto.tickCurrentTime = function tickCurrentTime(newTime, ignoreLimit) {
- if (newTime !== this._currentTime) {
- this._currentTime = newTime;
- if (this._isFinished && !ignoreLimit) {
- this._currentTime = this._playbackRate > 0 ? this._totalDuration : 0;
- }
- this.ensureAlive();
- }
- };
- _proto.fireEvents = function fireEvents(baseTime) {
- var _this2 = this;
- if (this._isFinished) {
- if (!this._finishedFlag) {
- if (this.onfinish) {
- var event = new AnimationEvent(null, this, this.currentTime, baseTime);
- setTimeout(function () {
- if (_this2.onfinish) {
- _this2.onfinish(event);
- }
- });
- }
- this._finishedFlag = true;
- }
- } else {
- if (this.onframe && this.playState === 'running') {
- var _event = new AnimationEvent(null, this, this.currentTime, baseTime);
- this.onframe(_event);
- }
- this._finishedFlag = false;
- }
- };
- _createClass$1(Animation, [{
- key: "pending",
- get:
- // animation: InternalAnimation | null;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/pending
- */
- function get() {
- return this._startTime === null && !this._paused && this.playbackRate !== 0 || this.currentTimePending;
- }
- }, {
- key: "playState",
- get: function get() {
- if (this._idle) return 'idle';
- if (this._isFinished) return 'finished';
- if (this._paused) return 'paused';
- return 'running';
- }
- }, {
- key: "ready",
- get:
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/ready
- * @example
- animation.pause();
- animation.ready.then(function() {
- // Displays 'running'
- alert(animation.playState);
- });
- animation.play();
- */
- function get() {
- var _this3 = this;
- if (!this.readyPromise) {
- if (this.timeline.animationsWithPromises.indexOf(this) === -1) {
- this.timeline.animationsWithPromises.push(this);
- }
- this.readyPromise = new Promise(function (resolve, reject) {
- _this3.resolveReadyPromise = function () {
- resolve(_this3);
- };
- _this3.rejectReadyPromise = function () {
- reject(new Error());
- };
- });
- if (!this.pending) {
- this.resolveReadyPromise();
- }
- }
- return this.readyPromise;
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/finished
- * @example
- Promise.all(
- elem.getAnimations().map(
- function(animation) {
- return animation.finished
- }
- )
- ).then(
- function() {
- return elem.remove();
- }
- );
- */
- }, {
- key: "finished",
- get: function get() {
- var _this4 = this;
- if (!this.finishedPromise) {
- if (this.timeline.animationsWithPromises.indexOf(this) === -1) {
- this.timeline.animationsWithPromises.push(this);
- }
- this.finishedPromise = new Promise(function (resolve, reject) {
- _this4.resolveFinishedPromise = function () {
- resolve(_this4);
- };
- _this4.rejectFinishedPromise = function () {
- reject(new Error());
- };
- });
- if (this.playState === 'finished') {
- this.resolveFinishedPromise();
- }
- }
- return this.finishedPromise;
- }
- }, {
- key: "currentTime",
- get: function get() {
- this.updatePromises();
- return this._idle || this.currentTimePending ? null : this._currentTime;
- },
- set: function set(newTime) {
- newTime = Number(newTime);
- if (isNaN(newTime)) return;
- this.timeline.restart();
- if (!this._paused && this._startTime !== null) {
- var _this$timeline;
- this._startTime = Number((_this$timeline = this.timeline) === null || _this$timeline === void 0 ? void 0 : _this$timeline.currentTime) - newTime / this.playbackRate;
- }
- this.currentTimePending = false;
- if (this._currentTime === newTime) {
- return;
- }
- if (this._idle) {
- this._idle = false;
- this._paused = true;
- }
- this.tickCurrentTime(newTime, true);
- this.timeline.applyDirtiedAnimation(this);
- }
- }, {
- key: "startTime",
- get: function get() {
- return this._startTime;
- },
- set: function set(newTime) {
- if (newTime !== null) {
- this.updatePromises();
- newTime = Number(newTime);
- if (isNaN(newTime)) return;
- if (this._paused || this._idle) return;
- this._startTime = newTime;
- this.tickCurrentTime((Number(this.timeline.currentTime) - this._startTime) * this.playbackRate);
- this.timeline.applyDirtiedAnimation(this);
- this.updatePromises();
- }
- }
- }, {
- key: "playbackRate",
- get: function get() {
- return this._playbackRate;
- },
- set: function set(value) {
- if (value === this._playbackRate) {
- return;
- }
- this.updatePromises();
- var oldCurrentTime = this.currentTime;
- this._playbackRate = value;
- this.startTime = null;
- if (this.playState !== 'paused' && this.playState !== 'idle') {
- this._finishedFlag = false;
- this._idle = false;
- this.ensureAlive();
- this.timeline.applyDirtiedAnimation(this);
- }
- if (oldCurrentTime !== null) {
- this.currentTime = oldCurrentTime;
- }
- this.updatePromises();
- }
- }, {
- key: "_isFinished",
- get: function get() {
- return !this._idle && (this._playbackRate > 0 && Number(this._currentTime) >= this._totalDuration || this._playbackRate < 0 && Number(this._currentTime) <= 0);
- }
- }, {
- key: "totalDuration",
- get: function get() {
- return this._totalDuration;
- }
- }, {
- key: "_needsTick",
- get: function get() {
- return this.pending || this.playState === 'running' || !this._finishedFlag;
- }
- }]);
- return Animation;
- }();
- /**
- * https://github.com/gre/bezier-easing
- * BezierEasing - use bezier curve for transition easing function
- * by Gaëtan Renaudeau 2014 - 2015 – MIT License
- */
- // These values are established by empiricism with tests (tradeoff: performance VS precision)
- var NEWTON_ITERATIONS = 4;
- var NEWTON_MIN_SLOPE = 0.001;
- var SUBDIVISION_PRECISION = 0.0000001;
- var SUBDIVISION_MAX_ITERATIONS = 10;
- var kSplineTableSize = 11;
- var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
- var float32ArraySupported = typeof Float32Array === 'function';
- var A = function A(aA1, aA2) {
- return 1.0 - 3.0 * aA2 + 3.0 * aA1;
- };
- var B = function B(aA1, aA2) {
- return 3.0 * aA2 - 6.0 * aA1;
- };
- var C = function C(aA1) {
- return 3.0 * aA1;
- };
- // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
- var calcBezier = function calcBezier(aT, aA1, aA2) {
- return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
- };
- // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
- var getSlope = function getSlope(aT, aA1, aA2) {
- return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
- };
- var binarySubdivide = function binarySubdivide(aX, aA, aB, mX1, mX2) {
- var currentX,
- currentT,
- i = 0;
- do {
- currentT = aA + (aB - aA) / 2.0;
- currentX = calcBezier(currentT, mX1, mX2) - aX;
- if (currentX > 0.0) aB = currentT;else aA = currentT;
- } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
- return currentT;
- };
- var newtonRaphsonIterate = function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
- for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
- var currentSlope = getSlope(aGuessT, mX1, mX2);
- if (currentSlope === 0.0) return aGuessT;
- var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
- aGuessT -= currentX / currentSlope;
- }
- return aGuessT;
- };
- var bezier = function bezier(mX1, mY1, mX2, mY2) {
- if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) throw new Error('bezier x values must be in [0, 1] range');
- if (mX1 === mY1 && mX2 === mY2) return function (t) {
- return t;
- };
- // Precompute samples table
- var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
- for (var i = 0; i < kSplineTableSize; ++i) {
- sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
- }
- var getTForX = function getTForX(aX) {
- var intervalStart = 0.0;
- var currentSample = 1;
- var lastSample = kSplineTableSize - 1;
- for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) intervalStart += kSampleStepSize;
- --currentSample;
- // Interpolate to provide an initial guess for t
- var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
- var guessForT = intervalStart + dist * kSampleStepSize;
- var initialSlope = getSlope(guessForT, mX1, mX2);
- if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT, mX1, mX2);else if (initialSlope === 0.0) return guessForT;else {
- return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
- }
- };
- return function (t) {
- // Because JavaScript number are imprecise, we should guarantee the extremes are right.
- if (t === 0 || t === 1) return t;
- return calcBezier(getTForX(t), mY1, mY2);
- };
- };
- var convertToDash = function convertToDash(str) {
- str = str.replace(/([A-Z])/g, function (letter) {
- return "-" + letter.toLowerCase();
- });
- // Remove first dash
- return str.charAt(0) === '-' ? str.substring(1) : str;
- };
- /**
- Easing Functions from anime.js, they are tried and true, so, its better to use them instead of other alternatives
- */
- var Quad = function Quad(t) {
- return Math.pow(t, 2);
- };
- var Cubic = function Cubic(t) {
- return Math.pow(t, 3);
- };
- var Quart = function Quart(t) {
- return Math.pow(t, 4);
- };
- var Quint = function Quint(t) {
- return Math.pow(t, 5);
- };
- var Expo = function Expo(t) {
- return Math.pow(t, 6);
- };
- var Sine = function Sine(t) {
- return 1 - Math.cos(t * Math.PI / 2);
- };
- var Circ = function Circ(t) {
- return 1 - Math.sqrt(1 - t * t);
- };
- var Back = function Back(t) {
- return t * t * (3 * t - 2);
- };
- var Bounce = function Bounce(t) {
- var pow2,
- b = 4;
- while (t < ((pow2 = Math.pow(2, --b)) - 1) / 11) {}
- return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - t, 2);
- };
- var Elastic = function Elastic(t, params) {
- if (params === void 0) {
- params = [];
- }
- var _params = params,
- _params$ = _params[0],
- amplitude = _params$ === void 0 ? 1 : _params$,
- _params$2 = _params[1],
- period = _params$2 === void 0 ? 0.5 : _params$2;
- var a = clamp(Number(amplitude), 1, 10);
- var p = clamp(Number(period), 0.1, 2);
- if (t === 0 || t === 1) return t;
- return -a * Math.pow(2, 10 * (t - 1)) * Math.sin((t - 1 - p / (Math.PI * 2) * Math.asin(1 / a)) * (Math.PI * 2) / p);
- };
- var Spring = function Spring(t, params, duration) {
- if (params === void 0) {
- params = [];
- }
- var _params2 = params,
- _params2$ = _params2[0],
- mass = _params2$ === void 0 ? 1 : _params2$,
- _params2$2 = _params2[1],
- stiffness = _params2$2 === void 0 ? 100 : _params2$2,
- _params2$3 = _params2[2],
- damping = _params2$3 === void 0 ? 10 : _params2$3,
- _params2$4 = _params2[3],
- velocity = _params2$4 === void 0 ? 0 : _params2$4;
- mass = clamp(mass, 0.1, 1000);
- stiffness = clamp(stiffness, 0.1, 1000);
- damping = clamp(damping, 0.1, 1000);
- velocity = clamp(velocity, 0.1, 1000);
- var w0 = Math.sqrt(stiffness / mass);
- var zeta = damping / (2 * Math.sqrt(stiffness * mass));
- var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
- var a = 1;
- var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
- var progress = duration ? duration * t / 1000 : t;
- if (zeta < 1) {
- progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
- } else {
- progress = (a + b * progress) * Math.exp(-progress * w0);
- }
- if (t === 0 || t === 1) return t;
- return 1 - progress;
- };
- /**
- * Cache the durations at set easing parameters
- */
- // export const EasingDurationCache: Map<string | TypeEasingFunction, number> = new Map();
- /**
- * The threshold for an infinite loop
- */
- // const INTINITE_LOOP_LIMIT = 10000;
- /** Convert easing parameters to Array of numbers, e.g. "spring(2, 500)" to [2, 500] */
- // export const parseEasingParameters = (str: string) => {
- // const match = /(\(|\s)([^)]+)\)?/.exec(str);
- // return match
- // ? match[2].split(',').map((value) => {
- // const num = parseFloat(value);
- // return !Number.isNaN(num) ? num : value.trim();
- // })
- // : [];
- // };
- /**
- * The spring easing function will only look smooth at certain durations, with certain parameters.
- * This functions returns the optimal duration to create a smooth springy animation based on physics
- *
- * Note: it can also be used to determine the optimal duration of other types of easing function, but be careful of 'in-'
- * easing functions, because of the nature of the function it can sometimes create an infinite loop, I suggest only using
- * `getEasingDuration` for `spring`, specifically 'out-spring' and 'spring'
- */
- // export const getEasingDuration = (easing: string | TypeEasingFunction = 'spring') => {
- // if (EasingDurationCache.has(easing)) return EasingDurationCache.get(easing);
- // // eslint-disable-next-line @typescript-eslint/no-use-before-define
- // const easingFunction = typeof easing == 'function' ? easing : getEasingFunction(easing as string);
- // const params = typeof easing == 'function' ? [] : parseEasingParameters(easing);
- // const frame = 1 / 6;
- // let elapsed = 0;
- // let rest = 0;
- // let count = 0;
- // while (++count < INTINITE_LOOP_LIMIT) {
- // elapsed += frame;
- // if (easingFunction(elapsed, params, undefined) === 1) {
- // rest++;
- // if (rest >= 16) break;
- // } else {
- // rest = 0;
- // }
- // }
- // const duration = elapsed * frame * 1000;
- // EasingDurationCache.set(easing, duration);
- // return duration;
- // };
- /**
- These Easing Functions are based off of the Sozi Project's easing functions
- https://github.com/sozi-projects/Sozi/blob/d72e44ebd580dc7579d1e177406ad41e632f961d/src/js/player/Timing.js
- */
- var Steps = function Steps(t, params) {
- if (params === void 0) {
- params = [];
- }
- var _params3 = params,
- _params3$ = _params3[0],
- steps = _params3$ === void 0 ? 10 : _params3$,
- type = _params3[1];
- var trunc = type == 'start' ? Math.ceil : Math.floor;
- return trunc(clamp(t, 0, 1) * steps) / steps;
- };
- // @ts-ignore
- var Bezier = function Bezier(t, params) {
- if (params === void 0) {
- params = [];
- }
- var _params4 = params,
- mX1 = _params4[0],
- mY1 = _params4[1],
- mX2 = _params4[2],
- mY2 = _params4[3];
- return bezier(mX1, mY1, mX2, mY2)(t);
- };
- /** The default `ease-in` easing function */
- var easein = bezier(0.42, 0.0, 1.0, 1.0);
- /** Converts easing functions to their `out`counter parts */
- var EaseOut = function EaseOut(ease) {
- return function (t, params, duration) {
- if (params === void 0) {
- params = [];
- }
- return 1 - ease(1 - t, params, duration);
- };
- };
- /** Converts easing functions to their `in-out` counter parts */
- var EaseInOut = function EaseInOut(ease) {
- return function (t, params, duration) {
- if (params === void 0) {
- params = [];
- }
- return t < 0.5 ? ease(t * 2, params, duration) / 2 : 1 - ease(t * -2 + 2, params, duration) / 2;
- };
- };
- /** Converts easing functions to their `out-in` counter parts */
- var EaseOutIn = function EaseOutIn(ease) {
- return function (t, params, duration) {
- if (params === void 0) {
- params = [];
- }
- return t < 0.5 ? (1 - ease(1 - t * 2, params, duration)) / 2 : (ease(t * 2 - 1, params, duration) + 1) / 2;
- };
- };
- var EasingFunctions = {
- steps: Steps,
- 'step-start': function stepStart(t) {
- return Steps(t, [1, 'start']);
- },
- 'step-end': function stepEnd(t) {
- return Steps(t, [1, 'end']);
- },
- linear: function linear(t) {
- return t;
- },
- 'cubic-bezier': Bezier,
- ease: function ease(t) {
- return Bezier(t, [0.25, 0.1, 0.25, 1.0]);
- },
- in: easein,
- out: EaseOut(easein),
- 'in-out': EaseInOut(easein),
- 'out-in': EaseOutIn(easein),
- 'in-quad': Quad,
- 'out-quad': EaseOut(Quad),
- 'in-out-quad': EaseInOut(Quad),
- 'out-in-quad': EaseOutIn(Quad),
- 'in-cubic': Cubic,
- 'out-cubic': EaseOut(Cubic),
- 'in-out-cubic': EaseInOut(Cubic),
- 'out-in-cubic': EaseOutIn(Cubic),
- 'in-quart': Quart,
- 'out-quart': EaseOut(Quart),
- 'in-out-quart': EaseInOut(Quart),
- 'out-in-quart': EaseOutIn(Quart),
- 'in-quint': Quint,
- 'out-quint': EaseOut(Quint),
- 'in-out-quint': EaseInOut(Quint),
- 'out-in-quint': EaseOutIn(Quint),
- 'in-expo': Expo,
- 'out-expo': EaseOut(Expo),
- 'in-out-expo': EaseInOut(Expo),
- 'out-in-expo': EaseOutIn(Expo),
- 'in-sine': Sine,
- 'out-sine': EaseOut(Sine),
- 'in-out-sine': EaseInOut(Sine),
- 'out-in-sine': EaseOutIn(Sine),
- 'in-circ': Circ,
- 'out-circ': EaseOut(Circ),
- 'in-out-circ': EaseInOut(Circ),
- 'out-in-circ': EaseOutIn(Circ),
- 'in-back': Back,
- 'out-back': EaseOut(Back),
- 'in-out-back': EaseInOut(Back),
- 'out-in-back': EaseOutIn(Back),
- 'in-bounce': Bounce,
- 'out-bounce': EaseOut(Bounce),
- 'in-out-bounce': EaseInOut(Bounce),
- 'out-in-bounce': EaseOutIn(Bounce),
- 'in-elastic': Elastic,
- 'out-elastic': EaseOut(Elastic),
- 'in-out-elastic': EaseInOut(Elastic),
- 'out-in-elastic': EaseOutIn(Elastic),
- spring: Spring,
- 'spring-in': Spring,
- 'spring-out': EaseOut(Spring),
- 'spring-in-out': EaseInOut(Spring),
- 'spring-out-in': EaseOutIn(Spring)
- };
- /**
- * Convert string easing to their proper form
- */
- var complexEasingSyntax = function complexEasingSyntax(ease) {
- return convertToDash(ease).replace(/^ease-/, '') // Remove the "ease-" keyword
- .replace(/(\(|\s).+/, '') // Remove the function brackets and parameters
- .toLowerCase().trim();
- };
- /** Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. */
- var getEasingFunction = function getEasingFunction(ease) {
- return EasingFunctions[complexEasingSyntax(ease)] || EasingFunctions.linear;
- };
- // /**
- // * Allows you to register new easing functions
- // */
- // export const registerEasingFunction = (key: string, fn: TypeEasingFunction) => {
- // Object.assign(EasingFunctions, {
- // [key]: fn,
- // });
- // };
- // /**
- // * Allows you to register multiple new easing functions
- // */
- // export const registerEasingFunctions = (...obj: typeof EasingFunctions[]) => {
- // Object.assign(EasingFunctions, ...obj);
- // };
- var linear = function linear(x) {
- return x;
- };
- var Start = 1;
- var Middle = 0.5;
- var End = 0;
- function step(count, pos) {
- return function (x) {
- if (x >= 1) {
- return 1;
- }
- var stepSize = 1 / count;
- x += pos * stepSize;
- return x - x % stepSize;
- };
- }
- var numberString = '\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*';
- var cubicBezierRe = new RegExp('cubic-bezier\\(' + numberString + ',' + numberString + ',' + numberString + ',' + numberString + '\\)');
- var step1Re = /steps\(\s*(\d+)\s*\)/;
- var step2Re = /steps\(\s*(\d+)\s*,\s*(start|middle|end)\s*\)/;
- function parseEasingFunction(normalizedEasing) {
- var cubicData = cubicBezierRe.exec(normalizedEasing);
- if (cubicData) {
- // @ts-ignore
- return bezier.apply(void 0, cubicData.slice(1).map(Number));
- }
- var step1Data = step1Re.exec(normalizedEasing);
- if (step1Data) {
- return step(Number(step1Data[1]), End);
- }
- var step2Data = step2Re.exec(normalizedEasing);
- if (step2Data) {
- // @ts-ignore
- return step(Number(step2Data[1]), {
- start: Start,
- middle: Middle,
- end: End
- }[step2Data[2]]);
- }
- return getEasingFunction(normalizedEasing);
- }
- function calculateActiveDuration(timing) {
- // @ts-ignore
- return Math.abs(repeatedDuration(timing) / (timing.playbackRate || 1));
- }
- function repeatedDuration(timing) {
- var _timing$iterations;
- // https://drafts.csswg.org/web-animations/#calculating-the-active-duration
- if (timing.duration === 0 || timing.iterations === 0) {
- return 0;
- }
- // @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/duration#value
- // if (timing.duration === 'auto') {
- // timing.duration = 0;
- // }
- return (timing.duration === 'auto' ? 0 : Number(timing.duration)) * ((_timing$iterations = timing.iterations) !== null && _timing$iterations !== void 0 ? _timing$iterations : 1);
- }
- var PhaseNone = 0;
- var PhaseBefore = 1;
- var PhaseAfter = 2;
- var PhaseActive = 3;
- function calculatePhase(activeDuration, localTime, timing) {
- // https://drafts.csswg.org/web-animations/#animation-effect-phases-and-states
- if (localTime === null) {
- return PhaseNone;
- }
- var endTime = timing.endTime;
- if (localTime < Math.min(timing.delay, endTime)) {
- return PhaseBefore;
- }
- if (localTime >= Math.min(timing.delay + activeDuration + timing.endDelay, endTime)) {
- return PhaseAfter;
- }
- return PhaseActive;
- }
- function calculateActiveTime(activeDuration, fillMode, localTime, phase, delay) {
- // https://drafts.csswg.org/web-animations/#calculating-the-active-time
- switch (phase) {
- case PhaseBefore:
- if (fillMode === 'backwards' || fillMode === 'both') return 0;
- return null;
- case PhaseActive:
- return localTime - delay;
- case PhaseAfter:
- if (fillMode === 'forwards' || fillMode === 'both') return activeDuration;
- return null;
- case PhaseNone:
- return null;
- }
- }
- function calculateOverallProgress(iterationDuration, phase, iterations, activeTime, iterationStart) {
- // https://drafts.csswg.org/web-animations/#calculating-the-overall-progress
- var overallProgress = iterationStart;
- if (iterationDuration === 0) {
- if (phase !== PhaseBefore) {
- overallProgress += iterations;
- }
- } else {
- overallProgress += activeTime / iterationDuration;
- }
- return overallProgress;
- }
- function calculateSimpleIterationProgress(overallProgress, iterationStart, phase, iterations, activeTime, iterationDuration) {
- // https://drafts.csswg.org/web-animations/#calculating-the-simple-iteration-progress
- var simpleIterationProgress = overallProgress === Infinity ? iterationStart % 1 : overallProgress % 1;
- if (simpleIterationProgress === 0 && phase === PhaseAfter && iterations !== 0 && (activeTime !== 0 || iterationDuration === 0)) {
- simpleIterationProgress = 1;
- }
- return simpleIterationProgress;
- }
- function calculateCurrentIteration(phase, iterations, simpleIterationProgress, overallProgress) {
- // https://drafts.csswg.org/web-animations/#calculating-the-current-iteration
- if (phase === PhaseAfter && iterations === Infinity) {
- return Infinity;
- }
- if (simpleIterationProgress === 1) {
- return Math.floor(overallProgress) - 1;
- }
- return Math.floor(overallProgress);
- }
- function calculateDirectedProgress(playbackDirection, currentIteration, simpleIterationProgress) {
- // https://drafts.csswg.org/web-animations/#calculating-the-directed-progress
- var currentDirection = playbackDirection;
- if (playbackDirection !== 'normal' && playbackDirection !== 'reverse') {
- var d = currentIteration;
- if (playbackDirection === 'alternate-reverse') {
- d += 1;
- }
- currentDirection = 'normal';
- if (d !== Infinity && d % 2 !== 0) {
- currentDirection = 'reverse';
- }
- }
- if (currentDirection === 'normal') {
- return simpleIterationProgress;
- }
- return 1 - simpleIterationProgress;
- }
- function calculateIterationProgress(activeDuration, localTime, timing) {
- var phase = calculatePhase(activeDuration, localTime, timing);
- var activeTime = calculateActiveTime(activeDuration, timing.fill, localTime, phase, timing.delay);
- if (activeTime === null) return null;
- var duration = timing.duration === 'auto' ? 0 : timing.duration;
- var overallProgress = calculateOverallProgress(duration, phase, timing.iterations, activeTime, timing.iterationStart);
- var simpleIterationProgress = calculateSimpleIterationProgress(overallProgress, timing.iterationStart, phase, timing.iterations, activeTime, duration);
- var currentIteration = calculateCurrentIteration(phase, timing.iterations, simpleIterationProgress, overallProgress);
- var directedProgress = calculateDirectedProgress(timing.direction, currentIteration, simpleIterationProgress);
- timing.currentIteration = currentIteration;
- timing.progress = directedProgress;
- // https://drafts.csswg.org/web-animations/#calculating-the-transformed-progress
- // https://drafts.csswg.org/web-animations/#calculating-the-iteration-progress
- return timing.easingFunction(directedProgress);
- }
- function convertEffectInput(keyframes, timing, target) {
- var propertySpecificKeyframeGroups = makePropertySpecificKeyframeGroups(keyframes, timing);
- var interpolations = makeInterpolations(propertySpecificKeyframeGroups, target);
- return function (target, fraction) {
- if (fraction !== null) {
- interpolations.filter(function (interpolation) {
- return fraction >= interpolation.applyFrom && fraction < interpolation.applyTo;
- }).forEach(function (interpolation) {
- var offsetFraction = fraction - interpolation.startOffset;
- var localDuration = interpolation.endOffset - interpolation.startOffset;
- var scaledLocalTime = localDuration === 0 ? 0 : interpolation.easingFunction(offsetFraction / localDuration);
- // apply updated attribute
- target.setAttribute(interpolation.property, interpolation.interpolation(scaledLocalTime));
- // if (interpolation.property === 'visibility') {
- // console.log(
- // scaledLocalTime,
- // interpolation.interpolation(scaledLocalTime),
- // );
- // }
- });
- } else {
- for (var property in propertySpecificKeyframeGroups) if (isNotReservedWord(property)) {
- // clear attribute
- target.setAttribute(property, null);
- }
- }
- };
- }
- function isNotReservedWord(member) {
- return member !== 'offset' && member !== 'easing' && member !== 'composite' && member !== 'computedOffset';
- }
- function makePropertySpecificKeyframeGroups(keyframes, timing) {
- var propertySpecificKeyframeGroups = {};
- for (var i = 0; i < keyframes.length; i++) {
- for (var member in keyframes[i]) {
- if (isNotReservedWord(member)) {
- var propertySpecificKeyframe = {
- offset: keyframes[i].offset,
- computedOffset: keyframes[i].computedOffset,
- easing: keyframes[i].easing,
- easingFunction: parseEasingFunction(keyframes[i].easing) || timing.easingFunction,
- value: keyframes[i][member]
- };
- propertySpecificKeyframeGroups[member] = propertySpecificKeyframeGroups[member] || [];
- propertySpecificKeyframeGroups[member].push(propertySpecificKeyframe);
- }
- }
- }
- return propertySpecificKeyframeGroups;
- }
- function makeInterpolations(propertySpecificKeyframeGroups, target) {
- var interpolations = [];
- for (var groupName in propertySpecificKeyframeGroups) {
- var keyframes = propertySpecificKeyframeGroups[groupName];
- for (var i = 0; i < keyframes.length - 1; i++) {
- var startIndex = i;
- var endIndex = i + 1;
- var startOffset = keyframes[startIndex].computedOffset;
- var endOffset = keyframes[endIndex].computedOffset;
- var applyFrom = startOffset;
- var applyTo = endOffset;
- if (i === 0) {
- applyFrom = -Infinity;
- if (endOffset === 0) {
- endIndex = startIndex;
- }
- }
- if (i === keyframes.length - 2) {
- applyTo = Infinity;
- if (startOffset === 1) {
- startIndex = endIndex;
- }
- }
- interpolations.push({
- applyFrom: applyFrom,
- applyTo: applyTo,
- startOffset: keyframes[startIndex].computedOffset,
- endOffset: keyframes[endIndex].computedOffset,
- easingFunction: keyframes[startIndex].easingFunction,
- property: groupName,
- interpolation: propertyInterpolation(groupName, keyframes[startIndex].value, keyframes[endIndex].value, target)
- });
- }
- }
- interpolations.sort(function (leftInterpolation, rightInterpolation) {
- return leftInterpolation.startOffset - rightInterpolation.startOffset;
- });
- return interpolations;
- }
- var InterpolationFactory = function InterpolationFactory(from, to,
- // eslint-disable-next-line @typescript-eslint/ban-types
- convertToString) {
- return function (f) {
- var interpolated = interpolate(from, to, f);
- return !runtime.enableCSSParsing && isNumber(interpolated) ? interpolated : convertToString(interpolated);
- };
- };
- function propertyInterpolation(property, left, right, target) {
- var metadata = propertyMetadataCache[property];
- // discrete step
- // if (property === 'visibility') {
- // return function (t: number) {
- // if (t === 0) return left;
- // if (t === 1) return right;
- // debugger;
- // return t < 0.5 ? left : right;
- // };
- // }
- if (metadata && metadata.syntax && metadata.int) {
- var propertyHandler = runtime.styleValueRegistry.getPropertySyntax(metadata.syntax);
- if (propertyHandler) {
- var usedLeft;
- var usedRight;
- if (runtime.enableCSSParsing) {
- var computedLeft = runtime.styleValueRegistry.parseProperty(property, left, target);
- var computedRight = runtime.styleValueRegistry.parseProperty(property, right, target);
- usedLeft = runtime.styleValueRegistry.computeProperty(property, computedLeft, target);
- usedRight = runtime.styleValueRegistry.computeProperty(property, computedRight, target);
- } else {
- var parser = propertyHandler.parserWithCSSDisabled;
- usedLeft = parser ? parser(left, target) : left;
- usedRight = parser ? parser(right, target) : right;
- }
- // merger [left, right, n2string()]
- var interpolationArgs = propertyHandler.mixer(usedLeft, usedRight, target);
- if (interpolationArgs) {
- var interp = InterpolationFactory.apply(void 0, interpolationArgs);
- return function (t) {
- if (t === 0) return left;
- if (t === 1) return right;
- return interp(t);
- };
- }
- }
- }
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
- return InterpolationFactory(false, true, function (bool) {
- return bool ? right : left;
- });
- }
- /**
- * interpolate with number, boolean, number[], boolean[]
- */
- function interpolate(from, to, f) {
- if (typeof from === 'number' && typeof to === 'number') {
- return from * (1 - f) + to * f;
- }
- if (typeof from === 'boolean' && typeof to === 'boolean' || typeof from === 'string' && typeof to === 'string' // skip string, eg. path ['M', 10, 10]
- ) {
- return f < 0.5 ? from : to;
- }
- if (Array.isArray(from) && Array.isArray(to)) {
- // interpolate arrays/matrix
- var fromLength = from.length;
- var toLength = to.length;
- var length = Math.max(fromLength, toLength);
- var r = [];
- for (var i = 0; i < length; i++) {
- r.push(interpolate(from[i < fromLength ? i : fromLength - 1], to[i < toLength ? i : toLength - 1], f));
- }
- return r;
- }
- throw new Error('Mismatched interpolation arguments ' + from + ':' + to);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming
- */
- var AnimationEffectTiming = /*#__PURE__*/function () {
- function AnimationEffectTiming() {
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/delay
- */
- this.delay = 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/direction
- */
- this.direction = 'normal';
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/duration
- */
- this.duration = 'auto';
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing
- */
- this._easing = 'linear';
- this.easingFunction = linear;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/endDelay
- */
- this.endDelay = 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill
- */
- this.fill = 'auto';
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/iterationStart
- */
- this.iterationStart = 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/iterations
- */
- this.iterations = 1;
- /**
- * @deprecated
- */
- this.playbackRate = void 0;
- /**
- * ref to effect
- */
- this.effect = void 0;
- this.composite = void 0;
- /**
- * ComputedEffectTiming
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/getComputedTiming
- */
- this.activeDuration = void 0;
- this.endTime = void 0;
- this.currentIteration = null;
- this.progress = null;
- }
- _createClass$1(AnimationEffectTiming, [{
- key: "easing",
- get: function get() {
- return this._easing;
- },
- set: function set(value) {
- this.easingFunction = parseEasingFunction(value);
- this._easing = value;
- }
- }]);
- return AnimationEffectTiming;
- }();
- /**
- * @example
- {
- translateY: [200, 300],
- scale: [1, 10],
- }
- * groups' length can be different, the following config should generate 3 frames:
- @example
- {
- translateY: [200, 300, 400],
- scale: [1, 10],
- }
- */
- function convertToArrayForm(effectInput) {
- var normalizedEffectInput = [];
- for (var property in effectInput) {
- // skip reserved props
- if (property in ['easing', 'offset', 'composite']) {
- continue;
- }
- // @ts-ignore
- var values = effectInput[property];
- if (!Array.isArray(values)) {
- values = [values];
- }
- var numKeyframes = values.length;
- for (var i = 0; i < numKeyframes; i++) {
- if (!normalizedEffectInput[i]) {
- var keyframe = {};
- if ('offset' in effectInput) {
- keyframe.offset = Number(effectInput.offset);
- }
- if ('easing' in effectInput) {
- // @ts-ignore
- keyframe.easing = effectInput.easing;
- }
- if ('composite' in effectInput) {
- // @ts-ignore
- keyframe.composite = effectInput.composite;
- }
- normalizedEffectInput[i] = keyframe;
- }
- if (values[i] !== undefined && values[i] !== null) {
- normalizedEffectInput[i][property] = values[i];
- }
- }
- }
- normalizedEffectInput.sort(function (a, b) {
- return (a.computedOffset || 0) - (b.computedOffset || 0);
- });
- return normalizedEffectInput;
- }
- function normalizeKeyframes(effectInput, timing) {
- if (effectInput === null) {
- return [];
- }
- if (!Array.isArray(effectInput)) {
- effectInput = convertToArrayForm(effectInput);
- }
- var keyframes = effectInput.map(function (originalKeyframe) {
- var keyframe = {};
- if (timing === null || timing === void 0 ? void 0 : timing.composite) {
- // This will be auto if the composite operation specified on the effect is being used.
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats
- keyframe.composite = 'auto';
- }
- for (var member in originalKeyframe) {
- var memberValue = originalKeyframe[member];
- if (member === 'offset') {
- if (memberValue !== null) {
- memberValue = Number(memberValue);
- if (!isFinite(memberValue)) throw new Error('Keyframe offsets must be numbers.');
- if (memberValue < 0 || memberValue > 1) throw new Error('Keyframe offsets must be between 0 and 1.');
- keyframe.computedOffset = memberValue;
- }
- } else if (member === 'composite') {
- // TODO: Support add & accumulate in KeyframeEffect.composite
- // @see https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/composite
- if (['replace', 'add', 'accumulate', 'auto'].indexOf(memberValue) === -1) {
- throw new Error(memberValue + " compositing is not supported");
- }
- } else ;
- // assign to keyframe, no need to parse shorthand value
- keyframe[member] = memberValue;
- }
- if (keyframe.offset === undefined) {
- keyframe.offset = null;
- }
- if (keyframe.easing === undefined) {
- // override with timing.easing
- keyframe.easing = (timing === null || timing === void 0 ? void 0 : timing.easing) || 'linear';
- }
- if (keyframe.composite === undefined) {
- keyframe.composite = 'auto';
- }
- return keyframe;
- });
- var everyFrameHasOffset = true;
- var previousOffset = -Infinity;
- for (var i = 0; i < keyframes.length; i++) {
- var offset = keyframes[i].offset;
- if (!isNil(offset)) {
- if (offset < previousOffset) {
- throw new TypeError('Keyframes are not loosely sorted by offset. Sort or specify offsets.');
- }
- previousOffset = offset;
- } else {
- everyFrameHasOffset = false;
- }
- }
- keyframes = keyframes.filter(function (keyframe) {
- return Number(keyframe.offset) >= 0 && Number(keyframe.offset) <= 1;
- });
- function spaceKeyframes() {
- var _keyframes$offset;
- var length = keyframes.length;
- keyframes[length - 1].computedOffset = Number((_keyframes$offset = keyframes[length - 1].offset) !== null && _keyframes$offset !== void 0 ? _keyframes$offset : 1);
- if (length > 1) {
- var _keyframes$0$offset;
- keyframes[0].computedOffset = Number((_keyframes$0$offset = keyframes[0].offset) !== null && _keyframes$0$offset !== void 0 ? _keyframes$0$offset : 0);
- }
- var previousIndex = 0;
- var previousOffset = Number(keyframes[0].computedOffset);
- for (var _i = 1; _i < length; _i++) {
- var _offset = keyframes[_i].computedOffset;
- if (!isNil(_offset) && !isNil(previousOffset)) {
- for (var j = 1; j < _i - previousIndex; j++) keyframes[previousIndex + j].computedOffset = previousOffset + (Number(_offset) - previousOffset) * j / (_i - previousIndex);
- previousIndex = _i;
- previousOffset = Number(_offset);
- }
- }
- }
- if (!everyFrameHasOffset) spaceKeyframes();
- return keyframes;
- }
- var fills = 'backwards|forwards|both|none'.split('|');
- var directions = 'reverse|alternate|alternate-reverse'.split('|');
- function makeTiming(timingInput, forGroup) {
- var timing = new AnimationEffectTiming();
- if (forGroup) {
- timing.fill = 'both';
- timing.duration = 'auto';
- }
- if (typeof timingInput === 'number' && !isNaN(timingInput)) {
- timing.duration = timingInput;
- } else if (timingInput !== undefined) {
- Object.keys(timingInput).forEach(function (property) {
- if (timingInput[property] !== undefined && timingInput[property] !== null && timingInput[property] !== 'auto') {
- if (typeof timing[property] === 'number' || property === 'duration') {
- if (typeof timingInput[property] !== 'number' || isNaN(timingInput[property])) {
- return;
- }
- }
- if (property === 'fill' && fills.indexOf(timingInput[property]) === -1) {
- return;
- }
- if (property === 'direction' && directions.indexOf(timingInput[property]) === -1) {
- return;
- }
- // @ts-ignore
- timing[property] = timingInput[property];
- }
- });
- }
- return timing;
- }
- function normalizeTimingInput(timingInput, forGroup) {
- var _timingInput;
- timingInput = numericTimingToObject((_timingInput = timingInput) !== null && _timingInput !== void 0 ? _timingInput : {
- duration: 'auto'
- });
- return makeTiming(timingInput, forGroup);
- }
- function numericTimingToObject(timingInput) {
- if (typeof timingInput === 'number') {
- if (isNaN(timingInput)) {
- timingInput = {
- duration: 'auto'
- };
- } else {
- timingInput = {
- duration: timingInput
- };
- }
- }
- return timingInput;
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect
- * @example
- const circleDownKeyframes = new KeyframeEffect(
- circle, // element to animate
- [
- { transform: 'translateY(0)' }, // keyframe
- { transform: 'translateY(100)' } // keyframe
- ],
- { duration: 3000, fill: 'forwards' } // keyframe options
- );
- *
- */
- var KeyframeEffect = /*#__PURE__*/function () {
- function KeyframeEffect(target, effectInput, timingInput) {
- var _this = this;
- this.composite = 'replace';
- this.iterationComposite = 'replace';
- // pseudoElement: string | null;
- this.target = void 0;
- this.animation = void 0;
- this.timing = void 0;
- this.computedTiming = void 0;
- this.normalizedKeyframes = void 0;
- this.timeFraction = void 0;
- this.interpolations = void 0;
- this.target = target;
- this.timing = normalizeTimingInput(timingInput, false);
- this.timing.effect = this;
- this.timing.activeDuration = calculateActiveDuration(this.timing);
- this.timing.endTime = Math.max(0, this.timing.delay + this.timing.activeDuration + this.timing.endDelay);
- this.normalizedKeyframes = normalizeKeyframes(effectInput, this.timing);
- this.interpolations = convertEffectInput(this.normalizedKeyframes, this.timing, this.target);
- // 不支持 proxy 时降级成 this.timing
- var Proxy = runtime.globalThis.Proxy;
- this.computedTiming = Proxy ? new Proxy(this.timing, {
- get: function get(target, prop) {
- if (prop === 'duration') {
- return target.duration === 'auto' ? 0 : target.duration;
- } else if (prop === 'fill') {
- return target.fill === 'auto' ? 'none' : target.fill;
- } else if (prop === 'localTime') {
- return _this.animation && _this.animation.currentTime || null;
- } else if (prop === 'currentIteration') {
- if (!_this.animation || _this.animation.playState !== 'running') {
- return null;
- }
- return target.currentIteration || 0;
- } else if (prop === 'progress') {
- if (!_this.animation || _this.animation.playState !== 'running') {
- return null;
- }
- return target.progress || 0;
- }
- return target[prop];
- },
- set: function set() {
- return true;
- }
- }) : this.timing;
- }
- var _proto = KeyframeEffect.prototype;
- _proto.applyInterpolations = function applyInterpolations() {
- this.interpolations(this.target, Number(this.timeFraction));
- };
- _proto.update = function update(localTime) {
- if (localTime === null) {
- return false;
- }
- this.timeFraction = calculateIterationProgress(this.timing.activeDuration, localTime, this.timing);
- return this.timeFraction !== null;
- };
- _proto.getKeyframes = function getKeyframes() {
- return this.normalizedKeyframes;
- };
- _proto.setKeyframes = function setKeyframes(keyframes) {
- this.normalizedKeyframes = normalizeKeyframes(keyframes);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/getComputedTiming
- */;
- _proto.getComputedTiming = function getComputedTiming() {
- return this.computedTiming;
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/getTiming
- */;
- _proto.getTiming = function getTiming() {
- return this.timing;
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/updateTiming
- */;
- _proto.updateTiming = function updateTiming(timing) {
- var _this2 = this;
- Object.keys(timing || {}).forEach(function (name) {
- _this2.timing[name] = timing[name];
- });
- };
- return KeyframeEffect;
- }();
- function compareAnimations(leftAnimation, rightAnimation) {
- return Number(leftAnimation.id) - Number(rightAnimation.id);
- }
- /**
- * @see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/web-animations-js/index.d.ts
- */
- var AnimationTimeline = /*#__PURE__*/function () {
- function AnimationTimeline(document) {
- var _this = this;
- this.document = void 0;
- /**
- * all active animations
- */
- this.animations = [];
- this.ticking = false;
- this.timelineTicking = false;
- this.hasRestartedThisFrame = false;
- this.animationsWithPromises = [];
- this.inTick = false;
- this.pendingEffects = [];
- this.currentTime = null;
- this.rafId = 0;
- this.rafCallbacks = [];
- this.frameId = void 0;
- this.webAnimationsNextTick = function (t) {
- _this.currentTime = t;
- _this.discardAnimations();
- if (_this.animations.length === 0) {
- _this.timelineTicking = false;
- } else {
- _this.requestAnimationFrame(_this.webAnimationsNextTick);
- }
- };
- this.processRafCallbacks = function (t) {
- var processing = _this.rafCallbacks;
- _this.rafCallbacks = [];
- if (t < Number(_this.currentTime)) t = Number(_this.currentTime);
- _this.animations.sort(compareAnimations);
- _this.animations = _this.tick(t, true, _this.animations)[0];
- processing.forEach(function (entry) {
- entry[1](t);
- });
- _this.applyPendingEffects();
- };
- this.document = document;
- }
- var _proto = AnimationTimeline.prototype;
- _proto.getAnimations = function getAnimations() {
- this.discardAnimations();
- return this.animations.slice();
- };
- _proto.isTicking = function isTicking() {
- return this.inTick;
- };
- _proto.play = function play(target, keyframes, options) {
- var effect = new KeyframeEffect(target, keyframes, options);
- var animation = new Animation(effect, this);
- this.animations.push(animation);
- this.restartWebAnimationsNextTick();
- animation.updatePromises();
- animation.play();
- animation.updatePromises();
- return animation;
- }
- // RAF is supposed to be the last script to occur before frame rendering but not
- // all browsers behave like this. This function is for synchonously updating an
- // animation's effects whenever its state is mutated by script to work around
- // incorrect script execution ordering by the browser.
- ;
- _proto.applyDirtiedAnimation = function applyDirtiedAnimation(animation) {
- var _this2 = this;
- if (this.inTick) {
- return;
- }
- // update active animations in displayobject
- animation.markTarget();
- var animations = animation.targetAnimations();
- animations.sort(compareAnimations);
- // clear inactive animations
- var inactiveAnimations = this.tick(Number(this.currentTime), false, animations.slice())[1];
- inactiveAnimations.forEach(function (animation) {
- var index = _this2.animations.indexOf(animation);
- if (index !== -1) {
- _this2.animations.splice(index, 1);
- }
- });
- this.applyPendingEffects();
- };
- _proto.restart = function restart() {
- if (!this.ticking) {
- this.ticking = true;
- this.requestAnimationFrame(function () {});
- this.hasRestartedThisFrame = true;
- }
- return this.hasRestartedThisFrame;
- };
- _proto.destroy = function destroy() {
- this.document.defaultView.cancelAnimationFrame(this.frameId);
- };
- _proto.applyPendingEffects = function applyPendingEffects() {
- this.pendingEffects.forEach(function (effect) {
- effect === null || effect === void 0 ? void 0 : effect.applyInterpolations();
- });
- this.pendingEffects = [];
- };
- _proto.updateAnimationsPromises = function updateAnimationsPromises() {
- this.animationsWithPromises = this.animationsWithPromises.filter(function (animation) {
- return animation.updatePromises();
- });
- };
- _proto.discardAnimations = function discardAnimations() {
- this.updateAnimationsPromises();
- this.animations = this.animations.filter(function (animation) {
- return animation.playState !== 'finished' && animation.playState !== 'idle';
- });
- };
- _proto.restartWebAnimationsNextTick = function restartWebAnimationsNextTick() {
- if (!this.timelineTicking) {
- this.timelineTicking = true;
- this.requestAnimationFrame(this.webAnimationsNextTick);
- }
- };
- _proto.rAF = function rAF(f) {
- var id = this.rafId++;
- if (this.rafCallbacks.length === 0) {
- this.frameId = this.document.defaultView.requestAnimationFrame(this.processRafCallbacks);
- }
- this.rafCallbacks.push([id, f]);
- return id;
- };
- _proto.requestAnimationFrame = function requestAnimationFrame(f) {
- var _this3 = this;
- return this.rAF(function (x) {
- _this3.updateAnimationsPromises();
- f(x);
- _this3.updateAnimationsPromises();
- });
- };
- _proto.tick = function tick(t, isAnimationFrame, updatingAnimations) {
- var _this4 = this,
- _this$pendingEffects,
- _this$pendingEffects2;
- this.inTick = true;
- this.hasRestartedThisFrame = false;
- this.currentTime = t;
- this.ticking = false;
- var newPendingClears = [];
- var newPendingEffects = [];
- var activeAnimations = [];
- var inactiveAnimations = [];
- updatingAnimations.forEach(function (animation) {
- animation.tick(t, isAnimationFrame);
- if (!animation._inEffect) {
- newPendingClears.push(animation.effect);
- animation.unmarkTarget();
- } else {
- newPendingEffects.push(animation.effect);
- animation.markTarget();
- }
- if (animation._needsTick) _this4.ticking = true;
- var alive = animation._inEffect || animation._needsTick;
- animation._inTimeline = alive;
- if (alive) {
- activeAnimations.push(animation);
- } else {
- inactiveAnimations.push(animation);
- }
- });
- (_this$pendingEffects = this.pendingEffects).push.apply(_this$pendingEffects, newPendingClears);
- (_this$pendingEffects2 = this.pendingEffects).push.apply(_this$pendingEffects2, newPendingEffects);
- if (this.ticking) this.requestAnimationFrame(function () {});
- this.inTick = false;
- return [activeAnimations, inactiveAnimations];
- };
- return AnimationTimeline;
- }();
- runtime.EasingFunction = parseEasingFunction;
- runtime.AnimationTimeline = AnimationTimeline;
- exports.AABB = AABB;
- exports.AbstractRenderer = AbstractRenderer;
- exports.AbstractRendererPlugin = AbstractRendererPlugin;
- exports.AdvancedCamera = AdvancedCamera;
- exports.Animation = Animation;
- exports.AnimationEvent = AnimationEvent;
- exports.AnimationTimeline = AnimationTimeline;
- exports.BUILT_IN_PROPERTIES = BUILT_IN_PROPERTIES;
- exports.CSS = CSS;
- exports.CSSGradientValue = CSSGradientValue;
- exports.CSSKeywordValue = CSSKeywordValue;
- exports.CSSRGB = CSSRGB;
- exports.CSSStyleValue = CSSStyleValue;
- exports.CSSUnitValue = CSSUnitValue;
- exports.Camera = Camera;
- exports.CameraEvent = CameraEvent;
- exports.Canvas = Canvas;
- exports.Circle = Circle;
- exports.CircleUpdater = CircleUpdater;
- exports.CustomElement = CustomElement;
- exports.CustomElementRegistry = CustomElementRegistry;
- exports.CustomEvent = CustomEvent;
- exports.DefaultSceneGraphSelector = DefaultSceneGraphSelector;
- exports.DefaultSceneGraphService = DefaultSceneGraphService;
- exports.DisplayObject = DisplayObject;
- exports.Document = Document;
- exports.EMPTY_PARSED_PATH = EMPTY_PARSED_PATH;
- exports.ERROR_MSG_METHOD_NOT_IMPLEMENTED = ERROR_MSG_METHOD_NOT_IMPLEMENTED;
- exports.Element = Element;
- exports.Ellipse = Ellipse;
- exports.EllipseUpdater = EllipseUpdater;
- exports.EventService = EventService;
- exports.EventTarget = EventTarget;
- exports.FederatedEvent = FederatedEvent;
- exports.FederatedMouseEvent = FederatedMouseEvent;
- exports.FederatedPointerEvent = FederatedPointerEvent;
- exports.FederatedWheelEvent = FederatedWheelEvent;
- exports.Frustum = Frustum;
- exports.Group = Group;
- exports.HTML = HTML;
- exports.Image = Image;
- exports.KeyframeEffect = KeyframeEffect;
- exports.Line = Line;
- exports.LineUpdater = LineUpdater;
- exports.MutationEvent = MutationEvent;
- exports.MutationObserver = MutationObserver;
- exports.MutationRecord = MutationRecord;
- exports.Node = Node;
- exports.OffscreenCanvasCreator = OffscreenCanvasCreator;
- exports.Path = Path;
- exports.PathUpdater = PathUpdater;
- exports.Plane = Plane;
- exports.Point = Point;
- exports.Polygon = Polygon;
- exports.Polyline = Polyline;
- exports.PolylineUpdater = PolylineUpdater;
- exports.RBush = rbush;
- exports.Rect = Rect;
- exports.RectUpdater = RectUpdater;
- exports.Rectangle = Rectangle;
- exports.Registration = Registration;
- exports.RenderingService = RenderingService;
- exports.Text = Text;
- exports.TextService = TextService;
- exports.TextUpdater = TextUpdater;
- exports.compareAnimations = compareAnimations;
- exports.computeLinearGradient = computeLinearGradient;
- exports.computeRadialGradient = computeRadialGradient;
- exports.convertToPath = convertToPath;
- exports.createVec3 = createVec3;
- exports.decompose = decompose;
- exports.definedProps = definedProps;
- exports.deg2rad = deg2rad;
- exports.deg2turn = deg2turn;
- exports.findClosestClipPathTarget = findClosestClipPathTarget;
- exports.fromRotationTranslationScale = fromRotationTranslationScale$1;
- exports.getAngle = getAngle$1;
- exports.getEuler = getEuler;
- exports.getOrCalculatePathTotalLength = getOrCalculatePathTotalLength;
- exports.grad2deg = grad2deg;
- exports.isBrowser = isBrowser;
- exports.isCSSGradientValue = isCSSGradientValue;
- exports.isCSSRGB = isCSSRGB;
- exports.isCanvas = isCanvas;
- exports.isDisplayObject = isDisplayObject;
- exports.isFederatedEvent = isFederatedEvent;
- exports.isFillOrStrokeAffected = isFillOrStrokeAffected;
- exports.isPattern = isPattern;
- exports.makeTiming = makeTiming;
- exports.mergeColors = mergeColors;
- exports.normalizeKeyframes = normalizeKeyframes;
- exports.normalizeTimingInput = normalizeTimingInput;
- exports.numericTimingToObject = numericTimingToObject;
- exports.parseColor = parseColor;
- exports.parseLength = parseLength;
- exports.parsePath = parsePath;
- exports.parseTransform = parseTransform;
- exports.parsedTransformToMat4 = parsedTransformToMat4;
- exports.propertyMetadataCache = propertyMetadataCache;
- exports.rad2deg = rad2deg;
- exports.resetEntityCounter = resetEntityCounter;
- exports.runtime = runtime;
- exports.setDOMSize = setDOMSize;
- exports.translatePathToString = translatePathToString;
- exports.turn2deg = turn2deg;
- Object.defineProperty(exports, '__esModule', { value: true });
- })));
|