three.cjs 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. Object.defineProperty(exports, '__esModule', { value: true });
  8. const REVISION = '144dev';
  9. const MOUSE = {
  10. LEFT: 0,
  11. MIDDLE: 1,
  12. RIGHT: 2,
  13. ROTATE: 0,
  14. DOLLY: 1,
  15. PAN: 2
  16. };
  17. const TOUCH = {
  18. ROTATE: 0,
  19. PAN: 1,
  20. DOLLY_PAN: 2,
  21. DOLLY_ROTATE: 3
  22. };
  23. const CullFaceNone = 0;
  24. const CullFaceBack = 1;
  25. const CullFaceFront = 2;
  26. const CullFaceFrontBack = 3;
  27. const BasicShadowMap = 0;
  28. const PCFShadowMap = 1;
  29. const PCFSoftShadowMap = 2;
  30. const VSMShadowMap = 3;
  31. const FrontSide = 0;
  32. const BackSide = 1;
  33. const DoubleSide = 2;
  34. const NoBlending = 0;
  35. const NormalBlending = 1;
  36. const AdditiveBlending = 2;
  37. const SubtractiveBlending = 3;
  38. const MultiplyBlending = 4;
  39. const CustomBlending = 5;
  40. const AddEquation = 100;
  41. const SubtractEquation = 101;
  42. const ReverseSubtractEquation = 102;
  43. const MinEquation = 103;
  44. const MaxEquation = 104;
  45. const ZeroFactor = 200;
  46. const OneFactor = 201;
  47. const SrcColorFactor = 202;
  48. const OneMinusSrcColorFactor = 203;
  49. const SrcAlphaFactor = 204;
  50. const OneMinusSrcAlphaFactor = 205;
  51. const DstAlphaFactor = 206;
  52. const OneMinusDstAlphaFactor = 207;
  53. const DstColorFactor = 208;
  54. const OneMinusDstColorFactor = 209;
  55. const SrcAlphaSaturateFactor = 210;
  56. const NeverDepth = 0;
  57. const AlwaysDepth = 1;
  58. const LessDepth = 2;
  59. const LessEqualDepth = 3;
  60. const EqualDepth = 4;
  61. const GreaterEqualDepth = 5;
  62. const GreaterDepth = 6;
  63. const NotEqualDepth = 7;
  64. const MultiplyOperation = 0;
  65. const MixOperation = 1;
  66. const AddOperation = 2;
  67. const NoToneMapping = 0;
  68. const LinearToneMapping = 1;
  69. const ReinhardToneMapping = 2;
  70. const CineonToneMapping = 3;
  71. const ACESFilmicToneMapping = 4;
  72. const CustomToneMapping = 5;
  73. const UVMapping = 300;
  74. const CubeReflectionMapping = 301;
  75. const CubeRefractionMapping = 302;
  76. const EquirectangularReflectionMapping = 303;
  77. const EquirectangularRefractionMapping = 304;
  78. const CubeUVReflectionMapping = 306;
  79. const RepeatWrapping = 1000;
  80. const ClampToEdgeWrapping = 1001;
  81. const MirroredRepeatWrapping = 1002;
  82. const NearestFilter = 1003;
  83. const NearestMipmapNearestFilter = 1004;
  84. const NearestMipMapNearestFilter = 1004;
  85. const NearestMipmapLinearFilter = 1005;
  86. const NearestMipMapLinearFilter = 1005;
  87. const LinearFilter = 1006;
  88. const LinearMipmapNearestFilter = 1007;
  89. const LinearMipMapNearestFilter = 1007;
  90. const LinearMipmapLinearFilter = 1008;
  91. const LinearMipMapLinearFilter = 1008;
  92. const UnsignedByteType = 1009;
  93. const ByteType = 1010;
  94. const ShortType = 1011;
  95. const UnsignedShortType = 1012;
  96. const IntType = 1013;
  97. const UnsignedIntType = 1014;
  98. const FloatType = 1015;
  99. const HalfFloatType = 1016;
  100. const UnsignedShort4444Type = 1017;
  101. const UnsignedShort5551Type = 1018;
  102. const UnsignedInt248Type = 1020;
  103. const AlphaFormat = 1021;
  104. const RGBFormat = 1022; // @deprecated since r137
  105. const RGBAFormat = 1023;
  106. const LuminanceFormat = 1024;
  107. const LuminanceAlphaFormat = 1025;
  108. const DepthFormat = 1026;
  109. const DepthStencilFormat = 1027;
  110. const RedFormat = 1028;
  111. const RedIntegerFormat = 1029;
  112. const RGFormat = 1030;
  113. const RGIntegerFormat = 1031;
  114. const RGBAIntegerFormat = 1033;
  115. const RGB_S3TC_DXT1_Format = 33776;
  116. const RGBA_S3TC_DXT1_Format = 33777;
  117. const RGBA_S3TC_DXT3_Format = 33778;
  118. const RGBA_S3TC_DXT5_Format = 33779;
  119. const RGB_PVRTC_4BPPV1_Format = 35840;
  120. const RGB_PVRTC_2BPPV1_Format = 35841;
  121. const RGBA_PVRTC_4BPPV1_Format = 35842;
  122. const RGBA_PVRTC_2BPPV1_Format = 35843;
  123. const RGB_ETC1_Format = 36196;
  124. const RGB_ETC2_Format = 37492;
  125. const RGBA_ETC2_EAC_Format = 37496;
  126. const RGBA_ASTC_4x4_Format = 37808;
  127. const RGBA_ASTC_5x4_Format = 37809;
  128. const RGBA_ASTC_5x5_Format = 37810;
  129. const RGBA_ASTC_6x5_Format = 37811;
  130. const RGBA_ASTC_6x6_Format = 37812;
  131. const RGBA_ASTC_8x5_Format = 37813;
  132. const RGBA_ASTC_8x6_Format = 37814;
  133. const RGBA_ASTC_8x8_Format = 37815;
  134. const RGBA_ASTC_10x5_Format = 37816;
  135. const RGBA_ASTC_10x6_Format = 37817;
  136. const RGBA_ASTC_10x8_Format = 37818;
  137. const RGBA_ASTC_10x10_Format = 37819;
  138. const RGBA_ASTC_12x10_Format = 37820;
  139. const RGBA_ASTC_12x12_Format = 37821;
  140. const RGBA_BPTC_Format = 36492;
  141. const LoopOnce = 2200;
  142. const LoopRepeat = 2201;
  143. const LoopPingPong = 2202;
  144. const InterpolateDiscrete = 2300;
  145. const InterpolateLinear = 2301;
  146. const InterpolateSmooth = 2302;
  147. const ZeroCurvatureEnding = 2400;
  148. const ZeroSlopeEnding = 2401;
  149. const WrapAroundEnding = 2402;
  150. const NormalAnimationBlendMode = 2500;
  151. const AdditiveAnimationBlendMode = 2501;
  152. const TrianglesDrawMode = 0;
  153. const TriangleStripDrawMode = 1;
  154. const TriangleFanDrawMode = 2;
  155. const LinearEncoding = 3000;
  156. const sRGBEncoding = 3001;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const TangentSpaceNormalMap = 0;
  160. const ObjectSpaceNormalMap = 1; // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  161. const NoColorSpace = '';
  162. const SRGBColorSpace = 'srgb';
  163. const LinearSRGBColorSpace = 'srgb-linear';
  164. const ZeroStencilOp = 0;
  165. const KeepStencilOp = 7680;
  166. const ReplaceStencilOp = 7681;
  167. const IncrementStencilOp = 7682;
  168. const DecrementStencilOp = 7683;
  169. const IncrementWrapStencilOp = 34055;
  170. const DecrementWrapStencilOp = 34056;
  171. const InvertStencilOp = 5386;
  172. const NeverStencilFunc = 512;
  173. const LessStencilFunc = 513;
  174. const EqualStencilFunc = 514;
  175. const LessEqualStencilFunc = 515;
  176. const GreaterStencilFunc = 516;
  177. const NotEqualStencilFunc = 517;
  178. const GreaterEqualStencilFunc = 518;
  179. const AlwaysStencilFunc = 519;
  180. const StaticDrawUsage = 35044;
  181. const DynamicDrawUsage = 35048;
  182. const StreamDrawUsage = 35040;
  183. const StaticReadUsage = 35045;
  184. const DynamicReadUsage = 35049;
  185. const StreamReadUsage = 35041;
  186. const StaticCopyUsage = 35046;
  187. const DynamicCopyUsage = 35050;
  188. const StreamCopyUsage = 35042;
  189. const GLSL1 = '100';
  190. const GLSL3 = '300 es';
  191. const _SRGBAFormat = 1035; // fallback for WebGL 1
  192. /**
  193. * https://github.com/mrdoob/eventdispatcher.js/
  194. */
  195. class EventDispatcher {
  196. addEventListener(type, listener) {
  197. if (this._listeners === undefined) this._listeners = {};
  198. const listeners = this._listeners;
  199. if (listeners[type] === undefined) {
  200. listeners[type] = [];
  201. }
  202. if (listeners[type].indexOf(listener) === -1) {
  203. listeners[type].push(listener);
  204. }
  205. }
  206. hasEventListener(type, listener) {
  207. if (this._listeners === undefined) return false;
  208. const listeners = this._listeners;
  209. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  210. }
  211. removeEventListener(type, listener) {
  212. if (this._listeners === undefined) return;
  213. const listeners = this._listeners;
  214. const listenerArray = listeners[type];
  215. if (listenerArray !== undefined) {
  216. const index = listenerArray.indexOf(listener);
  217. if (index !== -1) {
  218. listenerArray.splice(index, 1);
  219. }
  220. }
  221. }
  222. dispatchEvent(event) {
  223. if (this._listeners === undefined) return;
  224. const listeners = this._listeners;
  225. const listenerArray = listeners[event.type];
  226. if (listenerArray !== undefined) {
  227. event.target = this; // Make a copy, in case listeners are removed while iterating.
  228. const array = listenerArray.slice(0);
  229. for (let i = 0, l = array.length; i < l; i++) {
  230. array[i].call(this, event);
  231. }
  232. event.target = null;
  233. }
  234. }
  235. }
  236. const _lut = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff'];
  237. let _seed = 1234567;
  238. const DEG2RAD = Math.PI / 180;
  239. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  240. function generateUUID() {
  241. const d0 = Math.random() * 0xffffffff | 0;
  242. const d1 = Math.random() * 0xffffffff | 0;
  243. const d2 = Math.random() * 0xffffffff | 0;
  244. const d3 = Math.random() * 0xffffffff | 0;
  245. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toLowerCase() here flattens concatenated strings to save heap memory space.
  246. return uuid.toLowerCase();
  247. }
  248. function clamp(value, min, max) {
  249. return Math.max(min, Math.min(max, value));
  250. } // compute euclidean modulo of m % n
  251. // https://en.wikipedia.org/wiki/Modulo_operation
  252. function euclideanModulo(n, m) {
  253. return (n % m + m) % m;
  254. } // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear(x, a1, a2, b1, b2) {
  256. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  257. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  258. function inverseLerp(x, y, value) {
  259. if (x !== y) {
  260. return (value - x) / (y - x);
  261. } else {
  262. return 0;
  263. }
  264. } // https://en.wikipedia.org/wiki/Linear_interpolation
  265. function lerp(x, y, t) {
  266. return (1 - t) * x + t * y;
  267. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  268. function damp(x, y, lambda, dt) {
  269. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  270. } // https://www.desmos.com/calculator/vcsjnyz7x4
  271. function pingpong(x, length = 1) {
  272. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  273. } // http://en.wikipedia.org/wiki/Smoothstep
  274. function smoothstep(x, min, max) {
  275. if (x <= min) return 0;
  276. if (x >= max) return 1;
  277. x = (x - min) / (max - min);
  278. return x * x * (3 - 2 * x);
  279. }
  280. function smootherstep(x, min, max) {
  281. if (x <= min) return 0;
  282. if (x >= max) return 1;
  283. x = (x - min) / (max - min);
  284. return x * x * x * (x * (x * 6 - 15) + 10);
  285. } // Random integer from <low, high> interval
  286. function randInt(low, high) {
  287. return low + Math.floor(Math.random() * (high - low + 1));
  288. } // Random float from <low, high> interval
  289. function randFloat(low, high) {
  290. return low + Math.random() * (high - low);
  291. } // Random float from <-range/2, range/2> interval
  292. function randFloatSpread(range) {
  293. return range * (0.5 - Math.random());
  294. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  295. function seededRandom(s) {
  296. if (s !== undefined) _seed = s; // Mulberry32 generator
  297. let t = _seed += 0x6D2B79F5;
  298. t = Math.imul(t ^ t >>> 15, t | 1);
  299. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  300. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  301. }
  302. function degToRad(degrees) {
  303. return degrees * DEG2RAD;
  304. }
  305. function radToDeg(radians) {
  306. return radians * RAD2DEG;
  307. }
  308. function isPowerOfTwo(value) {
  309. return (value & value - 1) === 0 && value !== 0;
  310. }
  311. function ceilPowerOfTwo(value) {
  312. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  313. }
  314. function floorPowerOfTwo(value) {
  315. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  316. }
  317. function setQuaternionFromProperEuler(q, a, b, c, order) {
  318. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  319. // rotations are applied to the axes in the order specified by 'order'
  320. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  321. // angles are in radians
  322. const cos = Math.cos;
  323. const sin = Math.sin;
  324. const c2 = cos(b / 2);
  325. const s2 = sin(b / 2);
  326. const c13 = cos((a + c) / 2);
  327. const s13 = sin((a + c) / 2);
  328. const c1_3 = cos((a - c) / 2);
  329. const s1_3 = sin((a - c) / 2);
  330. const c3_1 = cos((c - a) / 2);
  331. const s3_1 = sin((c - a) / 2);
  332. switch (order) {
  333. case 'XYX':
  334. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  335. break;
  336. case 'YZY':
  337. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  338. break;
  339. case 'ZXZ':
  340. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  341. break;
  342. case 'XZX':
  343. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  344. break;
  345. case 'YXY':
  346. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  347. break;
  348. case 'ZYZ':
  349. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  350. break;
  351. default:
  352. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  353. }
  354. }
  355. function denormalize(value, array) {
  356. switch (array.constructor) {
  357. case Float32Array:
  358. return value;
  359. case Uint16Array:
  360. return value / 65535.0;
  361. case Uint8Array:
  362. return value / 255.0;
  363. case Int16Array:
  364. return Math.max(value / 32767.0, -1.0);
  365. case Int8Array:
  366. return Math.max(value / 127.0, -1.0);
  367. default:
  368. throw new Error('Invalid component type.');
  369. }
  370. }
  371. function normalize(value, array) {
  372. switch (array.constructor) {
  373. case Float32Array:
  374. return value;
  375. case Uint16Array:
  376. return Math.round(value * 65535.0);
  377. case Uint8Array:
  378. return Math.round(value * 255.0);
  379. case Int16Array:
  380. return Math.round(value * 32767.0);
  381. case Int8Array:
  382. return Math.round(value * 127.0);
  383. default:
  384. throw new Error('Invalid component type.');
  385. }
  386. }
  387. var MathUtils = /*#__PURE__*/Object.freeze({
  388. __proto__: null,
  389. DEG2RAD: DEG2RAD,
  390. RAD2DEG: RAD2DEG,
  391. generateUUID: generateUUID,
  392. clamp: clamp,
  393. euclideanModulo: euclideanModulo,
  394. mapLinear: mapLinear,
  395. inverseLerp: inverseLerp,
  396. lerp: lerp,
  397. damp: damp,
  398. pingpong: pingpong,
  399. smoothstep: smoothstep,
  400. smootherstep: smootherstep,
  401. randInt: randInt,
  402. randFloat: randFloat,
  403. randFloatSpread: randFloatSpread,
  404. seededRandom: seededRandom,
  405. degToRad: degToRad,
  406. radToDeg: radToDeg,
  407. isPowerOfTwo: isPowerOfTwo,
  408. ceilPowerOfTwo: ceilPowerOfTwo,
  409. floorPowerOfTwo: floorPowerOfTwo,
  410. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  411. normalize: normalize,
  412. denormalize: denormalize
  413. });
  414. class Vector2 {
  415. constructor(x = 0, y = 0) {
  416. Vector2.prototype.isVector2 = true;
  417. this.x = x;
  418. this.y = y;
  419. }
  420. get width() {
  421. return this.x;
  422. }
  423. set width(value) {
  424. this.x = value;
  425. }
  426. get height() {
  427. return this.y;
  428. }
  429. set height(value) {
  430. this.y = value;
  431. }
  432. set(x, y) {
  433. this.x = x;
  434. this.y = y;
  435. return this;
  436. }
  437. setScalar(scalar) {
  438. this.x = scalar;
  439. this.y = scalar;
  440. return this;
  441. }
  442. setX(x) {
  443. this.x = x;
  444. return this;
  445. }
  446. setY(y) {
  447. this.y = y;
  448. return this;
  449. }
  450. setComponent(index, value) {
  451. switch (index) {
  452. case 0:
  453. this.x = value;
  454. break;
  455. case 1:
  456. this.y = value;
  457. break;
  458. default:
  459. throw new Error('index is out of range: ' + index);
  460. }
  461. return this;
  462. }
  463. getComponent(index) {
  464. switch (index) {
  465. case 0:
  466. return this.x;
  467. case 1:
  468. return this.y;
  469. default:
  470. throw new Error('index is out of range: ' + index);
  471. }
  472. }
  473. clone() {
  474. return new this.constructor(this.x, this.y);
  475. }
  476. copy(v) {
  477. this.x = v.x;
  478. this.y = v.y;
  479. return this;
  480. }
  481. add(v) {
  482. this.x += v.x;
  483. this.y += v.y;
  484. return this;
  485. }
  486. addScalar(s) {
  487. this.x += s;
  488. this.y += s;
  489. return this;
  490. }
  491. addVectors(a, b) {
  492. this.x = a.x + b.x;
  493. this.y = a.y + b.y;
  494. return this;
  495. }
  496. addScaledVector(v, s) {
  497. this.x += v.x * s;
  498. this.y += v.y * s;
  499. return this;
  500. }
  501. sub(v) {
  502. this.x -= v.x;
  503. this.y -= v.y;
  504. return this;
  505. }
  506. subScalar(s) {
  507. this.x -= s;
  508. this.y -= s;
  509. return this;
  510. }
  511. subVectors(a, b) {
  512. this.x = a.x - b.x;
  513. this.y = a.y - b.y;
  514. return this;
  515. }
  516. multiply(v) {
  517. this.x *= v.x;
  518. this.y *= v.y;
  519. return this;
  520. }
  521. multiplyScalar(scalar) {
  522. this.x *= scalar;
  523. this.y *= scalar;
  524. return this;
  525. }
  526. divide(v) {
  527. this.x /= v.x;
  528. this.y /= v.y;
  529. return this;
  530. }
  531. divideScalar(scalar) {
  532. return this.multiplyScalar(1 / scalar);
  533. }
  534. applyMatrix3(m) {
  535. const x = this.x,
  536. y = this.y;
  537. const e = m.elements;
  538. this.x = e[0] * x + e[3] * y + e[6];
  539. this.y = e[1] * x + e[4] * y + e[7];
  540. return this;
  541. }
  542. min(v) {
  543. this.x = Math.min(this.x, v.x);
  544. this.y = Math.min(this.y, v.y);
  545. return this;
  546. }
  547. max(v) {
  548. this.x = Math.max(this.x, v.x);
  549. this.y = Math.max(this.y, v.y);
  550. return this;
  551. }
  552. clamp(min, max) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max(min.x, Math.min(max.x, this.x));
  555. this.y = Math.max(min.y, Math.min(max.y, this.y));
  556. return this;
  557. }
  558. clampScalar(minVal, maxVal) {
  559. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  560. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  561. return this;
  562. }
  563. clampLength(min, max) {
  564. const length = this.length();
  565. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  566. }
  567. floor() {
  568. this.x = Math.floor(this.x);
  569. this.y = Math.floor(this.y);
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil(this.x);
  574. this.y = Math.ceil(this.y);
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round(this.x);
  579. this.y = Math.round(this.y);
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  584. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  585. return this;
  586. }
  587. negate() {
  588. this.x = -this.x;
  589. this.y = -this.y;
  590. return this;
  591. }
  592. dot(v) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross(v) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt(this.x * this.x + this.y * this.y);
  603. }
  604. manhattanLength() {
  605. return Math.abs(this.x) + Math.abs(this.y);
  606. }
  607. normalize() {
  608. return this.divideScalar(this.length() || 1);
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo(v) {
  616. return Math.sqrt(this.distanceToSquared(v));
  617. }
  618. distanceToSquared(v) {
  619. const dx = this.x - v.x,
  620. dy = this.y - v.y;
  621. return dx * dx + dy * dy;
  622. }
  623. manhattanDistanceTo(v) {
  624. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  625. }
  626. setLength(length) {
  627. return this.normalize().multiplyScalar(length);
  628. }
  629. lerp(v, alpha) {
  630. this.x += (v.x - this.x) * alpha;
  631. this.y += (v.y - this.y) * alpha;
  632. return this;
  633. }
  634. lerpVectors(v1, v2, alpha) {
  635. this.x = v1.x + (v2.x - v1.x) * alpha;
  636. this.y = v1.y + (v2.y - v1.y) * alpha;
  637. return this;
  638. }
  639. equals(v) {
  640. return v.x === this.x && v.y === this.y;
  641. }
  642. fromArray(array, offset = 0) {
  643. this.x = array[offset];
  644. this.y = array[offset + 1];
  645. return this;
  646. }
  647. toArray(array = [], offset = 0) {
  648. array[offset] = this.x;
  649. array[offset + 1] = this.y;
  650. return array;
  651. }
  652. fromBufferAttribute(attribute, index) {
  653. this.x = attribute.getX(index);
  654. this.y = attribute.getY(index);
  655. return this;
  656. }
  657. rotateAround(center, angle) {
  658. const c = Math.cos(angle),
  659. s = Math.sin(angle);
  660. const x = this.x - center.x;
  661. const y = this.y - center.y;
  662. this.x = x * c - y * s + center.x;
  663. this.y = x * s + y * c + center.y;
  664. return this;
  665. }
  666. random() {
  667. this.x = Math.random();
  668. this.y = Math.random();
  669. return this;
  670. }
  671. *[Symbol.iterator]() {
  672. yield this.x;
  673. yield this.y;
  674. }
  675. }
  676. class Matrix3 {
  677. constructor() {
  678. Matrix3.prototype.isMatrix3 = true;
  679. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  680. }
  681. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  682. const te = this.elements;
  683. te[0] = n11;
  684. te[1] = n21;
  685. te[2] = n31;
  686. te[3] = n12;
  687. te[4] = n22;
  688. te[5] = n32;
  689. te[6] = n13;
  690. te[7] = n23;
  691. te[8] = n33;
  692. return this;
  693. }
  694. identity() {
  695. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  696. return this;
  697. }
  698. copy(m) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[0] = me[0];
  702. te[1] = me[1];
  703. te[2] = me[2];
  704. te[3] = me[3];
  705. te[4] = me[4];
  706. te[5] = me[5];
  707. te[6] = me[6];
  708. te[7] = me[7];
  709. te[8] = me[8];
  710. return this;
  711. }
  712. extractBasis(xAxis, yAxis, zAxis) {
  713. xAxis.setFromMatrix3Column(this, 0);
  714. yAxis.setFromMatrix3Column(this, 1);
  715. zAxis.setFromMatrix3Column(this, 2);
  716. return this;
  717. }
  718. setFromMatrix4(m) {
  719. const me = m.elements;
  720. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  721. return this;
  722. }
  723. multiply(m) {
  724. return this.multiplyMatrices(this, m);
  725. }
  726. premultiply(m) {
  727. return this.multiplyMatrices(m, this);
  728. }
  729. multiplyMatrices(a, b) {
  730. const ae = a.elements;
  731. const be = b.elements;
  732. const te = this.elements;
  733. const a11 = ae[0],
  734. a12 = ae[3],
  735. a13 = ae[6];
  736. const a21 = ae[1],
  737. a22 = ae[4],
  738. a23 = ae[7];
  739. const a31 = ae[2],
  740. a32 = ae[5],
  741. a33 = ae[8];
  742. const b11 = be[0],
  743. b12 = be[3],
  744. b13 = be[6];
  745. const b21 = be[1],
  746. b22 = be[4],
  747. b23 = be[7];
  748. const b31 = be[2],
  749. b32 = be[5],
  750. b33 = be[8];
  751. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  752. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  753. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  754. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  755. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  756. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  757. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  758. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  759. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  760. return this;
  761. }
  762. multiplyScalar(s) {
  763. const te = this.elements;
  764. te[0] *= s;
  765. te[3] *= s;
  766. te[6] *= s;
  767. te[1] *= s;
  768. te[4] *= s;
  769. te[7] *= s;
  770. te[2] *= s;
  771. te[5] *= s;
  772. te[8] *= s;
  773. return this;
  774. }
  775. determinant() {
  776. const te = this.elements;
  777. const a = te[0],
  778. b = te[1],
  779. c = te[2],
  780. d = te[3],
  781. e = te[4],
  782. f = te[5],
  783. g = te[6],
  784. h = te[7],
  785. i = te[8];
  786. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  787. }
  788. invert() {
  789. const te = this.elements,
  790. n11 = te[0],
  791. n21 = te[1],
  792. n31 = te[2],
  793. n12 = te[3],
  794. n22 = te[4],
  795. n32 = te[5],
  796. n13 = te[6],
  797. n23 = te[7],
  798. n33 = te[8],
  799. t11 = n33 * n22 - n32 * n23,
  800. t12 = n32 * n13 - n33 * n12,
  801. t13 = n23 * n12 - n22 * n13,
  802. det = n11 * t11 + n21 * t12 + n31 * t13;
  803. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  804. const detInv = 1 / det;
  805. te[0] = t11 * detInv;
  806. te[1] = (n31 * n23 - n33 * n21) * detInv;
  807. te[2] = (n32 * n21 - n31 * n22) * detInv;
  808. te[3] = t12 * detInv;
  809. te[4] = (n33 * n11 - n31 * n13) * detInv;
  810. te[5] = (n31 * n12 - n32 * n11) * detInv;
  811. te[6] = t13 * detInv;
  812. te[7] = (n21 * n13 - n23 * n11) * detInv;
  813. te[8] = (n22 * n11 - n21 * n12) * detInv;
  814. return this;
  815. }
  816. transpose() {
  817. let tmp;
  818. const m = this.elements;
  819. tmp = m[1];
  820. m[1] = m[3];
  821. m[3] = tmp;
  822. tmp = m[2];
  823. m[2] = m[6];
  824. m[6] = tmp;
  825. tmp = m[5];
  826. m[5] = m[7];
  827. m[7] = tmp;
  828. return this;
  829. }
  830. getNormalMatrix(matrix4) {
  831. return this.setFromMatrix4(matrix4).invert().transpose();
  832. }
  833. transposeIntoArray(r) {
  834. const m = this.elements;
  835. r[0] = m[0];
  836. r[1] = m[3];
  837. r[2] = m[6];
  838. r[3] = m[1];
  839. r[4] = m[4];
  840. r[5] = m[7];
  841. r[6] = m[2];
  842. r[7] = m[5];
  843. r[8] = m[8];
  844. return this;
  845. }
  846. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  847. const c = Math.cos(rotation);
  848. const s = Math.sin(rotation);
  849. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  850. return this;
  851. }
  852. scale(sx, sy) {
  853. const te = this.elements;
  854. te[0] *= sx;
  855. te[3] *= sx;
  856. te[6] *= sx;
  857. te[1] *= sy;
  858. te[4] *= sy;
  859. te[7] *= sy;
  860. return this;
  861. }
  862. rotate(theta) {
  863. const c = Math.cos(theta);
  864. const s = Math.sin(theta);
  865. const te = this.elements;
  866. const a11 = te[0],
  867. a12 = te[3],
  868. a13 = te[6];
  869. const a21 = te[1],
  870. a22 = te[4],
  871. a23 = te[7];
  872. te[0] = c * a11 + s * a21;
  873. te[3] = c * a12 + s * a22;
  874. te[6] = c * a13 + s * a23;
  875. te[1] = -s * a11 + c * a21;
  876. te[4] = -s * a12 + c * a22;
  877. te[7] = -s * a13 + c * a23;
  878. return this;
  879. }
  880. translate(tx, ty) {
  881. const te = this.elements;
  882. te[0] += tx * te[2];
  883. te[3] += tx * te[5];
  884. te[6] += tx * te[8];
  885. te[1] += ty * te[2];
  886. te[4] += ty * te[5];
  887. te[7] += ty * te[8];
  888. return this;
  889. }
  890. equals(matrix) {
  891. const te = this.elements;
  892. const me = matrix.elements;
  893. for (let i = 0; i < 9; i++) {
  894. if (te[i] !== me[i]) return false;
  895. }
  896. return true;
  897. }
  898. fromArray(array, offset = 0) {
  899. for (let i = 0; i < 9; i++) {
  900. this.elements[i] = array[i + offset];
  901. }
  902. return this;
  903. }
  904. toArray(array = [], offset = 0) {
  905. const te = this.elements;
  906. array[offset] = te[0];
  907. array[offset + 1] = te[1];
  908. array[offset + 2] = te[2];
  909. array[offset + 3] = te[3];
  910. array[offset + 4] = te[4];
  911. array[offset + 5] = te[5];
  912. array[offset + 6] = te[6];
  913. array[offset + 7] = te[7];
  914. array[offset + 8] = te[8];
  915. return array;
  916. }
  917. clone() {
  918. return new this.constructor().fromArray(this.elements);
  919. }
  920. }
  921. function arrayNeedsUint32(array) {
  922. // assumes larger values usually on last
  923. for (let i = array.length - 1; i >= 0; --i) {
  924. if (array[i] > 65535) return true;
  925. }
  926. return false;
  927. }
  928. const TYPED_ARRAYS = {
  929. Int8Array: Int8Array,
  930. Uint8Array: Uint8Array,
  931. Uint8ClampedArray: Uint8ClampedArray,
  932. Int16Array: Int16Array,
  933. Uint16Array: Uint16Array,
  934. Int32Array: Int32Array,
  935. Uint32Array: Uint32Array,
  936. Float32Array: Float32Array,
  937. Float64Array: Float64Array
  938. };
  939. function getTypedArray(type, buffer) {
  940. return new TYPED_ARRAYS[type](buffer);
  941. }
  942. function createElementNS(name) {
  943. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  944. }
  945. function SRGBToLinear(c) {
  946. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  947. }
  948. function LinearToSRGB(c) {
  949. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  950. } // JavaScript RGB-to-RGB transforms, defined as
  951. // FN[InputColorSpace][OutputColorSpace] callback functions.
  952. const FN = {
  953. [SRGBColorSpace]: {
  954. [LinearSRGBColorSpace]: SRGBToLinear
  955. },
  956. [LinearSRGBColorSpace]: {
  957. [SRGBColorSpace]: LinearToSRGB
  958. }
  959. };
  960. const ColorManagement = {
  961. legacyMode: true,
  962. get workingColorSpace() {
  963. return LinearSRGBColorSpace;
  964. },
  965. set workingColorSpace(colorSpace) {
  966. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  967. },
  968. convert: function (color, sourceColorSpace, targetColorSpace) {
  969. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  970. return color;
  971. }
  972. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  973. const fn = FN[sourceColorSpace][targetColorSpace];
  974. color.r = fn(color.r);
  975. color.g = fn(color.g);
  976. color.b = fn(color.b);
  977. return color;
  978. }
  979. throw new Error('Unsupported color space conversion.');
  980. },
  981. fromWorkingColorSpace: function (color, targetColorSpace) {
  982. return this.convert(color, this.workingColorSpace, targetColorSpace);
  983. },
  984. toWorkingColorSpace: function (color, sourceColorSpace) {
  985. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  986. }
  987. };
  988. const _colorKeywords = {
  989. 'aliceblue': 0xF0F8FF,
  990. 'antiquewhite': 0xFAEBD7,
  991. 'aqua': 0x00FFFF,
  992. 'aquamarine': 0x7FFFD4,
  993. 'azure': 0xF0FFFF,
  994. 'beige': 0xF5F5DC,
  995. 'bisque': 0xFFE4C4,
  996. 'black': 0x000000,
  997. 'blanchedalmond': 0xFFEBCD,
  998. 'blue': 0x0000FF,
  999. 'blueviolet': 0x8A2BE2,
  1000. 'brown': 0xA52A2A,
  1001. 'burlywood': 0xDEB887,
  1002. 'cadetblue': 0x5F9EA0,
  1003. 'chartreuse': 0x7FFF00,
  1004. 'chocolate': 0xD2691E,
  1005. 'coral': 0xFF7F50,
  1006. 'cornflowerblue': 0x6495ED,
  1007. 'cornsilk': 0xFFF8DC,
  1008. 'crimson': 0xDC143C,
  1009. 'cyan': 0x00FFFF,
  1010. 'darkblue': 0x00008B,
  1011. 'darkcyan': 0x008B8B,
  1012. 'darkgoldenrod': 0xB8860B,
  1013. 'darkgray': 0xA9A9A9,
  1014. 'darkgreen': 0x006400,
  1015. 'darkgrey': 0xA9A9A9,
  1016. 'darkkhaki': 0xBDB76B,
  1017. 'darkmagenta': 0x8B008B,
  1018. 'darkolivegreen': 0x556B2F,
  1019. 'darkorange': 0xFF8C00,
  1020. 'darkorchid': 0x9932CC,
  1021. 'darkred': 0x8B0000,
  1022. 'darksalmon': 0xE9967A,
  1023. 'darkseagreen': 0x8FBC8F,
  1024. 'darkslateblue': 0x483D8B,
  1025. 'darkslategray': 0x2F4F4F,
  1026. 'darkslategrey': 0x2F4F4F,
  1027. 'darkturquoise': 0x00CED1,
  1028. 'darkviolet': 0x9400D3,
  1029. 'deeppink': 0xFF1493,
  1030. 'deepskyblue': 0x00BFFF,
  1031. 'dimgray': 0x696969,
  1032. 'dimgrey': 0x696969,
  1033. 'dodgerblue': 0x1E90FF,
  1034. 'firebrick': 0xB22222,
  1035. 'floralwhite': 0xFFFAF0,
  1036. 'forestgreen': 0x228B22,
  1037. 'fuchsia': 0xFF00FF,
  1038. 'gainsboro': 0xDCDCDC,
  1039. 'ghostwhite': 0xF8F8FF,
  1040. 'gold': 0xFFD700,
  1041. 'goldenrod': 0xDAA520,
  1042. 'gray': 0x808080,
  1043. 'green': 0x008000,
  1044. 'greenyellow': 0xADFF2F,
  1045. 'grey': 0x808080,
  1046. 'honeydew': 0xF0FFF0,
  1047. 'hotpink': 0xFF69B4,
  1048. 'indianred': 0xCD5C5C,
  1049. 'indigo': 0x4B0082,
  1050. 'ivory': 0xFFFFF0,
  1051. 'khaki': 0xF0E68C,
  1052. 'lavender': 0xE6E6FA,
  1053. 'lavenderblush': 0xFFF0F5,
  1054. 'lawngreen': 0x7CFC00,
  1055. 'lemonchiffon': 0xFFFACD,
  1056. 'lightblue': 0xADD8E6,
  1057. 'lightcoral': 0xF08080,
  1058. 'lightcyan': 0xE0FFFF,
  1059. 'lightgoldenrodyellow': 0xFAFAD2,
  1060. 'lightgray': 0xD3D3D3,
  1061. 'lightgreen': 0x90EE90,
  1062. 'lightgrey': 0xD3D3D3,
  1063. 'lightpink': 0xFFB6C1,
  1064. 'lightsalmon': 0xFFA07A,
  1065. 'lightseagreen': 0x20B2AA,
  1066. 'lightskyblue': 0x87CEFA,
  1067. 'lightslategray': 0x778899,
  1068. 'lightslategrey': 0x778899,
  1069. 'lightsteelblue': 0xB0C4DE,
  1070. 'lightyellow': 0xFFFFE0,
  1071. 'lime': 0x00FF00,
  1072. 'limegreen': 0x32CD32,
  1073. 'linen': 0xFAF0E6,
  1074. 'magenta': 0xFF00FF,
  1075. 'maroon': 0x800000,
  1076. 'mediumaquamarine': 0x66CDAA,
  1077. 'mediumblue': 0x0000CD,
  1078. 'mediumorchid': 0xBA55D3,
  1079. 'mediumpurple': 0x9370DB,
  1080. 'mediumseagreen': 0x3CB371,
  1081. 'mediumslateblue': 0x7B68EE,
  1082. 'mediumspringgreen': 0x00FA9A,
  1083. 'mediumturquoise': 0x48D1CC,
  1084. 'mediumvioletred': 0xC71585,
  1085. 'midnightblue': 0x191970,
  1086. 'mintcream': 0xF5FFFA,
  1087. 'mistyrose': 0xFFE4E1,
  1088. 'moccasin': 0xFFE4B5,
  1089. 'navajowhite': 0xFFDEAD,
  1090. 'navy': 0x000080,
  1091. 'oldlace': 0xFDF5E6,
  1092. 'olive': 0x808000,
  1093. 'olivedrab': 0x6B8E23,
  1094. 'orange': 0xFFA500,
  1095. 'orangered': 0xFF4500,
  1096. 'orchid': 0xDA70D6,
  1097. 'palegoldenrod': 0xEEE8AA,
  1098. 'palegreen': 0x98FB98,
  1099. 'paleturquoise': 0xAFEEEE,
  1100. 'palevioletred': 0xDB7093,
  1101. 'papayawhip': 0xFFEFD5,
  1102. 'peachpuff': 0xFFDAB9,
  1103. 'peru': 0xCD853F,
  1104. 'pink': 0xFFC0CB,
  1105. 'plum': 0xDDA0DD,
  1106. 'powderblue': 0xB0E0E6,
  1107. 'purple': 0x800080,
  1108. 'rebeccapurple': 0x663399,
  1109. 'red': 0xFF0000,
  1110. 'rosybrown': 0xBC8F8F,
  1111. 'royalblue': 0x4169E1,
  1112. 'saddlebrown': 0x8B4513,
  1113. 'salmon': 0xFA8072,
  1114. 'sandybrown': 0xF4A460,
  1115. 'seagreen': 0x2E8B57,
  1116. 'seashell': 0xFFF5EE,
  1117. 'sienna': 0xA0522D,
  1118. 'silver': 0xC0C0C0,
  1119. 'skyblue': 0x87CEEB,
  1120. 'slateblue': 0x6A5ACD,
  1121. 'slategray': 0x708090,
  1122. 'slategrey': 0x708090,
  1123. 'snow': 0xFFFAFA,
  1124. 'springgreen': 0x00FF7F,
  1125. 'steelblue': 0x4682B4,
  1126. 'tan': 0xD2B48C,
  1127. 'teal': 0x008080,
  1128. 'thistle': 0xD8BFD8,
  1129. 'tomato': 0xFF6347,
  1130. 'turquoise': 0x40E0D0,
  1131. 'violet': 0xEE82EE,
  1132. 'wheat': 0xF5DEB3,
  1133. 'white': 0xFFFFFF,
  1134. 'whitesmoke': 0xF5F5F5,
  1135. 'yellow': 0xFFFF00,
  1136. 'yellowgreen': 0x9ACD32
  1137. };
  1138. const _rgb = {
  1139. r: 0,
  1140. g: 0,
  1141. b: 0
  1142. };
  1143. const _hslA = {
  1144. h: 0,
  1145. s: 0,
  1146. l: 0
  1147. };
  1148. const _hslB = {
  1149. h: 0,
  1150. s: 0,
  1151. l: 0
  1152. };
  1153. function hue2rgb(p, q, t) {
  1154. if (t < 0) t += 1;
  1155. if (t > 1) t -= 1;
  1156. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1157. if (t < 1 / 2) return q;
  1158. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1159. return p;
  1160. }
  1161. function toComponents(source, target) {
  1162. target.r = source.r;
  1163. target.g = source.g;
  1164. target.b = source.b;
  1165. return target;
  1166. }
  1167. class Color {
  1168. constructor(r, g, b) {
  1169. this.isColor = true;
  1170. this.r = 1;
  1171. this.g = 1;
  1172. this.b = 1;
  1173. if (g === undefined && b === undefined) {
  1174. // r is THREE.Color, hex or string
  1175. return this.set(r);
  1176. }
  1177. return this.setRGB(r, g, b);
  1178. }
  1179. set(value) {
  1180. if (value && value.isColor) {
  1181. this.copy(value);
  1182. } else if (typeof value === 'number') {
  1183. this.setHex(value);
  1184. } else if (typeof value === 'string') {
  1185. this.setStyle(value);
  1186. }
  1187. return this;
  1188. }
  1189. setScalar(scalar) {
  1190. this.r = scalar;
  1191. this.g = scalar;
  1192. this.b = scalar;
  1193. return this;
  1194. }
  1195. setHex(hex, colorSpace = SRGBColorSpace) {
  1196. hex = Math.floor(hex);
  1197. this.r = (hex >> 16 & 255) / 255;
  1198. this.g = (hex >> 8 & 255) / 255;
  1199. this.b = (hex & 255) / 255;
  1200. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1201. return this;
  1202. }
  1203. setRGB(r, g, b, colorSpace = LinearSRGBColorSpace) {
  1204. this.r = r;
  1205. this.g = g;
  1206. this.b = b;
  1207. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1208. return this;
  1209. }
  1210. setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) {
  1211. // h,s,l ranges are in 0.0 - 1.0
  1212. h = euclideanModulo(h, 1);
  1213. s = clamp(s, 0, 1);
  1214. l = clamp(l, 0, 1);
  1215. if (s === 0) {
  1216. this.r = this.g = this.b = l;
  1217. } else {
  1218. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1219. const q = 2 * l - p;
  1220. this.r = hue2rgb(q, p, h + 1 / 3);
  1221. this.g = hue2rgb(q, p, h);
  1222. this.b = hue2rgb(q, p, h - 1 / 3);
  1223. }
  1224. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1225. return this;
  1226. }
  1227. setStyle(style, colorSpace = SRGBColorSpace) {
  1228. function handleAlpha(string) {
  1229. if (string === undefined) return;
  1230. if (parseFloat(string) < 1) {
  1231. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1232. }
  1233. }
  1234. let m;
  1235. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1236. // rgb / hsl
  1237. let color;
  1238. const name = m[1];
  1239. const components = m[2];
  1240. switch (name) {
  1241. case 'rgb':
  1242. case 'rgba':
  1243. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1244. // rgb(255,0,0) rgba(255,0,0,0.5)
  1245. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1246. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1247. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1248. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1249. handleAlpha(color[4]);
  1250. return this;
  1251. }
  1252. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1253. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1254. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1255. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1256. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1257. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1258. handleAlpha(color[4]);
  1259. return this;
  1260. }
  1261. break;
  1262. case 'hsl':
  1263. case 'hsla':
  1264. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1265. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1266. const h = parseFloat(color[1]) / 360;
  1267. const s = parseFloat(color[2]) / 100;
  1268. const l = parseFloat(color[3]) / 100;
  1269. handleAlpha(color[4]);
  1270. return this.setHSL(h, s, l, colorSpace);
  1271. }
  1272. break;
  1273. }
  1274. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1275. // hex color
  1276. const hex = m[1];
  1277. const size = hex.length;
  1278. if (size === 3) {
  1279. // #ff0
  1280. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1281. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1282. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1283. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1284. return this;
  1285. } else if (size === 6) {
  1286. // #ff0000
  1287. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1288. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1289. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1290. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1291. return this;
  1292. }
  1293. }
  1294. if (style && style.length > 0) {
  1295. return this.setColorName(style, colorSpace);
  1296. }
  1297. return this;
  1298. }
  1299. setColorName(style, colorSpace = SRGBColorSpace) {
  1300. // color keywords
  1301. const hex = _colorKeywords[style.toLowerCase()];
  1302. if (hex !== undefined) {
  1303. // red
  1304. this.setHex(hex, colorSpace);
  1305. } else {
  1306. // unknown color
  1307. console.warn('THREE.Color: Unknown color ' + style);
  1308. }
  1309. return this;
  1310. }
  1311. clone() {
  1312. return new this.constructor(this.r, this.g, this.b);
  1313. }
  1314. copy(color) {
  1315. this.r = color.r;
  1316. this.g = color.g;
  1317. this.b = color.b;
  1318. return this;
  1319. }
  1320. copySRGBToLinear(color) {
  1321. this.r = SRGBToLinear(color.r);
  1322. this.g = SRGBToLinear(color.g);
  1323. this.b = SRGBToLinear(color.b);
  1324. return this;
  1325. }
  1326. copyLinearToSRGB(color) {
  1327. this.r = LinearToSRGB(color.r);
  1328. this.g = LinearToSRGB(color.g);
  1329. this.b = LinearToSRGB(color.b);
  1330. return this;
  1331. }
  1332. convertSRGBToLinear() {
  1333. this.copySRGBToLinear(this);
  1334. return this;
  1335. }
  1336. convertLinearToSRGB() {
  1337. this.copyLinearToSRGB(this);
  1338. return this;
  1339. }
  1340. getHex(colorSpace = SRGBColorSpace) {
  1341. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1342. return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0;
  1343. }
  1344. getHexString(colorSpace = SRGBColorSpace) {
  1345. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1346. }
  1347. getHSL(target, colorSpace = LinearSRGBColorSpace) {
  1348. // h,s,l ranges are in 0.0 - 1.0
  1349. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1350. const r = _rgb.r,
  1351. g = _rgb.g,
  1352. b = _rgb.b;
  1353. const max = Math.max(r, g, b);
  1354. const min = Math.min(r, g, b);
  1355. let hue, saturation;
  1356. const lightness = (min + max) / 2.0;
  1357. if (min === max) {
  1358. hue = 0;
  1359. saturation = 0;
  1360. } else {
  1361. const delta = max - min;
  1362. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1363. switch (max) {
  1364. case r:
  1365. hue = (g - b) / delta + (g < b ? 6 : 0);
  1366. break;
  1367. case g:
  1368. hue = (b - r) / delta + 2;
  1369. break;
  1370. case b:
  1371. hue = (r - g) / delta + 4;
  1372. break;
  1373. }
  1374. hue /= 6;
  1375. }
  1376. target.h = hue;
  1377. target.s = saturation;
  1378. target.l = lightness;
  1379. return target;
  1380. }
  1381. getRGB(target, colorSpace = LinearSRGBColorSpace) {
  1382. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1383. target.r = _rgb.r;
  1384. target.g = _rgb.g;
  1385. target.b = _rgb.b;
  1386. return target;
  1387. }
  1388. getStyle(colorSpace = SRGBColorSpace) {
  1389. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1390. if (colorSpace !== SRGBColorSpace) {
  1391. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1392. return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`;
  1393. }
  1394. return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`;
  1395. }
  1396. offsetHSL(h, s, l) {
  1397. this.getHSL(_hslA);
  1398. _hslA.h += h;
  1399. _hslA.s += s;
  1400. _hslA.l += l;
  1401. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1402. return this;
  1403. }
  1404. add(color) {
  1405. this.r += color.r;
  1406. this.g += color.g;
  1407. this.b += color.b;
  1408. return this;
  1409. }
  1410. addColors(color1, color2) {
  1411. this.r = color1.r + color2.r;
  1412. this.g = color1.g + color2.g;
  1413. this.b = color1.b + color2.b;
  1414. return this;
  1415. }
  1416. addScalar(s) {
  1417. this.r += s;
  1418. this.g += s;
  1419. this.b += s;
  1420. return this;
  1421. }
  1422. sub(color) {
  1423. this.r = Math.max(0, this.r - color.r);
  1424. this.g = Math.max(0, this.g - color.g);
  1425. this.b = Math.max(0, this.b - color.b);
  1426. return this;
  1427. }
  1428. multiply(color) {
  1429. this.r *= color.r;
  1430. this.g *= color.g;
  1431. this.b *= color.b;
  1432. return this;
  1433. }
  1434. multiplyScalar(s) {
  1435. this.r *= s;
  1436. this.g *= s;
  1437. this.b *= s;
  1438. return this;
  1439. }
  1440. lerp(color, alpha) {
  1441. this.r += (color.r - this.r) * alpha;
  1442. this.g += (color.g - this.g) * alpha;
  1443. this.b += (color.b - this.b) * alpha;
  1444. return this;
  1445. }
  1446. lerpColors(color1, color2, alpha) {
  1447. this.r = color1.r + (color2.r - color1.r) * alpha;
  1448. this.g = color1.g + (color2.g - color1.g) * alpha;
  1449. this.b = color1.b + (color2.b - color1.b) * alpha;
  1450. return this;
  1451. }
  1452. lerpHSL(color, alpha) {
  1453. this.getHSL(_hslA);
  1454. color.getHSL(_hslB);
  1455. const h = lerp(_hslA.h, _hslB.h, alpha);
  1456. const s = lerp(_hslA.s, _hslB.s, alpha);
  1457. const l = lerp(_hslA.l, _hslB.l, alpha);
  1458. this.setHSL(h, s, l);
  1459. return this;
  1460. }
  1461. equals(c) {
  1462. return c.r === this.r && c.g === this.g && c.b === this.b;
  1463. }
  1464. fromArray(array, offset = 0) {
  1465. this.r = array[offset];
  1466. this.g = array[offset + 1];
  1467. this.b = array[offset + 2];
  1468. return this;
  1469. }
  1470. toArray(array = [], offset = 0) {
  1471. array[offset] = this.r;
  1472. array[offset + 1] = this.g;
  1473. array[offset + 2] = this.b;
  1474. return array;
  1475. }
  1476. fromBufferAttribute(attribute, index) {
  1477. this.r = attribute.getX(index);
  1478. this.g = attribute.getY(index);
  1479. this.b = attribute.getZ(index);
  1480. return this;
  1481. }
  1482. toJSON() {
  1483. return this.getHex();
  1484. }
  1485. *[Symbol.iterator]() {
  1486. yield this.r;
  1487. yield this.g;
  1488. yield this.b;
  1489. }
  1490. }
  1491. Color.NAMES = _colorKeywords;
  1492. let _canvas;
  1493. class ImageUtils {
  1494. static getDataURL(image) {
  1495. if (/^data:/i.test(image.src)) {
  1496. return image.src;
  1497. }
  1498. if (typeof HTMLCanvasElement == 'undefined') {
  1499. return image.src;
  1500. }
  1501. let canvas;
  1502. if (image instanceof HTMLCanvasElement) {
  1503. canvas = image;
  1504. } else {
  1505. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1506. _canvas.width = image.width;
  1507. _canvas.height = image.height;
  1508. const context = _canvas.getContext('2d');
  1509. if (image instanceof ImageData) {
  1510. context.putImageData(image, 0, 0);
  1511. } else {
  1512. context.drawImage(image, 0, 0, image.width, image.height);
  1513. }
  1514. canvas = _canvas;
  1515. }
  1516. if (canvas.width > 2048 || canvas.height > 2048) {
  1517. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1518. return canvas.toDataURL('image/jpeg', 0.6);
  1519. } else {
  1520. return canvas.toDataURL('image/png');
  1521. }
  1522. }
  1523. static sRGBToLinear(image) {
  1524. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1525. const canvas = createElementNS('canvas');
  1526. canvas.width = image.width;
  1527. canvas.height = image.height;
  1528. const context = canvas.getContext('2d');
  1529. context.drawImage(image, 0, 0, image.width, image.height);
  1530. const imageData = context.getImageData(0, 0, image.width, image.height);
  1531. const data = imageData.data;
  1532. for (let i = 0; i < data.length; i++) {
  1533. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1534. }
  1535. context.putImageData(imageData, 0, 0);
  1536. return canvas;
  1537. } else if (image.data) {
  1538. const data = image.data.slice(0);
  1539. for (let i = 0; i < data.length; i++) {
  1540. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1541. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1542. } else {
  1543. // assuming float
  1544. data[i] = SRGBToLinear(data[i]);
  1545. }
  1546. }
  1547. return {
  1548. data: data,
  1549. width: image.width,
  1550. height: image.height
  1551. };
  1552. } else {
  1553. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1554. return image;
  1555. }
  1556. }
  1557. }
  1558. class Source {
  1559. constructor(data = null) {
  1560. this.isSource = true;
  1561. this.uuid = generateUUID();
  1562. this.data = data;
  1563. this.version = 0;
  1564. }
  1565. set needsUpdate(value) {
  1566. if (value === true) this.version++;
  1567. }
  1568. toJSON(meta) {
  1569. const isRootObject = meta === undefined || typeof meta === 'string';
  1570. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1571. return meta.images[this.uuid];
  1572. }
  1573. const output = {
  1574. uuid: this.uuid,
  1575. url: ''
  1576. };
  1577. const data = this.data;
  1578. if (data !== null) {
  1579. let url;
  1580. if (Array.isArray(data)) {
  1581. // cube texture
  1582. url = [];
  1583. for (let i = 0, l = data.length; i < l; i++) {
  1584. if (data[i].isDataTexture) {
  1585. url.push(serializeImage(data[i].image));
  1586. } else {
  1587. url.push(serializeImage(data[i]));
  1588. }
  1589. }
  1590. } else {
  1591. // texture
  1592. url = serializeImage(data);
  1593. }
  1594. output.url = url;
  1595. }
  1596. if (!isRootObject) {
  1597. meta.images[this.uuid] = output;
  1598. }
  1599. return output;
  1600. }
  1601. }
  1602. function serializeImage(image) {
  1603. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1604. // default images
  1605. return ImageUtils.getDataURL(image);
  1606. } else {
  1607. if (image.data) {
  1608. // images of DataTexture
  1609. return {
  1610. data: Array.from(image.data),
  1611. width: image.width,
  1612. height: image.height,
  1613. type: image.data.constructor.name
  1614. };
  1615. } else {
  1616. console.warn('THREE.Texture: Unable to serialize Texture.');
  1617. return {};
  1618. }
  1619. }
  1620. }
  1621. let textureId = 0;
  1622. class Texture extends EventDispatcher {
  1623. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1624. super();
  1625. this.isTexture = true;
  1626. Object.defineProperty(this, 'id', {
  1627. value: textureId++
  1628. });
  1629. this.uuid = generateUUID();
  1630. this.name = '';
  1631. this.source = new Source(image);
  1632. this.mipmaps = [];
  1633. this.mapping = mapping;
  1634. this.wrapS = wrapS;
  1635. this.wrapT = wrapT;
  1636. this.magFilter = magFilter;
  1637. this.minFilter = minFilter;
  1638. this.anisotropy = anisotropy;
  1639. this.format = format;
  1640. this.internalFormat = null;
  1641. this.type = type;
  1642. this.offset = new Vector2(0, 0);
  1643. this.repeat = new Vector2(1, 1);
  1644. this.center = new Vector2(0, 0);
  1645. this.rotation = 0;
  1646. this.matrixAutoUpdate = true;
  1647. this.matrix = new Matrix3();
  1648. this.generateMipmaps = true;
  1649. this.premultiplyAlpha = false;
  1650. this.flipY = true;
  1651. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1652. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1653. //
  1654. // Also changing the encoding after already used by a Material will not automatically make the Material
  1655. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1656. this.encoding = encoding;
  1657. this.userData = {};
  1658. this.version = 0;
  1659. this.onUpdate = null;
  1660. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1661. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1662. }
  1663. get image() {
  1664. return this.source.data;
  1665. }
  1666. set image(value) {
  1667. this.source.data = value;
  1668. }
  1669. updateMatrix() {
  1670. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1671. }
  1672. clone() {
  1673. return new this.constructor().copy(this);
  1674. }
  1675. copy(source) {
  1676. this.name = source.name;
  1677. this.source = source.source;
  1678. this.mipmaps = source.mipmaps.slice(0);
  1679. this.mapping = source.mapping;
  1680. this.wrapS = source.wrapS;
  1681. this.wrapT = source.wrapT;
  1682. this.magFilter = source.magFilter;
  1683. this.minFilter = source.minFilter;
  1684. this.anisotropy = source.anisotropy;
  1685. this.format = source.format;
  1686. this.internalFormat = source.internalFormat;
  1687. this.type = source.type;
  1688. this.offset.copy(source.offset);
  1689. this.repeat.copy(source.repeat);
  1690. this.center.copy(source.center);
  1691. this.rotation = source.rotation;
  1692. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1693. this.matrix.copy(source.matrix);
  1694. this.generateMipmaps = source.generateMipmaps;
  1695. this.premultiplyAlpha = source.premultiplyAlpha;
  1696. this.flipY = source.flipY;
  1697. this.unpackAlignment = source.unpackAlignment;
  1698. this.encoding = source.encoding;
  1699. this.userData = JSON.parse(JSON.stringify(source.userData));
  1700. this.needsUpdate = true;
  1701. return this;
  1702. }
  1703. toJSON(meta) {
  1704. const isRootObject = meta === undefined || typeof meta === 'string';
  1705. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1706. return meta.textures[this.uuid];
  1707. }
  1708. const output = {
  1709. metadata: {
  1710. version: 4.5,
  1711. type: 'Texture',
  1712. generator: 'Texture.toJSON'
  1713. },
  1714. uuid: this.uuid,
  1715. name: this.name,
  1716. image: this.source.toJSON(meta).uuid,
  1717. mapping: this.mapping,
  1718. repeat: [this.repeat.x, this.repeat.y],
  1719. offset: [this.offset.x, this.offset.y],
  1720. center: [this.center.x, this.center.y],
  1721. rotation: this.rotation,
  1722. wrap: [this.wrapS, this.wrapT],
  1723. format: this.format,
  1724. type: this.type,
  1725. encoding: this.encoding,
  1726. minFilter: this.minFilter,
  1727. magFilter: this.magFilter,
  1728. anisotropy: this.anisotropy,
  1729. flipY: this.flipY,
  1730. premultiplyAlpha: this.premultiplyAlpha,
  1731. unpackAlignment: this.unpackAlignment
  1732. };
  1733. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1734. if (!isRootObject) {
  1735. meta.textures[this.uuid] = output;
  1736. }
  1737. return output;
  1738. }
  1739. dispose() {
  1740. this.dispatchEvent({
  1741. type: 'dispose'
  1742. });
  1743. }
  1744. transformUv(uv) {
  1745. if (this.mapping !== UVMapping) return uv;
  1746. uv.applyMatrix3(this.matrix);
  1747. if (uv.x < 0 || uv.x > 1) {
  1748. switch (this.wrapS) {
  1749. case RepeatWrapping:
  1750. uv.x = uv.x - Math.floor(uv.x);
  1751. break;
  1752. case ClampToEdgeWrapping:
  1753. uv.x = uv.x < 0 ? 0 : 1;
  1754. break;
  1755. case MirroredRepeatWrapping:
  1756. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1757. uv.x = Math.ceil(uv.x) - uv.x;
  1758. } else {
  1759. uv.x = uv.x - Math.floor(uv.x);
  1760. }
  1761. break;
  1762. }
  1763. }
  1764. if (uv.y < 0 || uv.y > 1) {
  1765. switch (this.wrapT) {
  1766. case RepeatWrapping:
  1767. uv.y = uv.y - Math.floor(uv.y);
  1768. break;
  1769. case ClampToEdgeWrapping:
  1770. uv.y = uv.y < 0 ? 0 : 1;
  1771. break;
  1772. case MirroredRepeatWrapping:
  1773. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1774. uv.y = Math.ceil(uv.y) - uv.y;
  1775. } else {
  1776. uv.y = uv.y - Math.floor(uv.y);
  1777. }
  1778. break;
  1779. }
  1780. }
  1781. if (this.flipY) {
  1782. uv.y = 1 - uv.y;
  1783. }
  1784. return uv;
  1785. }
  1786. set needsUpdate(value) {
  1787. if (value === true) {
  1788. this.version++;
  1789. this.source.needsUpdate = true;
  1790. }
  1791. }
  1792. }
  1793. Texture.DEFAULT_IMAGE = null;
  1794. Texture.DEFAULT_MAPPING = UVMapping;
  1795. class Vector4 {
  1796. constructor(x = 0, y = 0, z = 0, w = 1) {
  1797. Vector4.prototype.isVector4 = true;
  1798. this.x = x;
  1799. this.y = y;
  1800. this.z = z;
  1801. this.w = w;
  1802. }
  1803. get width() {
  1804. return this.z;
  1805. }
  1806. set width(value) {
  1807. this.z = value;
  1808. }
  1809. get height() {
  1810. return this.w;
  1811. }
  1812. set height(value) {
  1813. this.w = value;
  1814. }
  1815. set(x, y, z, w) {
  1816. this.x = x;
  1817. this.y = y;
  1818. this.z = z;
  1819. this.w = w;
  1820. return this;
  1821. }
  1822. setScalar(scalar) {
  1823. this.x = scalar;
  1824. this.y = scalar;
  1825. this.z = scalar;
  1826. this.w = scalar;
  1827. return this;
  1828. }
  1829. setX(x) {
  1830. this.x = x;
  1831. return this;
  1832. }
  1833. setY(y) {
  1834. this.y = y;
  1835. return this;
  1836. }
  1837. setZ(z) {
  1838. this.z = z;
  1839. return this;
  1840. }
  1841. setW(w) {
  1842. this.w = w;
  1843. return this;
  1844. }
  1845. setComponent(index, value) {
  1846. switch (index) {
  1847. case 0:
  1848. this.x = value;
  1849. break;
  1850. case 1:
  1851. this.y = value;
  1852. break;
  1853. case 2:
  1854. this.z = value;
  1855. break;
  1856. case 3:
  1857. this.w = value;
  1858. break;
  1859. default:
  1860. throw new Error('index is out of range: ' + index);
  1861. }
  1862. return this;
  1863. }
  1864. getComponent(index) {
  1865. switch (index) {
  1866. case 0:
  1867. return this.x;
  1868. case 1:
  1869. return this.y;
  1870. case 2:
  1871. return this.z;
  1872. case 3:
  1873. return this.w;
  1874. default:
  1875. throw new Error('index is out of range: ' + index);
  1876. }
  1877. }
  1878. clone() {
  1879. return new this.constructor(this.x, this.y, this.z, this.w);
  1880. }
  1881. copy(v) {
  1882. this.x = v.x;
  1883. this.y = v.y;
  1884. this.z = v.z;
  1885. this.w = v.w !== undefined ? v.w : 1;
  1886. return this;
  1887. }
  1888. add(v) {
  1889. this.x += v.x;
  1890. this.y += v.y;
  1891. this.z += v.z;
  1892. this.w += v.w;
  1893. return this;
  1894. }
  1895. addScalar(s) {
  1896. this.x += s;
  1897. this.y += s;
  1898. this.z += s;
  1899. this.w += s;
  1900. return this;
  1901. }
  1902. addVectors(a, b) {
  1903. this.x = a.x + b.x;
  1904. this.y = a.y + b.y;
  1905. this.z = a.z + b.z;
  1906. this.w = a.w + b.w;
  1907. return this;
  1908. }
  1909. addScaledVector(v, s) {
  1910. this.x += v.x * s;
  1911. this.y += v.y * s;
  1912. this.z += v.z * s;
  1913. this.w += v.w * s;
  1914. return this;
  1915. }
  1916. sub(v) {
  1917. this.x -= v.x;
  1918. this.y -= v.y;
  1919. this.z -= v.z;
  1920. this.w -= v.w;
  1921. return this;
  1922. }
  1923. subScalar(s) {
  1924. this.x -= s;
  1925. this.y -= s;
  1926. this.z -= s;
  1927. this.w -= s;
  1928. return this;
  1929. }
  1930. subVectors(a, b) {
  1931. this.x = a.x - b.x;
  1932. this.y = a.y - b.y;
  1933. this.z = a.z - b.z;
  1934. this.w = a.w - b.w;
  1935. return this;
  1936. }
  1937. multiply(v) {
  1938. this.x *= v.x;
  1939. this.y *= v.y;
  1940. this.z *= v.z;
  1941. this.w *= v.w;
  1942. return this;
  1943. }
  1944. multiplyScalar(scalar) {
  1945. this.x *= scalar;
  1946. this.y *= scalar;
  1947. this.z *= scalar;
  1948. this.w *= scalar;
  1949. return this;
  1950. }
  1951. applyMatrix4(m) {
  1952. const x = this.x,
  1953. y = this.y,
  1954. z = this.z,
  1955. w = this.w;
  1956. const e = m.elements;
  1957. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1958. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1959. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1960. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1961. return this;
  1962. }
  1963. divideScalar(scalar) {
  1964. return this.multiplyScalar(1 / scalar);
  1965. }
  1966. setAxisAngleFromQuaternion(q) {
  1967. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1968. // q is assumed to be normalized
  1969. this.w = 2 * Math.acos(q.w);
  1970. const s = Math.sqrt(1 - q.w * q.w);
  1971. if (s < 0.0001) {
  1972. this.x = 1;
  1973. this.y = 0;
  1974. this.z = 0;
  1975. } else {
  1976. this.x = q.x / s;
  1977. this.y = q.y / s;
  1978. this.z = q.z / s;
  1979. }
  1980. return this;
  1981. }
  1982. setAxisAngleFromRotationMatrix(m) {
  1983. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1984. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1985. let angle, x, y, z; // variables for result
  1986. const epsilon = 0.01,
  1987. // margin to allow for rounding errors
  1988. epsilon2 = 0.1,
  1989. // margin to distinguish between 0 and 180 degrees
  1990. te = m.elements,
  1991. m11 = te[0],
  1992. m12 = te[4],
  1993. m13 = te[8],
  1994. m21 = te[1],
  1995. m22 = te[5],
  1996. m23 = te[9],
  1997. m31 = te[2],
  1998. m32 = te[6],
  1999. m33 = te[10];
  2000. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2001. // singularity found
  2002. // first check for identity matrix which must have +1 for all terms
  2003. // in leading diagonal and zero in other terms
  2004. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2005. // this singularity is identity matrix so angle = 0
  2006. this.set(1, 0, 0, 0);
  2007. return this; // zero angle, arbitrary axis
  2008. } // otherwise this singularity is angle = 180
  2009. angle = Math.PI;
  2010. const xx = (m11 + 1) / 2;
  2011. const yy = (m22 + 1) / 2;
  2012. const zz = (m33 + 1) / 2;
  2013. const xy = (m12 + m21) / 4;
  2014. const xz = (m13 + m31) / 4;
  2015. const yz = (m23 + m32) / 4;
  2016. if (xx > yy && xx > zz) {
  2017. // m11 is the largest diagonal term
  2018. if (xx < epsilon) {
  2019. x = 0;
  2020. y = 0.707106781;
  2021. z = 0.707106781;
  2022. } else {
  2023. x = Math.sqrt(xx);
  2024. y = xy / x;
  2025. z = xz / x;
  2026. }
  2027. } else if (yy > zz) {
  2028. // m22 is the largest diagonal term
  2029. if (yy < epsilon) {
  2030. x = 0.707106781;
  2031. y = 0;
  2032. z = 0.707106781;
  2033. } else {
  2034. y = Math.sqrt(yy);
  2035. x = xy / y;
  2036. z = yz / y;
  2037. }
  2038. } else {
  2039. // m33 is the largest diagonal term so base result on this
  2040. if (zz < epsilon) {
  2041. x = 0.707106781;
  2042. y = 0.707106781;
  2043. z = 0;
  2044. } else {
  2045. z = Math.sqrt(zz);
  2046. x = xz / z;
  2047. y = yz / z;
  2048. }
  2049. }
  2050. this.set(x, y, z, angle);
  2051. return this; // return 180 deg rotation
  2052. } // as we have reached here there are no singularities so we can handle normally
  2053. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2054. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2055. // caught by singularity test above, but I've left it in just in case
  2056. this.x = (m32 - m23) / s;
  2057. this.y = (m13 - m31) / s;
  2058. this.z = (m21 - m12) / s;
  2059. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2060. return this;
  2061. }
  2062. min(v) {
  2063. this.x = Math.min(this.x, v.x);
  2064. this.y = Math.min(this.y, v.y);
  2065. this.z = Math.min(this.z, v.z);
  2066. this.w = Math.min(this.w, v.w);
  2067. return this;
  2068. }
  2069. max(v) {
  2070. this.x = Math.max(this.x, v.x);
  2071. this.y = Math.max(this.y, v.y);
  2072. this.z = Math.max(this.z, v.z);
  2073. this.w = Math.max(this.w, v.w);
  2074. return this;
  2075. }
  2076. clamp(min, max) {
  2077. // assumes min < max, componentwise
  2078. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2079. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2080. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2081. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2082. return this;
  2083. }
  2084. clampScalar(minVal, maxVal) {
  2085. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2086. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2087. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2088. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2089. return this;
  2090. }
  2091. clampLength(min, max) {
  2092. const length = this.length();
  2093. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2094. }
  2095. floor() {
  2096. this.x = Math.floor(this.x);
  2097. this.y = Math.floor(this.y);
  2098. this.z = Math.floor(this.z);
  2099. this.w = Math.floor(this.w);
  2100. return this;
  2101. }
  2102. ceil() {
  2103. this.x = Math.ceil(this.x);
  2104. this.y = Math.ceil(this.y);
  2105. this.z = Math.ceil(this.z);
  2106. this.w = Math.ceil(this.w);
  2107. return this;
  2108. }
  2109. round() {
  2110. this.x = Math.round(this.x);
  2111. this.y = Math.round(this.y);
  2112. this.z = Math.round(this.z);
  2113. this.w = Math.round(this.w);
  2114. return this;
  2115. }
  2116. roundToZero() {
  2117. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2118. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2119. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2120. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2121. return this;
  2122. }
  2123. negate() {
  2124. this.x = -this.x;
  2125. this.y = -this.y;
  2126. this.z = -this.z;
  2127. this.w = -this.w;
  2128. return this;
  2129. }
  2130. dot(v) {
  2131. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2132. }
  2133. lengthSq() {
  2134. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2135. }
  2136. length() {
  2137. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2138. }
  2139. manhattanLength() {
  2140. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2141. }
  2142. normalize() {
  2143. return this.divideScalar(this.length() || 1);
  2144. }
  2145. setLength(length) {
  2146. return this.normalize().multiplyScalar(length);
  2147. }
  2148. lerp(v, alpha) {
  2149. this.x += (v.x - this.x) * alpha;
  2150. this.y += (v.y - this.y) * alpha;
  2151. this.z += (v.z - this.z) * alpha;
  2152. this.w += (v.w - this.w) * alpha;
  2153. return this;
  2154. }
  2155. lerpVectors(v1, v2, alpha) {
  2156. this.x = v1.x + (v2.x - v1.x) * alpha;
  2157. this.y = v1.y + (v2.y - v1.y) * alpha;
  2158. this.z = v1.z + (v2.z - v1.z) * alpha;
  2159. this.w = v1.w + (v2.w - v1.w) * alpha;
  2160. return this;
  2161. }
  2162. equals(v) {
  2163. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2164. }
  2165. fromArray(array, offset = 0) {
  2166. this.x = array[offset];
  2167. this.y = array[offset + 1];
  2168. this.z = array[offset + 2];
  2169. this.w = array[offset + 3];
  2170. return this;
  2171. }
  2172. toArray(array = [], offset = 0) {
  2173. array[offset] = this.x;
  2174. array[offset + 1] = this.y;
  2175. array[offset + 2] = this.z;
  2176. array[offset + 3] = this.w;
  2177. return array;
  2178. }
  2179. fromBufferAttribute(attribute, index) {
  2180. this.x = attribute.getX(index);
  2181. this.y = attribute.getY(index);
  2182. this.z = attribute.getZ(index);
  2183. this.w = attribute.getW(index);
  2184. return this;
  2185. }
  2186. random() {
  2187. this.x = Math.random();
  2188. this.y = Math.random();
  2189. this.z = Math.random();
  2190. this.w = Math.random();
  2191. return this;
  2192. }
  2193. *[Symbol.iterator]() {
  2194. yield this.x;
  2195. yield this.y;
  2196. yield this.z;
  2197. yield this.w;
  2198. }
  2199. }
  2200. /*
  2201. In options, we can specify:
  2202. * Texture parameters for an auto-generated target texture
  2203. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2204. */
  2205. class WebGLRenderTarget extends EventDispatcher {
  2206. constructor(width, height, options = {}) {
  2207. super();
  2208. this.isWebGLRenderTarget = true;
  2209. this.width = width;
  2210. this.height = height;
  2211. this.depth = 1;
  2212. this.scissor = new Vector4(0, 0, width, height);
  2213. this.scissorTest = false;
  2214. this.viewport = new Vector4(0, 0, width, height);
  2215. const image = {
  2216. width: width,
  2217. height: height,
  2218. depth: 1
  2219. };
  2220. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2221. this.texture.isRenderTargetTexture = true;
  2222. this.texture.flipY = false;
  2223. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2224. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2225. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2226. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2227. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2228. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2229. this.samples = options.samples !== undefined ? options.samples : 0;
  2230. }
  2231. setSize(width, height, depth = 1) {
  2232. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2233. this.width = width;
  2234. this.height = height;
  2235. this.depth = depth;
  2236. this.texture.image.width = width;
  2237. this.texture.image.height = height;
  2238. this.texture.image.depth = depth;
  2239. this.dispose();
  2240. }
  2241. this.viewport.set(0, 0, width, height);
  2242. this.scissor.set(0, 0, width, height);
  2243. }
  2244. clone() {
  2245. return new this.constructor().copy(this);
  2246. }
  2247. copy(source) {
  2248. this.width = source.width;
  2249. this.height = source.height;
  2250. this.depth = source.depth;
  2251. this.viewport.copy(source.viewport);
  2252. this.texture = source.texture.clone();
  2253. this.texture.isRenderTargetTexture = true; // ensure image object is not shared, see #20328
  2254. const image = Object.assign({}, source.texture.image);
  2255. this.texture.source = new Source(image);
  2256. this.depthBuffer = source.depthBuffer;
  2257. this.stencilBuffer = source.stencilBuffer;
  2258. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2259. this.samples = source.samples;
  2260. return this;
  2261. }
  2262. dispose() {
  2263. this.dispatchEvent({
  2264. type: 'dispose'
  2265. });
  2266. }
  2267. }
  2268. class DataArrayTexture extends Texture {
  2269. constructor(data = null, width = 1, height = 1, depth = 1) {
  2270. super(null);
  2271. this.isDataArrayTexture = true;
  2272. this.image = {
  2273. data,
  2274. width,
  2275. height,
  2276. depth
  2277. };
  2278. this.magFilter = NearestFilter;
  2279. this.minFilter = NearestFilter;
  2280. this.wrapR = ClampToEdgeWrapping;
  2281. this.generateMipmaps = false;
  2282. this.flipY = false;
  2283. this.unpackAlignment = 1;
  2284. }
  2285. }
  2286. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2287. constructor(width, height, depth) {
  2288. super(width, height);
  2289. this.isWebGLArrayRenderTarget = true;
  2290. this.depth = depth;
  2291. this.texture = new DataArrayTexture(null, width, height, depth);
  2292. this.texture.isRenderTargetTexture = true;
  2293. }
  2294. }
  2295. class Data3DTexture extends Texture {
  2296. constructor(data = null, width = 1, height = 1, depth = 1) {
  2297. // We're going to add .setXXX() methods for setting properties later.
  2298. // Users can still set in DataTexture3D directly.
  2299. //
  2300. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2301. // texture.anisotropy = 16;
  2302. //
  2303. // See #14839
  2304. super(null);
  2305. this.isData3DTexture = true;
  2306. this.image = {
  2307. data,
  2308. width,
  2309. height,
  2310. depth
  2311. };
  2312. this.magFilter = NearestFilter;
  2313. this.minFilter = NearestFilter;
  2314. this.wrapR = ClampToEdgeWrapping;
  2315. this.generateMipmaps = false;
  2316. this.flipY = false;
  2317. this.unpackAlignment = 1;
  2318. }
  2319. }
  2320. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2321. constructor(width, height, depth) {
  2322. super(width, height);
  2323. this.isWebGL3DRenderTarget = true;
  2324. this.depth = depth;
  2325. this.texture = new Data3DTexture(null, width, height, depth);
  2326. this.texture.isRenderTargetTexture = true;
  2327. }
  2328. }
  2329. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2330. constructor(width, height, count, options = {}) {
  2331. super(width, height, options);
  2332. this.isWebGLMultipleRenderTargets = true;
  2333. const texture = this.texture;
  2334. this.texture = [];
  2335. for (let i = 0; i < count; i++) {
  2336. this.texture[i] = texture.clone();
  2337. this.texture[i].isRenderTargetTexture = true;
  2338. }
  2339. }
  2340. setSize(width, height, depth = 1) {
  2341. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2342. this.width = width;
  2343. this.height = height;
  2344. this.depth = depth;
  2345. for (let i = 0, il = this.texture.length; i < il; i++) {
  2346. this.texture[i].image.width = width;
  2347. this.texture[i].image.height = height;
  2348. this.texture[i].image.depth = depth;
  2349. }
  2350. this.dispose();
  2351. }
  2352. this.viewport.set(0, 0, width, height);
  2353. this.scissor.set(0, 0, width, height);
  2354. return this;
  2355. }
  2356. copy(source) {
  2357. this.dispose();
  2358. this.width = source.width;
  2359. this.height = source.height;
  2360. this.depth = source.depth;
  2361. this.viewport.set(0, 0, this.width, this.height);
  2362. this.scissor.set(0, 0, this.width, this.height);
  2363. this.depthBuffer = source.depthBuffer;
  2364. this.stencilBuffer = source.stencilBuffer;
  2365. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2366. this.texture.length = 0;
  2367. for (let i = 0, il = source.texture.length; i < il; i++) {
  2368. this.texture[i] = source.texture[i].clone();
  2369. this.texture[i].isRenderTargetTexture = true;
  2370. }
  2371. return this;
  2372. }
  2373. }
  2374. class Quaternion {
  2375. constructor(x = 0, y = 0, z = 0, w = 1) {
  2376. this.isQuaternion = true;
  2377. this._x = x;
  2378. this._y = y;
  2379. this._z = z;
  2380. this._w = w;
  2381. }
  2382. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2383. // fuzz-free, array-based Quaternion SLERP operation
  2384. let x0 = src0[srcOffset0 + 0],
  2385. y0 = src0[srcOffset0 + 1],
  2386. z0 = src0[srcOffset0 + 2],
  2387. w0 = src0[srcOffset0 + 3];
  2388. const x1 = src1[srcOffset1 + 0],
  2389. y1 = src1[srcOffset1 + 1],
  2390. z1 = src1[srcOffset1 + 2],
  2391. w1 = src1[srcOffset1 + 3];
  2392. if (t === 0) {
  2393. dst[dstOffset + 0] = x0;
  2394. dst[dstOffset + 1] = y0;
  2395. dst[dstOffset + 2] = z0;
  2396. dst[dstOffset + 3] = w0;
  2397. return;
  2398. }
  2399. if (t === 1) {
  2400. dst[dstOffset + 0] = x1;
  2401. dst[dstOffset + 1] = y1;
  2402. dst[dstOffset + 2] = z1;
  2403. dst[dstOffset + 3] = w1;
  2404. return;
  2405. }
  2406. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2407. let s = 1 - t;
  2408. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2409. dir = cos >= 0 ? 1 : -1,
  2410. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2411. if (sqrSin > Number.EPSILON) {
  2412. const sin = Math.sqrt(sqrSin),
  2413. len = Math.atan2(sin, cos * dir);
  2414. s = Math.sin(s * len) / sin;
  2415. t = Math.sin(t * len) / sin;
  2416. }
  2417. const tDir = t * dir;
  2418. x0 = x0 * s + x1 * tDir;
  2419. y0 = y0 * s + y1 * tDir;
  2420. z0 = z0 * s + z1 * tDir;
  2421. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2422. if (s === 1 - t) {
  2423. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2424. x0 *= f;
  2425. y0 *= f;
  2426. z0 *= f;
  2427. w0 *= f;
  2428. }
  2429. }
  2430. dst[dstOffset] = x0;
  2431. dst[dstOffset + 1] = y0;
  2432. dst[dstOffset + 2] = z0;
  2433. dst[dstOffset + 3] = w0;
  2434. }
  2435. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2436. const x0 = src0[srcOffset0];
  2437. const y0 = src0[srcOffset0 + 1];
  2438. const z0 = src0[srcOffset0 + 2];
  2439. const w0 = src0[srcOffset0 + 3];
  2440. const x1 = src1[srcOffset1];
  2441. const y1 = src1[srcOffset1 + 1];
  2442. const z1 = src1[srcOffset1 + 2];
  2443. const w1 = src1[srcOffset1 + 3];
  2444. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2445. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2446. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2447. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2448. return dst;
  2449. }
  2450. get x() {
  2451. return this._x;
  2452. }
  2453. set x(value) {
  2454. this._x = value;
  2455. this._onChangeCallback();
  2456. }
  2457. get y() {
  2458. return this._y;
  2459. }
  2460. set y(value) {
  2461. this._y = value;
  2462. this._onChangeCallback();
  2463. }
  2464. get z() {
  2465. return this._z;
  2466. }
  2467. set z(value) {
  2468. this._z = value;
  2469. this._onChangeCallback();
  2470. }
  2471. get w() {
  2472. return this._w;
  2473. }
  2474. set w(value) {
  2475. this._w = value;
  2476. this._onChangeCallback();
  2477. }
  2478. set(x, y, z, w) {
  2479. this._x = x;
  2480. this._y = y;
  2481. this._z = z;
  2482. this._w = w;
  2483. this._onChangeCallback();
  2484. return this;
  2485. }
  2486. clone() {
  2487. return new this.constructor(this._x, this._y, this._z, this._w);
  2488. }
  2489. copy(quaternion) {
  2490. this._x = quaternion.x;
  2491. this._y = quaternion.y;
  2492. this._z = quaternion.z;
  2493. this._w = quaternion.w;
  2494. this._onChangeCallback();
  2495. return this;
  2496. }
  2497. setFromEuler(euler, update) {
  2498. const x = euler._x,
  2499. y = euler._y,
  2500. z = euler._z,
  2501. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2502. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2503. // content/SpinCalc.m
  2504. const cos = Math.cos;
  2505. const sin = Math.sin;
  2506. const c1 = cos(x / 2);
  2507. const c2 = cos(y / 2);
  2508. const c3 = cos(z / 2);
  2509. const s1 = sin(x / 2);
  2510. const s2 = sin(y / 2);
  2511. const s3 = sin(z / 2);
  2512. switch (order) {
  2513. case 'XYZ':
  2514. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2515. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2516. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2517. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2518. break;
  2519. case 'YXZ':
  2520. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2521. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2522. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2523. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2524. break;
  2525. case 'ZXY':
  2526. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2527. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2528. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2529. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2530. break;
  2531. case 'ZYX':
  2532. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2533. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2534. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2535. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2536. break;
  2537. case 'YZX':
  2538. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2539. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2540. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2541. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2542. break;
  2543. case 'XZY':
  2544. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2545. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2546. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2547. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2548. break;
  2549. default:
  2550. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2551. }
  2552. if (update !== false) this._onChangeCallback();
  2553. return this;
  2554. }
  2555. setFromAxisAngle(axis, angle) {
  2556. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2557. // assumes axis is normalized
  2558. const halfAngle = angle / 2,
  2559. s = Math.sin(halfAngle);
  2560. this._x = axis.x * s;
  2561. this._y = axis.y * s;
  2562. this._z = axis.z * s;
  2563. this._w = Math.cos(halfAngle);
  2564. this._onChangeCallback();
  2565. return this;
  2566. }
  2567. setFromRotationMatrix(m) {
  2568. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2569. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2570. const te = m.elements,
  2571. m11 = te[0],
  2572. m12 = te[4],
  2573. m13 = te[8],
  2574. m21 = te[1],
  2575. m22 = te[5],
  2576. m23 = te[9],
  2577. m31 = te[2],
  2578. m32 = te[6],
  2579. m33 = te[10],
  2580. trace = m11 + m22 + m33;
  2581. if (trace > 0) {
  2582. const s = 0.5 / Math.sqrt(trace + 1.0);
  2583. this._w = 0.25 / s;
  2584. this._x = (m32 - m23) * s;
  2585. this._y = (m13 - m31) * s;
  2586. this._z = (m21 - m12) * s;
  2587. } else if (m11 > m22 && m11 > m33) {
  2588. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2589. this._w = (m32 - m23) / s;
  2590. this._x = 0.25 * s;
  2591. this._y = (m12 + m21) / s;
  2592. this._z = (m13 + m31) / s;
  2593. } else if (m22 > m33) {
  2594. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2595. this._w = (m13 - m31) / s;
  2596. this._x = (m12 + m21) / s;
  2597. this._y = 0.25 * s;
  2598. this._z = (m23 + m32) / s;
  2599. } else {
  2600. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2601. this._w = (m21 - m12) / s;
  2602. this._x = (m13 + m31) / s;
  2603. this._y = (m23 + m32) / s;
  2604. this._z = 0.25 * s;
  2605. }
  2606. this._onChangeCallback();
  2607. return this;
  2608. }
  2609. setFromUnitVectors(vFrom, vTo) {
  2610. // assumes direction vectors vFrom and vTo are normalized
  2611. let r = vFrom.dot(vTo) + 1;
  2612. if (r < Number.EPSILON) {
  2613. // vFrom and vTo point in opposite directions
  2614. r = 0;
  2615. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2616. this._x = -vFrom.y;
  2617. this._y = vFrom.x;
  2618. this._z = 0;
  2619. this._w = r;
  2620. } else {
  2621. this._x = 0;
  2622. this._y = -vFrom.z;
  2623. this._z = vFrom.y;
  2624. this._w = r;
  2625. }
  2626. } else {
  2627. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2628. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2629. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2630. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2631. this._w = r;
  2632. }
  2633. return this.normalize();
  2634. }
  2635. angleTo(q) {
  2636. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2637. }
  2638. rotateTowards(q, step) {
  2639. const angle = this.angleTo(q);
  2640. if (angle === 0) return this;
  2641. const t = Math.min(1, step / angle);
  2642. this.slerp(q, t);
  2643. return this;
  2644. }
  2645. identity() {
  2646. return this.set(0, 0, 0, 1);
  2647. }
  2648. invert() {
  2649. // quaternion is assumed to have unit length
  2650. return this.conjugate();
  2651. }
  2652. conjugate() {
  2653. this._x *= -1;
  2654. this._y *= -1;
  2655. this._z *= -1;
  2656. this._onChangeCallback();
  2657. return this;
  2658. }
  2659. dot(v) {
  2660. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2661. }
  2662. lengthSq() {
  2663. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2664. }
  2665. length() {
  2666. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2667. }
  2668. normalize() {
  2669. let l = this.length();
  2670. if (l === 0) {
  2671. this._x = 0;
  2672. this._y = 0;
  2673. this._z = 0;
  2674. this._w = 1;
  2675. } else {
  2676. l = 1 / l;
  2677. this._x = this._x * l;
  2678. this._y = this._y * l;
  2679. this._z = this._z * l;
  2680. this._w = this._w * l;
  2681. }
  2682. this._onChangeCallback();
  2683. return this;
  2684. }
  2685. multiply(q) {
  2686. return this.multiplyQuaternions(this, q);
  2687. }
  2688. premultiply(q) {
  2689. return this.multiplyQuaternions(q, this);
  2690. }
  2691. multiplyQuaternions(a, b) {
  2692. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2693. const qax = a._x,
  2694. qay = a._y,
  2695. qaz = a._z,
  2696. qaw = a._w;
  2697. const qbx = b._x,
  2698. qby = b._y,
  2699. qbz = b._z,
  2700. qbw = b._w;
  2701. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2702. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2703. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2704. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2705. this._onChangeCallback();
  2706. return this;
  2707. }
  2708. slerp(qb, t) {
  2709. if (t === 0) return this;
  2710. if (t === 1) return this.copy(qb);
  2711. const x = this._x,
  2712. y = this._y,
  2713. z = this._z,
  2714. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2715. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2716. if (cosHalfTheta < 0) {
  2717. this._w = -qb._w;
  2718. this._x = -qb._x;
  2719. this._y = -qb._y;
  2720. this._z = -qb._z;
  2721. cosHalfTheta = -cosHalfTheta;
  2722. } else {
  2723. this.copy(qb);
  2724. }
  2725. if (cosHalfTheta >= 1.0) {
  2726. this._w = w;
  2727. this._x = x;
  2728. this._y = y;
  2729. this._z = z;
  2730. return this;
  2731. }
  2732. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2733. if (sqrSinHalfTheta <= Number.EPSILON) {
  2734. const s = 1 - t;
  2735. this._w = s * w + t * this._w;
  2736. this._x = s * x + t * this._x;
  2737. this._y = s * y + t * this._y;
  2738. this._z = s * z + t * this._z;
  2739. this.normalize();
  2740. this._onChangeCallback();
  2741. return this;
  2742. }
  2743. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2744. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2745. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2746. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2747. this._w = w * ratioA + this._w * ratioB;
  2748. this._x = x * ratioA + this._x * ratioB;
  2749. this._y = y * ratioA + this._y * ratioB;
  2750. this._z = z * ratioA + this._z * ratioB;
  2751. this._onChangeCallback();
  2752. return this;
  2753. }
  2754. slerpQuaternions(qa, qb, t) {
  2755. return this.copy(qa).slerp(qb, t);
  2756. }
  2757. random() {
  2758. // Derived from http://planning.cs.uiuc.edu/node198.html
  2759. // Note, this source uses w, x, y, z ordering,
  2760. // so we swap the order below.
  2761. const u1 = Math.random();
  2762. const sqrt1u1 = Math.sqrt(1 - u1);
  2763. const sqrtu1 = Math.sqrt(u1);
  2764. const u2 = 2 * Math.PI * Math.random();
  2765. const u3 = 2 * Math.PI * Math.random();
  2766. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2767. }
  2768. equals(quaternion) {
  2769. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2770. }
  2771. fromArray(array, offset = 0) {
  2772. this._x = array[offset];
  2773. this._y = array[offset + 1];
  2774. this._z = array[offset + 2];
  2775. this._w = array[offset + 3];
  2776. this._onChangeCallback();
  2777. return this;
  2778. }
  2779. toArray(array = [], offset = 0) {
  2780. array[offset] = this._x;
  2781. array[offset + 1] = this._y;
  2782. array[offset + 2] = this._z;
  2783. array[offset + 3] = this._w;
  2784. return array;
  2785. }
  2786. fromBufferAttribute(attribute, index) {
  2787. this._x = attribute.getX(index);
  2788. this._y = attribute.getY(index);
  2789. this._z = attribute.getZ(index);
  2790. this._w = attribute.getW(index);
  2791. return this;
  2792. }
  2793. _onChange(callback) {
  2794. this._onChangeCallback = callback;
  2795. return this;
  2796. }
  2797. _onChangeCallback() {}
  2798. *[Symbol.iterator]() {
  2799. yield this._x;
  2800. yield this._y;
  2801. yield this._z;
  2802. yield this._w;
  2803. }
  2804. }
  2805. class Vector3 {
  2806. constructor(x = 0, y = 0, z = 0) {
  2807. Vector3.prototype.isVector3 = true;
  2808. this.x = x;
  2809. this.y = y;
  2810. this.z = z;
  2811. }
  2812. set(x, y, z) {
  2813. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2814. this.x = x;
  2815. this.y = y;
  2816. this.z = z;
  2817. return this;
  2818. }
  2819. setScalar(scalar) {
  2820. this.x = scalar;
  2821. this.y = scalar;
  2822. this.z = scalar;
  2823. return this;
  2824. }
  2825. setX(x) {
  2826. this.x = x;
  2827. return this;
  2828. }
  2829. setY(y) {
  2830. this.y = y;
  2831. return this;
  2832. }
  2833. setZ(z) {
  2834. this.z = z;
  2835. return this;
  2836. }
  2837. setComponent(index, value) {
  2838. switch (index) {
  2839. case 0:
  2840. this.x = value;
  2841. break;
  2842. case 1:
  2843. this.y = value;
  2844. break;
  2845. case 2:
  2846. this.z = value;
  2847. break;
  2848. default:
  2849. throw new Error('index is out of range: ' + index);
  2850. }
  2851. return this;
  2852. }
  2853. getComponent(index) {
  2854. switch (index) {
  2855. case 0:
  2856. return this.x;
  2857. case 1:
  2858. return this.y;
  2859. case 2:
  2860. return this.z;
  2861. default:
  2862. throw new Error('index is out of range: ' + index);
  2863. }
  2864. }
  2865. clone() {
  2866. return new this.constructor(this.x, this.y, this.z);
  2867. }
  2868. copy(v) {
  2869. this.x = v.x;
  2870. this.y = v.y;
  2871. this.z = v.z;
  2872. return this;
  2873. }
  2874. add(v) {
  2875. this.x += v.x;
  2876. this.y += v.y;
  2877. this.z += v.z;
  2878. return this;
  2879. }
  2880. addScalar(s) {
  2881. this.x += s;
  2882. this.y += s;
  2883. this.z += s;
  2884. return this;
  2885. }
  2886. addVectors(a, b) {
  2887. this.x = a.x + b.x;
  2888. this.y = a.y + b.y;
  2889. this.z = a.z + b.z;
  2890. return this;
  2891. }
  2892. addScaledVector(v, s) {
  2893. this.x += v.x * s;
  2894. this.y += v.y * s;
  2895. this.z += v.z * s;
  2896. return this;
  2897. }
  2898. sub(v) {
  2899. this.x -= v.x;
  2900. this.y -= v.y;
  2901. this.z -= v.z;
  2902. return this;
  2903. }
  2904. subScalar(s) {
  2905. this.x -= s;
  2906. this.y -= s;
  2907. this.z -= s;
  2908. return this;
  2909. }
  2910. subVectors(a, b) {
  2911. this.x = a.x - b.x;
  2912. this.y = a.y - b.y;
  2913. this.z = a.z - b.z;
  2914. return this;
  2915. }
  2916. multiply(v) {
  2917. this.x *= v.x;
  2918. this.y *= v.y;
  2919. this.z *= v.z;
  2920. return this;
  2921. }
  2922. multiplyScalar(scalar) {
  2923. this.x *= scalar;
  2924. this.y *= scalar;
  2925. this.z *= scalar;
  2926. return this;
  2927. }
  2928. multiplyVectors(a, b) {
  2929. this.x = a.x * b.x;
  2930. this.y = a.y * b.y;
  2931. this.z = a.z * b.z;
  2932. return this;
  2933. }
  2934. applyEuler(euler) {
  2935. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2936. }
  2937. applyAxisAngle(axis, angle) {
  2938. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2939. }
  2940. applyMatrix3(m) {
  2941. const x = this.x,
  2942. y = this.y,
  2943. z = this.z;
  2944. const e = m.elements;
  2945. this.x = e[0] * x + e[3] * y + e[6] * z;
  2946. this.y = e[1] * x + e[4] * y + e[7] * z;
  2947. this.z = e[2] * x + e[5] * y + e[8] * z;
  2948. return this;
  2949. }
  2950. applyNormalMatrix(m) {
  2951. return this.applyMatrix3(m).normalize();
  2952. }
  2953. applyMatrix4(m) {
  2954. const x = this.x,
  2955. y = this.y,
  2956. z = this.z;
  2957. const e = m.elements;
  2958. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2959. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2960. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2961. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2962. return this;
  2963. }
  2964. applyQuaternion(q) {
  2965. const x = this.x,
  2966. y = this.y,
  2967. z = this.z;
  2968. const qx = q.x,
  2969. qy = q.y,
  2970. qz = q.z,
  2971. qw = q.w; // calculate quat * vector
  2972. const ix = qw * x + qy * z - qz * y;
  2973. const iy = qw * y + qz * x - qx * z;
  2974. const iz = qw * z + qx * y - qy * x;
  2975. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2976. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2977. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2978. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2979. return this;
  2980. }
  2981. project(camera) {
  2982. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2983. }
  2984. unproject(camera) {
  2985. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2986. }
  2987. transformDirection(m) {
  2988. // input: THREE.Matrix4 affine matrix
  2989. // vector interpreted as a direction
  2990. const x = this.x,
  2991. y = this.y,
  2992. z = this.z;
  2993. const e = m.elements;
  2994. this.x = e[0] * x + e[4] * y + e[8] * z;
  2995. this.y = e[1] * x + e[5] * y + e[9] * z;
  2996. this.z = e[2] * x + e[6] * y + e[10] * z;
  2997. return this.normalize();
  2998. }
  2999. divide(v) {
  3000. this.x /= v.x;
  3001. this.y /= v.y;
  3002. this.z /= v.z;
  3003. return this;
  3004. }
  3005. divideScalar(scalar) {
  3006. return this.multiplyScalar(1 / scalar);
  3007. }
  3008. min(v) {
  3009. this.x = Math.min(this.x, v.x);
  3010. this.y = Math.min(this.y, v.y);
  3011. this.z = Math.min(this.z, v.z);
  3012. return this;
  3013. }
  3014. max(v) {
  3015. this.x = Math.max(this.x, v.x);
  3016. this.y = Math.max(this.y, v.y);
  3017. this.z = Math.max(this.z, v.z);
  3018. return this;
  3019. }
  3020. clamp(min, max) {
  3021. // assumes min < max, componentwise
  3022. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3023. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3024. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3025. return this;
  3026. }
  3027. clampScalar(minVal, maxVal) {
  3028. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3029. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3030. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3031. return this;
  3032. }
  3033. clampLength(min, max) {
  3034. const length = this.length();
  3035. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3036. }
  3037. floor() {
  3038. this.x = Math.floor(this.x);
  3039. this.y = Math.floor(this.y);
  3040. this.z = Math.floor(this.z);
  3041. return this;
  3042. }
  3043. ceil() {
  3044. this.x = Math.ceil(this.x);
  3045. this.y = Math.ceil(this.y);
  3046. this.z = Math.ceil(this.z);
  3047. return this;
  3048. }
  3049. round() {
  3050. this.x = Math.round(this.x);
  3051. this.y = Math.round(this.y);
  3052. this.z = Math.round(this.z);
  3053. return this;
  3054. }
  3055. roundToZero() {
  3056. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3057. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3058. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3059. return this;
  3060. }
  3061. negate() {
  3062. this.x = -this.x;
  3063. this.y = -this.y;
  3064. this.z = -this.z;
  3065. return this;
  3066. }
  3067. dot(v) {
  3068. return this.x * v.x + this.y * v.y + this.z * v.z;
  3069. } // TODO lengthSquared?
  3070. lengthSq() {
  3071. return this.x * this.x + this.y * this.y + this.z * this.z;
  3072. }
  3073. length() {
  3074. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3075. }
  3076. manhattanLength() {
  3077. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3078. }
  3079. normalize() {
  3080. return this.divideScalar(this.length() || 1);
  3081. }
  3082. setLength(length) {
  3083. return this.normalize().multiplyScalar(length);
  3084. }
  3085. lerp(v, alpha) {
  3086. this.x += (v.x - this.x) * alpha;
  3087. this.y += (v.y - this.y) * alpha;
  3088. this.z += (v.z - this.z) * alpha;
  3089. return this;
  3090. }
  3091. lerpVectors(v1, v2, alpha) {
  3092. this.x = v1.x + (v2.x - v1.x) * alpha;
  3093. this.y = v1.y + (v2.y - v1.y) * alpha;
  3094. this.z = v1.z + (v2.z - v1.z) * alpha;
  3095. return this;
  3096. }
  3097. cross(v) {
  3098. return this.crossVectors(this, v);
  3099. }
  3100. crossVectors(a, b) {
  3101. const ax = a.x,
  3102. ay = a.y,
  3103. az = a.z;
  3104. const bx = b.x,
  3105. by = b.y,
  3106. bz = b.z;
  3107. this.x = ay * bz - az * by;
  3108. this.y = az * bx - ax * bz;
  3109. this.z = ax * by - ay * bx;
  3110. return this;
  3111. }
  3112. projectOnVector(v) {
  3113. const denominator = v.lengthSq();
  3114. if (denominator === 0) return this.set(0, 0, 0);
  3115. const scalar = v.dot(this) / denominator;
  3116. return this.copy(v).multiplyScalar(scalar);
  3117. }
  3118. projectOnPlane(planeNormal) {
  3119. _vector$c.copy(this).projectOnVector(planeNormal);
  3120. return this.sub(_vector$c);
  3121. }
  3122. reflect(normal) {
  3123. // reflect incident vector off plane orthogonal to normal
  3124. // normal is assumed to have unit length
  3125. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3126. }
  3127. angleTo(v) {
  3128. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3129. if (denominator === 0) return Math.PI / 2;
  3130. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  3131. return Math.acos(clamp(theta, -1, 1));
  3132. }
  3133. distanceTo(v) {
  3134. return Math.sqrt(this.distanceToSquared(v));
  3135. }
  3136. distanceToSquared(v) {
  3137. const dx = this.x - v.x,
  3138. dy = this.y - v.y,
  3139. dz = this.z - v.z;
  3140. return dx * dx + dy * dy + dz * dz;
  3141. }
  3142. manhattanDistanceTo(v) {
  3143. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3144. }
  3145. setFromSpherical(s) {
  3146. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3147. }
  3148. setFromSphericalCoords(radius, phi, theta) {
  3149. const sinPhiRadius = Math.sin(phi) * radius;
  3150. this.x = sinPhiRadius * Math.sin(theta);
  3151. this.y = Math.cos(phi) * radius;
  3152. this.z = sinPhiRadius * Math.cos(theta);
  3153. return this;
  3154. }
  3155. setFromCylindrical(c) {
  3156. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3157. }
  3158. setFromCylindricalCoords(radius, theta, y) {
  3159. this.x = radius * Math.sin(theta);
  3160. this.y = y;
  3161. this.z = radius * Math.cos(theta);
  3162. return this;
  3163. }
  3164. setFromMatrixPosition(m) {
  3165. const e = m.elements;
  3166. this.x = e[12];
  3167. this.y = e[13];
  3168. this.z = e[14];
  3169. return this;
  3170. }
  3171. setFromMatrixScale(m) {
  3172. const sx = this.setFromMatrixColumn(m, 0).length();
  3173. const sy = this.setFromMatrixColumn(m, 1).length();
  3174. const sz = this.setFromMatrixColumn(m, 2).length();
  3175. this.x = sx;
  3176. this.y = sy;
  3177. this.z = sz;
  3178. return this;
  3179. }
  3180. setFromMatrixColumn(m, index) {
  3181. return this.fromArray(m.elements, index * 4);
  3182. }
  3183. setFromMatrix3Column(m, index) {
  3184. return this.fromArray(m.elements, index * 3);
  3185. }
  3186. setFromEuler(e) {
  3187. this.x = e._x;
  3188. this.y = e._y;
  3189. this.z = e._z;
  3190. return this;
  3191. }
  3192. equals(v) {
  3193. return v.x === this.x && v.y === this.y && v.z === this.z;
  3194. }
  3195. fromArray(array, offset = 0) {
  3196. this.x = array[offset];
  3197. this.y = array[offset + 1];
  3198. this.z = array[offset + 2];
  3199. return this;
  3200. }
  3201. toArray(array = [], offset = 0) {
  3202. array[offset] = this.x;
  3203. array[offset + 1] = this.y;
  3204. array[offset + 2] = this.z;
  3205. return array;
  3206. }
  3207. fromBufferAttribute(attribute, index) {
  3208. this.x = attribute.getX(index);
  3209. this.y = attribute.getY(index);
  3210. this.z = attribute.getZ(index);
  3211. return this;
  3212. }
  3213. random() {
  3214. this.x = Math.random();
  3215. this.y = Math.random();
  3216. this.z = Math.random();
  3217. return this;
  3218. }
  3219. randomDirection() {
  3220. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3221. const u = (Math.random() - 0.5) * 2;
  3222. const t = Math.random() * Math.PI * 2;
  3223. const f = Math.sqrt(1 - u ** 2);
  3224. this.x = f * Math.cos(t);
  3225. this.y = f * Math.sin(t);
  3226. this.z = u;
  3227. return this;
  3228. }
  3229. *[Symbol.iterator]() {
  3230. yield this.x;
  3231. yield this.y;
  3232. yield this.z;
  3233. }
  3234. }
  3235. const _vector$c = /*@__PURE__*/new Vector3();
  3236. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3237. class Box3 {
  3238. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3239. this.isBox3 = true;
  3240. this.min = min;
  3241. this.max = max;
  3242. }
  3243. set(min, max) {
  3244. this.min.copy(min);
  3245. this.max.copy(max);
  3246. return this;
  3247. }
  3248. setFromArray(array) {
  3249. let minX = +Infinity;
  3250. let minY = +Infinity;
  3251. let minZ = +Infinity;
  3252. let maxX = -Infinity;
  3253. let maxY = -Infinity;
  3254. let maxZ = -Infinity;
  3255. for (let i = 0, l = array.length; i < l; i += 3) {
  3256. const x = array[i];
  3257. const y = array[i + 1];
  3258. const z = array[i + 2];
  3259. if (x < minX) minX = x;
  3260. if (y < minY) minY = y;
  3261. if (z < minZ) minZ = z;
  3262. if (x > maxX) maxX = x;
  3263. if (y > maxY) maxY = y;
  3264. if (z > maxZ) maxZ = z;
  3265. }
  3266. this.min.set(minX, minY, minZ);
  3267. this.max.set(maxX, maxY, maxZ);
  3268. return this;
  3269. }
  3270. setFromBufferAttribute(attribute) {
  3271. let minX = +Infinity;
  3272. let minY = +Infinity;
  3273. let minZ = +Infinity;
  3274. let maxX = -Infinity;
  3275. let maxY = -Infinity;
  3276. let maxZ = -Infinity;
  3277. for (let i = 0, l = attribute.count; i < l; i++) {
  3278. const x = attribute.getX(i);
  3279. const y = attribute.getY(i);
  3280. const z = attribute.getZ(i);
  3281. if (x < minX) minX = x;
  3282. if (y < minY) minY = y;
  3283. if (z < minZ) minZ = z;
  3284. if (x > maxX) maxX = x;
  3285. if (y > maxY) maxY = y;
  3286. if (z > maxZ) maxZ = z;
  3287. }
  3288. this.min.set(minX, minY, minZ);
  3289. this.max.set(maxX, maxY, maxZ);
  3290. return this;
  3291. }
  3292. setFromPoints(points) {
  3293. this.makeEmpty();
  3294. for (let i = 0, il = points.length; i < il; i++) {
  3295. this.expandByPoint(points[i]);
  3296. }
  3297. return this;
  3298. }
  3299. setFromCenterAndSize(center, size) {
  3300. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3301. this.min.copy(center).sub(halfSize);
  3302. this.max.copy(center).add(halfSize);
  3303. return this;
  3304. }
  3305. setFromObject(object, precise = false) {
  3306. this.makeEmpty();
  3307. return this.expandByObject(object, precise);
  3308. }
  3309. clone() {
  3310. return new this.constructor().copy(this);
  3311. }
  3312. copy(box) {
  3313. this.min.copy(box.min);
  3314. this.max.copy(box.max);
  3315. return this;
  3316. }
  3317. makeEmpty() {
  3318. this.min.x = this.min.y = this.min.z = +Infinity;
  3319. this.max.x = this.max.y = this.max.z = -Infinity;
  3320. return this;
  3321. }
  3322. isEmpty() {
  3323. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3324. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3325. }
  3326. getCenter(target) {
  3327. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3328. }
  3329. getSize(target) {
  3330. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3331. }
  3332. expandByPoint(point) {
  3333. this.min.min(point);
  3334. this.max.max(point);
  3335. return this;
  3336. }
  3337. expandByVector(vector) {
  3338. this.min.sub(vector);
  3339. this.max.add(vector);
  3340. return this;
  3341. }
  3342. expandByScalar(scalar) {
  3343. this.min.addScalar(-scalar);
  3344. this.max.addScalar(scalar);
  3345. return this;
  3346. }
  3347. expandByObject(object, precise = false) {
  3348. // Computes the world-axis-aligned bounding box of an object (including its children),
  3349. // accounting for both the object's, and children's, world transforms
  3350. object.updateWorldMatrix(false, false);
  3351. const geometry = object.geometry;
  3352. if (geometry !== undefined) {
  3353. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3354. const position = geometry.attributes.position;
  3355. for (let i = 0, l = position.count; i < l; i++) {
  3356. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3357. this.expandByPoint(_vector$b);
  3358. }
  3359. } else {
  3360. if (geometry.boundingBox === null) {
  3361. geometry.computeBoundingBox();
  3362. }
  3363. _box$3.copy(geometry.boundingBox);
  3364. _box$3.applyMatrix4(object.matrixWorld);
  3365. this.union(_box$3);
  3366. }
  3367. }
  3368. const children = object.children;
  3369. for (let i = 0, l = children.length; i < l; i++) {
  3370. this.expandByObject(children[i], precise);
  3371. }
  3372. return this;
  3373. }
  3374. containsPoint(point) {
  3375. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  3376. }
  3377. containsBox(box) {
  3378. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  3379. }
  3380. getParameter(point, target) {
  3381. // This can potentially have a divide by zero if the box
  3382. // has a size dimension of 0.
  3383. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  3384. }
  3385. intersectsBox(box) {
  3386. // using 6 splitting planes to rule out intersections.
  3387. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3388. }
  3389. intersectsSphere(sphere) {
  3390. // Find the point on the AABB closest to the sphere center.
  3391. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  3392. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3393. }
  3394. intersectsPlane(plane) {
  3395. // We compute the minimum and maximum dot product values. If those values
  3396. // are on the same side (back or front) of the plane, then there is no intersection.
  3397. let min, max;
  3398. if (plane.normal.x > 0) {
  3399. min = plane.normal.x * this.min.x;
  3400. max = plane.normal.x * this.max.x;
  3401. } else {
  3402. min = plane.normal.x * this.max.x;
  3403. max = plane.normal.x * this.min.x;
  3404. }
  3405. if (plane.normal.y > 0) {
  3406. min += plane.normal.y * this.min.y;
  3407. max += plane.normal.y * this.max.y;
  3408. } else {
  3409. min += plane.normal.y * this.max.y;
  3410. max += plane.normal.y * this.min.y;
  3411. }
  3412. if (plane.normal.z > 0) {
  3413. min += plane.normal.z * this.min.z;
  3414. max += plane.normal.z * this.max.z;
  3415. } else {
  3416. min += plane.normal.z * this.max.z;
  3417. max += plane.normal.z * this.min.z;
  3418. }
  3419. return min <= -plane.constant && max >= -plane.constant;
  3420. }
  3421. intersectsTriangle(triangle) {
  3422. if (this.isEmpty()) {
  3423. return false;
  3424. } // compute box center and extents
  3425. this.getCenter(_center);
  3426. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3427. _v0$2.subVectors(triangle.a, _center);
  3428. _v1$7.subVectors(triangle.b, _center);
  3429. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3430. _f0.subVectors(_v1$7, _v0$2);
  3431. _f1.subVectors(_v2$3, _v1$7);
  3432. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3433. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  3434. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3435. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  3436. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3437. return false;
  3438. } // test 3 face normals from the aabb
  3439. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3440. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3441. return false;
  3442. } // finally testing the face normal of the triangle
  3443. // use already existing triangle edge vectors here
  3444. _triangleNormal.crossVectors(_f0, _f1);
  3445. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3446. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  3447. }
  3448. clampPoint(point, target) {
  3449. return target.copy(point).clamp(this.min, this.max);
  3450. }
  3451. distanceToPoint(point) {
  3452. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3453. return clampedPoint.sub(point).length();
  3454. }
  3455. getBoundingSphere(target) {
  3456. this.getCenter(target.center);
  3457. target.radius = this.getSize(_vector$b).length() * 0.5;
  3458. return target;
  3459. }
  3460. intersect(box) {
  3461. this.min.max(box.min);
  3462. this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  3463. if (this.isEmpty()) this.makeEmpty();
  3464. return this;
  3465. }
  3466. union(box) {
  3467. this.min.min(box.min);
  3468. this.max.max(box.max);
  3469. return this;
  3470. }
  3471. applyMatrix4(matrix) {
  3472. // transform of empty box is an empty box.
  3473. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3474. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3475. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3476. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3477. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3478. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3479. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3480. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3481. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3482. this.setFromPoints(_points);
  3483. return this;
  3484. }
  3485. translate(offset) {
  3486. this.min.add(offset);
  3487. this.max.add(offset);
  3488. return this;
  3489. }
  3490. equals(box) {
  3491. return box.min.equals(this.min) && box.max.equals(this.max);
  3492. }
  3493. }
  3494. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  3495. const _vector$b = /*@__PURE__*/new Vector3();
  3496. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  3497. const _v0$2 = /*@__PURE__*/new Vector3();
  3498. const _v1$7 = /*@__PURE__*/new Vector3();
  3499. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  3500. const _f0 = /*@__PURE__*/new Vector3();
  3501. const _f1 = /*@__PURE__*/new Vector3();
  3502. const _f2 = /*@__PURE__*/new Vector3();
  3503. const _center = /*@__PURE__*/new Vector3();
  3504. const _extents = /*@__PURE__*/new Vector3();
  3505. const _triangleNormal = /*@__PURE__*/new Vector3();
  3506. const _testAxis = /*@__PURE__*/new Vector3();
  3507. function satForAxes(axes, v0, v1, v2, extents) {
  3508. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3509. _testAxis.fromArray(axes, i); // project the aabb onto the separating axis
  3510. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the separating axis
  3511. const p0 = v0.dot(_testAxis);
  3512. const p1 = v1.dot(_testAxis);
  3513. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3514. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3515. // points of the projected triangle are outside the projected half-length of the aabb
  3516. // the axis is separating and we can exit
  3517. return false;
  3518. }
  3519. }
  3520. return true;
  3521. }
  3522. const _box$2 = /*@__PURE__*/new Box3();
  3523. const _v1$6 = /*@__PURE__*/new Vector3();
  3524. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  3525. const _toPoint = /*@__PURE__*/new Vector3();
  3526. class Sphere {
  3527. constructor(center = new Vector3(), radius = -1) {
  3528. this.center = center;
  3529. this.radius = radius;
  3530. }
  3531. set(center, radius) {
  3532. this.center.copy(center);
  3533. this.radius = radius;
  3534. return this;
  3535. }
  3536. setFromPoints(points, optionalCenter) {
  3537. const center = this.center;
  3538. if (optionalCenter !== undefined) {
  3539. center.copy(optionalCenter);
  3540. } else {
  3541. _box$2.setFromPoints(points).getCenter(center);
  3542. }
  3543. let maxRadiusSq = 0;
  3544. for (let i = 0, il = points.length; i < il; i++) {
  3545. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3546. }
  3547. this.radius = Math.sqrt(maxRadiusSq);
  3548. return this;
  3549. }
  3550. copy(sphere) {
  3551. this.center.copy(sphere.center);
  3552. this.radius = sphere.radius;
  3553. return this;
  3554. }
  3555. isEmpty() {
  3556. return this.radius < 0;
  3557. }
  3558. makeEmpty() {
  3559. this.center.set(0, 0, 0);
  3560. this.radius = -1;
  3561. return this;
  3562. }
  3563. containsPoint(point) {
  3564. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3565. }
  3566. distanceToPoint(point) {
  3567. return point.distanceTo(this.center) - this.radius;
  3568. }
  3569. intersectsSphere(sphere) {
  3570. const radiusSum = this.radius + sphere.radius;
  3571. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3572. }
  3573. intersectsBox(box) {
  3574. return box.intersectsSphere(this);
  3575. }
  3576. intersectsPlane(plane) {
  3577. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3578. }
  3579. clampPoint(point, target) {
  3580. const deltaLengthSq = this.center.distanceToSquared(point);
  3581. target.copy(point);
  3582. if (deltaLengthSq > this.radius * this.radius) {
  3583. target.sub(this.center).normalize();
  3584. target.multiplyScalar(this.radius).add(this.center);
  3585. }
  3586. return target;
  3587. }
  3588. getBoundingBox(target) {
  3589. if (this.isEmpty()) {
  3590. // Empty sphere produces empty bounding box
  3591. target.makeEmpty();
  3592. return target;
  3593. }
  3594. target.set(this.center, this.center);
  3595. target.expandByScalar(this.radius);
  3596. return target;
  3597. }
  3598. applyMatrix4(matrix) {
  3599. this.center.applyMatrix4(matrix);
  3600. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3601. return this;
  3602. }
  3603. translate(offset) {
  3604. this.center.add(offset);
  3605. return this;
  3606. }
  3607. expandByPoint(point) {
  3608. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3609. _toPoint.subVectors(point, this.center);
  3610. const lengthSq = _toPoint.lengthSq();
  3611. if (lengthSq > this.radius * this.radius) {
  3612. const length = Math.sqrt(lengthSq);
  3613. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3614. // and the other half to position. This gives a tighter enclosure, instead of if
  3615. // the whole missing distance were just added to radius.
  3616. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  3617. this.radius += missingRadiusHalf;
  3618. }
  3619. return this;
  3620. }
  3621. union(sphere) {
  3622. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3623. // To enclose another sphere into this sphere, we only need to enclose two points:
  3624. // 1) Enclose the farthest point on the other sphere into this sphere.
  3625. // 2) Enclose the opposite point of the farthest point into this sphere.
  3626. if (this.center.equals(sphere.center) === true) {
  3627. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3628. } else {
  3629. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3630. }
  3631. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3632. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3633. return this;
  3634. }
  3635. equals(sphere) {
  3636. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3637. }
  3638. clone() {
  3639. return new this.constructor().copy(this);
  3640. }
  3641. }
  3642. const _vector$a = /*@__PURE__*/new Vector3();
  3643. const _segCenter = /*@__PURE__*/new Vector3();
  3644. const _segDir = /*@__PURE__*/new Vector3();
  3645. const _diff = /*@__PURE__*/new Vector3();
  3646. const _edge1 = /*@__PURE__*/new Vector3();
  3647. const _edge2 = /*@__PURE__*/new Vector3();
  3648. const _normal$1 = /*@__PURE__*/new Vector3();
  3649. class Ray {
  3650. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3651. this.origin = origin;
  3652. this.direction = direction;
  3653. }
  3654. set(origin, direction) {
  3655. this.origin.copy(origin);
  3656. this.direction.copy(direction);
  3657. return this;
  3658. }
  3659. copy(ray) {
  3660. this.origin.copy(ray.origin);
  3661. this.direction.copy(ray.direction);
  3662. return this;
  3663. }
  3664. at(t, target) {
  3665. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3666. }
  3667. lookAt(v) {
  3668. this.direction.copy(v).sub(this.origin).normalize();
  3669. return this;
  3670. }
  3671. recast(t) {
  3672. this.origin.copy(this.at(t, _vector$a));
  3673. return this;
  3674. }
  3675. closestPointToPoint(point, target) {
  3676. target.subVectors(point, this.origin);
  3677. const directionDistance = target.dot(this.direction);
  3678. if (directionDistance < 0) {
  3679. return target.copy(this.origin);
  3680. }
  3681. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3682. }
  3683. distanceToPoint(point) {
  3684. return Math.sqrt(this.distanceSqToPoint(point));
  3685. }
  3686. distanceSqToPoint(point) {
  3687. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3688. if (directionDistance < 0) {
  3689. return this.origin.distanceToSquared(point);
  3690. }
  3691. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3692. return _vector$a.distanceToSquared(point);
  3693. }
  3694. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3695. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3696. // It returns the min distance between the ray and the segment
  3697. // defined by v0 and v1
  3698. // It can also set two optional targets :
  3699. // - The closest point on the ray
  3700. // - The closest point on the segment
  3701. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3702. _segDir.copy(v1).sub(v0).normalize();
  3703. _diff.copy(this.origin).sub(_segCenter);
  3704. const segExtent = v0.distanceTo(v1) * 0.5;
  3705. const a01 = -this.direction.dot(_segDir);
  3706. const b0 = _diff.dot(this.direction);
  3707. const b1 = -_diff.dot(_segDir);
  3708. const c = _diff.lengthSq();
  3709. const det = Math.abs(1 - a01 * a01);
  3710. let s0, s1, sqrDist, extDet;
  3711. if (det > 0) {
  3712. // The ray and segment are not parallel.
  3713. s0 = a01 * b1 - b0;
  3714. s1 = a01 * b0 - b1;
  3715. extDet = segExtent * det;
  3716. if (s0 >= 0) {
  3717. if (s1 >= -extDet) {
  3718. if (s1 <= extDet) {
  3719. // region 0
  3720. // Minimum at interior points of ray and segment.
  3721. const invDet = 1 / det;
  3722. s0 *= invDet;
  3723. s1 *= invDet;
  3724. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3725. } else {
  3726. // region 1
  3727. s1 = segExtent;
  3728. s0 = Math.max(0, -(a01 * s1 + b0));
  3729. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3730. }
  3731. } else {
  3732. // region 5
  3733. s1 = -segExtent;
  3734. s0 = Math.max(0, -(a01 * s1 + b0));
  3735. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3736. }
  3737. } else {
  3738. if (s1 <= -extDet) {
  3739. // region 4
  3740. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3741. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3742. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3743. } else if (s1 <= extDet) {
  3744. // region 3
  3745. s0 = 0;
  3746. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3747. sqrDist = s1 * (s1 + 2 * b1) + c;
  3748. } else {
  3749. // region 2
  3750. s0 = Math.max(0, -(a01 * segExtent + b0));
  3751. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3752. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3753. }
  3754. }
  3755. } else {
  3756. // Ray and segment are parallel.
  3757. s1 = a01 > 0 ? -segExtent : segExtent;
  3758. s0 = Math.max(0, -(a01 * s1 + b0));
  3759. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3760. }
  3761. if (optionalPointOnRay) {
  3762. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3763. }
  3764. if (optionalPointOnSegment) {
  3765. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3766. }
  3767. return sqrDist;
  3768. }
  3769. intersectSphere(sphere, target) {
  3770. _vector$a.subVectors(sphere.center, this.origin);
  3771. const tca = _vector$a.dot(this.direction);
  3772. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3773. const radius2 = sphere.radius * sphere.radius;
  3774. if (d2 > radius2) return null;
  3775. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3776. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3777. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3778. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3779. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3780. // in order to always return an intersect point that is in front of the ray.
  3781. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3782. return this.at(t0, target);
  3783. }
  3784. intersectsSphere(sphere) {
  3785. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3786. }
  3787. distanceToPlane(plane) {
  3788. const denominator = plane.normal.dot(this.direction);
  3789. if (denominator === 0) {
  3790. // line is coplanar, return origin
  3791. if (plane.distanceToPoint(this.origin) === 0) {
  3792. return 0;
  3793. } // Null is preferable to undefined since undefined means.... it is undefined
  3794. return null;
  3795. }
  3796. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3797. return t >= 0 ? t : null;
  3798. }
  3799. intersectPlane(plane, target) {
  3800. const t = this.distanceToPlane(plane);
  3801. if (t === null) {
  3802. return null;
  3803. }
  3804. return this.at(t, target);
  3805. }
  3806. intersectsPlane(plane) {
  3807. // check if the ray lies on the plane first
  3808. const distToPoint = plane.distanceToPoint(this.origin);
  3809. if (distToPoint === 0) {
  3810. return true;
  3811. }
  3812. const denominator = plane.normal.dot(this.direction);
  3813. if (denominator * distToPoint < 0) {
  3814. return true;
  3815. } // ray origin is behind the plane (and is pointing behind it)
  3816. return false;
  3817. }
  3818. intersectBox(box, target) {
  3819. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3820. const invdirx = 1 / this.direction.x,
  3821. invdiry = 1 / this.direction.y,
  3822. invdirz = 1 / this.direction.z;
  3823. const origin = this.origin;
  3824. if (invdirx >= 0) {
  3825. tmin = (box.min.x - origin.x) * invdirx;
  3826. tmax = (box.max.x - origin.x) * invdirx;
  3827. } else {
  3828. tmin = (box.max.x - origin.x) * invdirx;
  3829. tmax = (box.min.x - origin.x) * invdirx;
  3830. }
  3831. if (invdiry >= 0) {
  3832. tymin = (box.min.y - origin.y) * invdiry;
  3833. tymax = (box.max.y - origin.y) * invdiry;
  3834. } else {
  3835. tymin = (box.max.y - origin.y) * invdiry;
  3836. tymax = (box.min.y - origin.y) * invdiry;
  3837. }
  3838. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3839. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3840. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3841. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3842. if (invdirz >= 0) {
  3843. tzmin = (box.min.z - origin.z) * invdirz;
  3844. tzmax = (box.max.z - origin.z) * invdirz;
  3845. } else {
  3846. tzmin = (box.max.z - origin.z) * invdirz;
  3847. tzmax = (box.min.z - origin.z) * invdirz;
  3848. }
  3849. if (tmin > tzmax || tzmin > tmax) return null;
  3850. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3851. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3852. if (tmax < 0) return null;
  3853. return this.at(tmin >= 0 ? tmin : tmax, target);
  3854. }
  3855. intersectsBox(box) {
  3856. return this.intersectBox(box, _vector$a) !== null;
  3857. }
  3858. intersectTriangle(a, b, c, backfaceCulling, target) {
  3859. // Compute the offset origin, edges, and normal.
  3860. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3861. _edge1.subVectors(b, a);
  3862. _edge2.subVectors(c, a);
  3863. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3864. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3865. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3866. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3867. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3868. let DdN = this.direction.dot(_normal$1);
  3869. let sign;
  3870. if (DdN > 0) {
  3871. if (backfaceCulling) return null;
  3872. sign = 1;
  3873. } else if (DdN < 0) {
  3874. sign = -1;
  3875. DdN = -DdN;
  3876. } else {
  3877. return null;
  3878. }
  3879. _diff.subVectors(this.origin, a);
  3880. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3881. if (DdQxE2 < 0) {
  3882. return null;
  3883. }
  3884. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3885. if (DdE1xQ < 0) {
  3886. return null;
  3887. } // b1+b2 > 1, no intersection
  3888. if (DdQxE2 + DdE1xQ > DdN) {
  3889. return null;
  3890. } // Line intersects triangle, check if ray does.
  3891. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3892. if (QdN < 0) {
  3893. return null;
  3894. } // Ray intersects triangle.
  3895. return this.at(QdN / DdN, target);
  3896. }
  3897. applyMatrix4(matrix4) {
  3898. this.origin.applyMatrix4(matrix4);
  3899. this.direction.transformDirection(matrix4);
  3900. return this;
  3901. }
  3902. equals(ray) {
  3903. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3904. }
  3905. clone() {
  3906. return new this.constructor().copy(this);
  3907. }
  3908. }
  3909. class Matrix4 {
  3910. constructor() {
  3911. Matrix4.prototype.isMatrix4 = true;
  3912. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3913. }
  3914. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3915. const te = this.elements;
  3916. te[0] = n11;
  3917. te[4] = n12;
  3918. te[8] = n13;
  3919. te[12] = n14;
  3920. te[1] = n21;
  3921. te[5] = n22;
  3922. te[9] = n23;
  3923. te[13] = n24;
  3924. te[2] = n31;
  3925. te[6] = n32;
  3926. te[10] = n33;
  3927. te[14] = n34;
  3928. te[3] = n41;
  3929. te[7] = n42;
  3930. te[11] = n43;
  3931. te[15] = n44;
  3932. return this;
  3933. }
  3934. identity() {
  3935. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3936. return this;
  3937. }
  3938. clone() {
  3939. return new Matrix4().fromArray(this.elements);
  3940. }
  3941. copy(m) {
  3942. const te = this.elements;
  3943. const me = m.elements;
  3944. te[0] = me[0];
  3945. te[1] = me[1];
  3946. te[2] = me[2];
  3947. te[3] = me[3];
  3948. te[4] = me[4];
  3949. te[5] = me[5];
  3950. te[6] = me[6];
  3951. te[7] = me[7];
  3952. te[8] = me[8];
  3953. te[9] = me[9];
  3954. te[10] = me[10];
  3955. te[11] = me[11];
  3956. te[12] = me[12];
  3957. te[13] = me[13];
  3958. te[14] = me[14];
  3959. te[15] = me[15];
  3960. return this;
  3961. }
  3962. copyPosition(m) {
  3963. const te = this.elements,
  3964. me = m.elements;
  3965. te[12] = me[12];
  3966. te[13] = me[13];
  3967. te[14] = me[14];
  3968. return this;
  3969. }
  3970. setFromMatrix3(m) {
  3971. const me = m.elements;
  3972. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  3973. return this;
  3974. }
  3975. extractBasis(xAxis, yAxis, zAxis) {
  3976. xAxis.setFromMatrixColumn(this, 0);
  3977. yAxis.setFromMatrixColumn(this, 1);
  3978. zAxis.setFromMatrixColumn(this, 2);
  3979. return this;
  3980. }
  3981. makeBasis(xAxis, yAxis, zAxis) {
  3982. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  3983. return this;
  3984. }
  3985. extractRotation(m) {
  3986. // this method does not support reflection matrices
  3987. const te = this.elements;
  3988. const me = m.elements;
  3989. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3990. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3991. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3992. te[0] = me[0] * scaleX;
  3993. te[1] = me[1] * scaleX;
  3994. te[2] = me[2] * scaleX;
  3995. te[3] = 0;
  3996. te[4] = me[4] * scaleY;
  3997. te[5] = me[5] * scaleY;
  3998. te[6] = me[6] * scaleY;
  3999. te[7] = 0;
  4000. te[8] = me[8] * scaleZ;
  4001. te[9] = me[9] * scaleZ;
  4002. te[10] = me[10] * scaleZ;
  4003. te[11] = 0;
  4004. te[12] = 0;
  4005. te[13] = 0;
  4006. te[14] = 0;
  4007. te[15] = 1;
  4008. return this;
  4009. }
  4010. makeRotationFromEuler(euler) {
  4011. const te = this.elements;
  4012. const x = euler.x,
  4013. y = euler.y,
  4014. z = euler.z;
  4015. const a = Math.cos(x),
  4016. b = Math.sin(x);
  4017. const c = Math.cos(y),
  4018. d = Math.sin(y);
  4019. const e = Math.cos(z),
  4020. f = Math.sin(z);
  4021. if (euler.order === 'XYZ') {
  4022. const ae = a * e,
  4023. af = a * f,
  4024. be = b * e,
  4025. bf = b * f;
  4026. te[0] = c * e;
  4027. te[4] = -c * f;
  4028. te[8] = d;
  4029. te[1] = af + be * d;
  4030. te[5] = ae - bf * d;
  4031. te[9] = -b * c;
  4032. te[2] = bf - ae * d;
  4033. te[6] = be + af * d;
  4034. te[10] = a * c;
  4035. } else if (euler.order === 'YXZ') {
  4036. const ce = c * e,
  4037. cf = c * f,
  4038. de = d * e,
  4039. df = d * f;
  4040. te[0] = ce + df * b;
  4041. te[4] = de * b - cf;
  4042. te[8] = a * d;
  4043. te[1] = a * f;
  4044. te[5] = a * e;
  4045. te[9] = -b;
  4046. te[2] = cf * b - de;
  4047. te[6] = df + ce * b;
  4048. te[10] = a * c;
  4049. } else if (euler.order === 'ZXY') {
  4050. const ce = c * e,
  4051. cf = c * f,
  4052. de = d * e,
  4053. df = d * f;
  4054. te[0] = ce - df * b;
  4055. te[4] = -a * f;
  4056. te[8] = de + cf * b;
  4057. te[1] = cf + de * b;
  4058. te[5] = a * e;
  4059. te[9] = df - ce * b;
  4060. te[2] = -a * d;
  4061. te[6] = b;
  4062. te[10] = a * c;
  4063. } else if (euler.order === 'ZYX') {
  4064. const ae = a * e,
  4065. af = a * f,
  4066. be = b * e,
  4067. bf = b * f;
  4068. te[0] = c * e;
  4069. te[4] = be * d - af;
  4070. te[8] = ae * d + bf;
  4071. te[1] = c * f;
  4072. te[5] = bf * d + ae;
  4073. te[9] = af * d - be;
  4074. te[2] = -d;
  4075. te[6] = b * c;
  4076. te[10] = a * c;
  4077. } else if (euler.order === 'YZX') {
  4078. const ac = a * c,
  4079. ad = a * d,
  4080. bc = b * c,
  4081. bd = b * d;
  4082. te[0] = c * e;
  4083. te[4] = bd - ac * f;
  4084. te[8] = bc * f + ad;
  4085. te[1] = f;
  4086. te[5] = a * e;
  4087. te[9] = -b * e;
  4088. te[2] = -d * e;
  4089. te[6] = ad * f + bc;
  4090. te[10] = ac - bd * f;
  4091. } else if (euler.order === 'XZY') {
  4092. const ac = a * c,
  4093. ad = a * d,
  4094. bc = b * c,
  4095. bd = b * d;
  4096. te[0] = c * e;
  4097. te[4] = -f;
  4098. te[8] = d * e;
  4099. te[1] = ac * f + bd;
  4100. te[5] = a * e;
  4101. te[9] = ad * f - bc;
  4102. te[2] = bc * f - ad;
  4103. te[6] = b * e;
  4104. te[10] = bd * f + ac;
  4105. } // bottom row
  4106. te[3] = 0;
  4107. te[7] = 0;
  4108. te[11] = 0; // last column
  4109. te[12] = 0;
  4110. te[13] = 0;
  4111. te[14] = 0;
  4112. te[15] = 1;
  4113. return this;
  4114. }
  4115. makeRotationFromQuaternion(q) {
  4116. return this.compose(_zero, q, _one);
  4117. }
  4118. lookAt(eye, target, up) {
  4119. const te = this.elements;
  4120. _z.subVectors(eye, target);
  4121. if (_z.lengthSq() === 0) {
  4122. // eye and target are in the same position
  4123. _z.z = 1;
  4124. }
  4125. _z.normalize();
  4126. _x.crossVectors(up, _z);
  4127. if (_x.lengthSq() === 0) {
  4128. // up and z are parallel
  4129. if (Math.abs(up.z) === 1) {
  4130. _z.x += 0.0001;
  4131. } else {
  4132. _z.z += 0.0001;
  4133. }
  4134. _z.normalize();
  4135. _x.crossVectors(up, _z);
  4136. }
  4137. _x.normalize();
  4138. _y.crossVectors(_z, _x);
  4139. te[0] = _x.x;
  4140. te[4] = _y.x;
  4141. te[8] = _z.x;
  4142. te[1] = _x.y;
  4143. te[5] = _y.y;
  4144. te[9] = _z.y;
  4145. te[2] = _x.z;
  4146. te[6] = _y.z;
  4147. te[10] = _z.z;
  4148. return this;
  4149. }
  4150. multiply(m) {
  4151. return this.multiplyMatrices(this, m);
  4152. }
  4153. premultiply(m) {
  4154. return this.multiplyMatrices(m, this);
  4155. }
  4156. multiplyMatrices(a, b) {
  4157. const ae = a.elements;
  4158. const be = b.elements;
  4159. const te = this.elements;
  4160. const a11 = ae[0],
  4161. a12 = ae[4],
  4162. a13 = ae[8],
  4163. a14 = ae[12];
  4164. const a21 = ae[1],
  4165. a22 = ae[5],
  4166. a23 = ae[9],
  4167. a24 = ae[13];
  4168. const a31 = ae[2],
  4169. a32 = ae[6],
  4170. a33 = ae[10],
  4171. a34 = ae[14];
  4172. const a41 = ae[3],
  4173. a42 = ae[7],
  4174. a43 = ae[11],
  4175. a44 = ae[15];
  4176. const b11 = be[0],
  4177. b12 = be[4],
  4178. b13 = be[8],
  4179. b14 = be[12];
  4180. const b21 = be[1],
  4181. b22 = be[5],
  4182. b23 = be[9],
  4183. b24 = be[13];
  4184. const b31 = be[2],
  4185. b32 = be[6],
  4186. b33 = be[10],
  4187. b34 = be[14];
  4188. const b41 = be[3],
  4189. b42 = be[7],
  4190. b43 = be[11],
  4191. b44 = be[15];
  4192. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4193. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4194. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4195. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4196. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4197. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4198. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4199. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4200. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4201. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4202. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4203. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4204. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4205. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4206. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4207. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4208. return this;
  4209. }
  4210. multiplyScalar(s) {
  4211. const te = this.elements;
  4212. te[0] *= s;
  4213. te[4] *= s;
  4214. te[8] *= s;
  4215. te[12] *= s;
  4216. te[1] *= s;
  4217. te[5] *= s;
  4218. te[9] *= s;
  4219. te[13] *= s;
  4220. te[2] *= s;
  4221. te[6] *= s;
  4222. te[10] *= s;
  4223. te[14] *= s;
  4224. te[3] *= s;
  4225. te[7] *= s;
  4226. te[11] *= s;
  4227. te[15] *= s;
  4228. return this;
  4229. }
  4230. determinant() {
  4231. const te = this.elements;
  4232. const n11 = te[0],
  4233. n12 = te[4],
  4234. n13 = te[8],
  4235. n14 = te[12];
  4236. const n21 = te[1],
  4237. n22 = te[5],
  4238. n23 = te[9],
  4239. n24 = te[13];
  4240. const n31 = te[2],
  4241. n32 = te[6],
  4242. n33 = te[10],
  4243. n34 = te[14];
  4244. const n41 = te[3],
  4245. n42 = te[7],
  4246. n43 = te[11],
  4247. n44 = te[15]; //TODO: make this more efficient
  4248. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4249. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  4250. }
  4251. transpose() {
  4252. const te = this.elements;
  4253. let tmp;
  4254. tmp = te[1];
  4255. te[1] = te[4];
  4256. te[4] = tmp;
  4257. tmp = te[2];
  4258. te[2] = te[8];
  4259. te[8] = tmp;
  4260. tmp = te[6];
  4261. te[6] = te[9];
  4262. te[9] = tmp;
  4263. tmp = te[3];
  4264. te[3] = te[12];
  4265. te[12] = tmp;
  4266. tmp = te[7];
  4267. te[7] = te[13];
  4268. te[13] = tmp;
  4269. tmp = te[11];
  4270. te[11] = te[14];
  4271. te[14] = tmp;
  4272. return this;
  4273. }
  4274. setPosition(x, y, z) {
  4275. const te = this.elements;
  4276. if (x.isVector3) {
  4277. te[12] = x.x;
  4278. te[13] = x.y;
  4279. te[14] = x.z;
  4280. } else {
  4281. te[12] = x;
  4282. te[13] = y;
  4283. te[14] = z;
  4284. }
  4285. return this;
  4286. }
  4287. invert() {
  4288. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4289. const te = this.elements,
  4290. n11 = te[0],
  4291. n21 = te[1],
  4292. n31 = te[2],
  4293. n41 = te[3],
  4294. n12 = te[4],
  4295. n22 = te[5],
  4296. n32 = te[6],
  4297. n42 = te[7],
  4298. n13 = te[8],
  4299. n23 = te[9],
  4300. n33 = te[10],
  4301. n43 = te[11],
  4302. n14 = te[12],
  4303. n24 = te[13],
  4304. n34 = te[14],
  4305. n44 = te[15],
  4306. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4307. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4308. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4309. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4310. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4311. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4312. const detInv = 1 / det;
  4313. te[0] = t11 * detInv;
  4314. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4315. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4316. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4317. te[4] = t12 * detInv;
  4318. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4319. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4320. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4321. te[8] = t13 * detInv;
  4322. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4323. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4324. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4325. te[12] = t14 * detInv;
  4326. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4327. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4328. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4329. return this;
  4330. }
  4331. scale(v) {
  4332. const te = this.elements;
  4333. const x = v.x,
  4334. y = v.y,
  4335. z = v.z;
  4336. te[0] *= x;
  4337. te[4] *= y;
  4338. te[8] *= z;
  4339. te[1] *= x;
  4340. te[5] *= y;
  4341. te[9] *= z;
  4342. te[2] *= x;
  4343. te[6] *= y;
  4344. te[10] *= z;
  4345. te[3] *= x;
  4346. te[7] *= y;
  4347. te[11] *= z;
  4348. return this;
  4349. }
  4350. getMaxScaleOnAxis() {
  4351. const te = this.elements;
  4352. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4353. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4354. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4355. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4356. }
  4357. makeTranslation(x, y, z) {
  4358. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4359. return this;
  4360. }
  4361. makeRotationX(theta) {
  4362. const c = Math.cos(theta),
  4363. s = Math.sin(theta);
  4364. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4365. return this;
  4366. }
  4367. makeRotationY(theta) {
  4368. const c = Math.cos(theta),
  4369. s = Math.sin(theta);
  4370. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4371. return this;
  4372. }
  4373. makeRotationZ(theta) {
  4374. const c = Math.cos(theta),
  4375. s = Math.sin(theta);
  4376. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4377. return this;
  4378. }
  4379. makeRotationAxis(axis, angle) {
  4380. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4381. const c = Math.cos(angle);
  4382. const s = Math.sin(angle);
  4383. const t = 1 - c;
  4384. const x = axis.x,
  4385. y = axis.y,
  4386. z = axis.z;
  4387. const tx = t * x,
  4388. ty = t * y;
  4389. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  4390. return this;
  4391. }
  4392. makeScale(x, y, z) {
  4393. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4394. return this;
  4395. }
  4396. makeShear(xy, xz, yx, yz, zx, zy) {
  4397. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4398. return this;
  4399. }
  4400. compose(position, quaternion, scale) {
  4401. const te = this.elements;
  4402. const x = quaternion._x,
  4403. y = quaternion._y,
  4404. z = quaternion._z,
  4405. w = quaternion._w;
  4406. const x2 = x + x,
  4407. y2 = y + y,
  4408. z2 = z + z;
  4409. const xx = x * x2,
  4410. xy = x * y2,
  4411. xz = x * z2;
  4412. const yy = y * y2,
  4413. yz = y * z2,
  4414. zz = z * z2;
  4415. const wx = w * x2,
  4416. wy = w * y2,
  4417. wz = w * z2;
  4418. const sx = scale.x,
  4419. sy = scale.y,
  4420. sz = scale.z;
  4421. te[0] = (1 - (yy + zz)) * sx;
  4422. te[1] = (xy + wz) * sx;
  4423. te[2] = (xz - wy) * sx;
  4424. te[3] = 0;
  4425. te[4] = (xy - wz) * sy;
  4426. te[5] = (1 - (xx + zz)) * sy;
  4427. te[6] = (yz + wx) * sy;
  4428. te[7] = 0;
  4429. te[8] = (xz + wy) * sz;
  4430. te[9] = (yz - wx) * sz;
  4431. te[10] = (1 - (xx + yy)) * sz;
  4432. te[11] = 0;
  4433. te[12] = position.x;
  4434. te[13] = position.y;
  4435. te[14] = position.z;
  4436. te[15] = 1;
  4437. return this;
  4438. }
  4439. decompose(position, quaternion, scale) {
  4440. const te = this.elements;
  4441. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4442. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4443. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4444. const det = this.determinant();
  4445. if (det < 0) sx = -sx;
  4446. position.x = te[12];
  4447. position.y = te[13];
  4448. position.z = te[14]; // scale the rotation part
  4449. _m1$2.copy(this);
  4450. const invSX = 1 / sx;
  4451. const invSY = 1 / sy;
  4452. const invSZ = 1 / sz;
  4453. _m1$2.elements[0] *= invSX;
  4454. _m1$2.elements[1] *= invSX;
  4455. _m1$2.elements[2] *= invSX;
  4456. _m1$2.elements[4] *= invSY;
  4457. _m1$2.elements[5] *= invSY;
  4458. _m1$2.elements[6] *= invSY;
  4459. _m1$2.elements[8] *= invSZ;
  4460. _m1$2.elements[9] *= invSZ;
  4461. _m1$2.elements[10] *= invSZ;
  4462. quaternion.setFromRotationMatrix(_m1$2);
  4463. scale.x = sx;
  4464. scale.y = sy;
  4465. scale.z = sz;
  4466. return this;
  4467. }
  4468. makePerspective(left, right, top, bottom, near, far) {
  4469. const te = this.elements;
  4470. const x = 2 * near / (right - left);
  4471. const y = 2 * near / (top - bottom);
  4472. const a = (right + left) / (right - left);
  4473. const b = (top + bottom) / (top - bottom);
  4474. const c = -(far + near) / (far - near);
  4475. const d = -2 * far * near / (far - near);
  4476. te[0] = x;
  4477. te[4] = 0;
  4478. te[8] = a;
  4479. te[12] = 0;
  4480. te[1] = 0;
  4481. te[5] = y;
  4482. te[9] = b;
  4483. te[13] = 0;
  4484. te[2] = 0;
  4485. te[6] = 0;
  4486. te[10] = c;
  4487. te[14] = d;
  4488. te[3] = 0;
  4489. te[7] = 0;
  4490. te[11] = -1;
  4491. te[15] = 0;
  4492. return this;
  4493. }
  4494. makeOrthographic(left, right, top, bottom, near, far) {
  4495. const te = this.elements;
  4496. const w = 1.0 / (right - left);
  4497. const h = 1.0 / (top - bottom);
  4498. const p = 1.0 / (far - near);
  4499. const x = (right + left) * w;
  4500. const y = (top + bottom) * h;
  4501. const z = (far + near) * p;
  4502. te[0] = 2 * w;
  4503. te[4] = 0;
  4504. te[8] = 0;
  4505. te[12] = -x;
  4506. te[1] = 0;
  4507. te[5] = 2 * h;
  4508. te[9] = 0;
  4509. te[13] = -y;
  4510. te[2] = 0;
  4511. te[6] = 0;
  4512. te[10] = -2 * p;
  4513. te[14] = -z;
  4514. te[3] = 0;
  4515. te[7] = 0;
  4516. te[11] = 0;
  4517. te[15] = 1;
  4518. return this;
  4519. }
  4520. equals(matrix) {
  4521. const te = this.elements;
  4522. const me = matrix.elements;
  4523. for (let i = 0; i < 16; i++) {
  4524. if (te[i] !== me[i]) return false;
  4525. }
  4526. return true;
  4527. }
  4528. fromArray(array, offset = 0) {
  4529. for (let i = 0; i < 16; i++) {
  4530. this.elements[i] = array[i + offset];
  4531. }
  4532. return this;
  4533. }
  4534. toArray(array = [], offset = 0) {
  4535. const te = this.elements;
  4536. array[offset] = te[0];
  4537. array[offset + 1] = te[1];
  4538. array[offset + 2] = te[2];
  4539. array[offset + 3] = te[3];
  4540. array[offset + 4] = te[4];
  4541. array[offset + 5] = te[5];
  4542. array[offset + 6] = te[6];
  4543. array[offset + 7] = te[7];
  4544. array[offset + 8] = te[8];
  4545. array[offset + 9] = te[9];
  4546. array[offset + 10] = te[10];
  4547. array[offset + 11] = te[11];
  4548. array[offset + 12] = te[12];
  4549. array[offset + 13] = te[13];
  4550. array[offset + 14] = te[14];
  4551. array[offset + 15] = te[15];
  4552. return array;
  4553. }
  4554. }
  4555. const _v1$5 = /*@__PURE__*/new Vector3();
  4556. const _m1$2 = /*@__PURE__*/new Matrix4();
  4557. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4558. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4559. const _x = /*@__PURE__*/new Vector3();
  4560. const _y = /*@__PURE__*/new Vector3();
  4561. const _z = /*@__PURE__*/new Vector3();
  4562. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4563. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4564. class Euler {
  4565. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4566. this.isEuler = true;
  4567. this._x = x;
  4568. this._y = y;
  4569. this._z = z;
  4570. this._order = order;
  4571. }
  4572. get x() {
  4573. return this._x;
  4574. }
  4575. set x(value) {
  4576. this._x = value;
  4577. this._onChangeCallback();
  4578. }
  4579. get y() {
  4580. return this._y;
  4581. }
  4582. set y(value) {
  4583. this._y = value;
  4584. this._onChangeCallback();
  4585. }
  4586. get z() {
  4587. return this._z;
  4588. }
  4589. set z(value) {
  4590. this._z = value;
  4591. this._onChangeCallback();
  4592. }
  4593. get order() {
  4594. return this._order;
  4595. }
  4596. set order(value) {
  4597. this._order = value;
  4598. this._onChangeCallback();
  4599. }
  4600. set(x, y, z, order = this._order) {
  4601. this._x = x;
  4602. this._y = y;
  4603. this._z = z;
  4604. this._order = order;
  4605. this._onChangeCallback();
  4606. return this;
  4607. }
  4608. clone() {
  4609. return new this.constructor(this._x, this._y, this._z, this._order);
  4610. }
  4611. copy(euler) {
  4612. this._x = euler._x;
  4613. this._y = euler._y;
  4614. this._z = euler._z;
  4615. this._order = euler._order;
  4616. this._onChangeCallback();
  4617. return this;
  4618. }
  4619. setFromRotationMatrix(m, order = this._order, update = true) {
  4620. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4621. const te = m.elements;
  4622. const m11 = te[0],
  4623. m12 = te[4],
  4624. m13 = te[8];
  4625. const m21 = te[1],
  4626. m22 = te[5],
  4627. m23 = te[9];
  4628. const m31 = te[2],
  4629. m32 = te[6],
  4630. m33 = te[10];
  4631. switch (order) {
  4632. case 'XYZ':
  4633. this._y = Math.asin(clamp(m13, -1, 1));
  4634. if (Math.abs(m13) < 0.9999999) {
  4635. this._x = Math.atan2(-m23, m33);
  4636. this._z = Math.atan2(-m12, m11);
  4637. } else {
  4638. this._x = Math.atan2(m32, m22);
  4639. this._z = 0;
  4640. }
  4641. break;
  4642. case 'YXZ':
  4643. this._x = Math.asin(-clamp(m23, -1, 1));
  4644. if (Math.abs(m23) < 0.9999999) {
  4645. this._y = Math.atan2(m13, m33);
  4646. this._z = Math.atan2(m21, m22);
  4647. } else {
  4648. this._y = Math.atan2(-m31, m11);
  4649. this._z = 0;
  4650. }
  4651. break;
  4652. case 'ZXY':
  4653. this._x = Math.asin(clamp(m32, -1, 1));
  4654. if (Math.abs(m32) < 0.9999999) {
  4655. this._y = Math.atan2(-m31, m33);
  4656. this._z = Math.atan2(-m12, m22);
  4657. } else {
  4658. this._y = 0;
  4659. this._z = Math.atan2(m21, m11);
  4660. }
  4661. break;
  4662. case 'ZYX':
  4663. this._y = Math.asin(-clamp(m31, -1, 1));
  4664. if (Math.abs(m31) < 0.9999999) {
  4665. this._x = Math.atan2(m32, m33);
  4666. this._z = Math.atan2(m21, m11);
  4667. } else {
  4668. this._x = 0;
  4669. this._z = Math.atan2(-m12, m22);
  4670. }
  4671. break;
  4672. case 'YZX':
  4673. this._z = Math.asin(clamp(m21, -1, 1));
  4674. if (Math.abs(m21) < 0.9999999) {
  4675. this._x = Math.atan2(-m23, m22);
  4676. this._y = Math.atan2(-m31, m11);
  4677. } else {
  4678. this._x = 0;
  4679. this._y = Math.atan2(m13, m33);
  4680. }
  4681. break;
  4682. case 'XZY':
  4683. this._z = Math.asin(-clamp(m12, -1, 1));
  4684. if (Math.abs(m12) < 0.9999999) {
  4685. this._x = Math.atan2(m32, m22);
  4686. this._y = Math.atan2(m13, m11);
  4687. } else {
  4688. this._x = Math.atan2(-m23, m33);
  4689. this._y = 0;
  4690. }
  4691. break;
  4692. default:
  4693. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4694. }
  4695. this._order = order;
  4696. if (update === true) this._onChangeCallback();
  4697. return this;
  4698. }
  4699. setFromQuaternion(q, order, update) {
  4700. _matrix$1.makeRotationFromQuaternion(q);
  4701. return this.setFromRotationMatrix(_matrix$1, order, update);
  4702. }
  4703. setFromVector3(v, order = this._order) {
  4704. return this.set(v.x, v.y, v.z, order);
  4705. }
  4706. reorder(newOrder) {
  4707. // WARNING: this discards revolution information -bhouston
  4708. _quaternion$3.setFromEuler(this);
  4709. return this.setFromQuaternion(_quaternion$3, newOrder);
  4710. }
  4711. equals(euler) {
  4712. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4713. }
  4714. fromArray(array) {
  4715. this._x = array[0];
  4716. this._y = array[1];
  4717. this._z = array[2];
  4718. if (array[3] !== undefined) this._order = array[3];
  4719. this._onChangeCallback();
  4720. return this;
  4721. }
  4722. toArray(array = [], offset = 0) {
  4723. array[offset] = this._x;
  4724. array[offset + 1] = this._y;
  4725. array[offset + 2] = this._z;
  4726. array[offset + 3] = this._order;
  4727. return array;
  4728. }
  4729. _onChange(callback) {
  4730. this._onChangeCallback = callback;
  4731. return this;
  4732. }
  4733. _onChangeCallback() {}
  4734. *[Symbol.iterator]() {
  4735. yield this._x;
  4736. yield this._y;
  4737. yield this._z;
  4738. yield this._order;
  4739. } // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4740. toVector3() {
  4741. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4742. }
  4743. }
  4744. Euler.DefaultOrder = 'XYZ';
  4745. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4746. class Layers {
  4747. constructor() {
  4748. this.mask = 1 | 0;
  4749. }
  4750. set(channel) {
  4751. this.mask = (1 << channel | 0) >>> 0;
  4752. }
  4753. enable(channel) {
  4754. this.mask |= 1 << channel | 0;
  4755. }
  4756. enableAll() {
  4757. this.mask = 0xffffffff | 0;
  4758. }
  4759. toggle(channel) {
  4760. this.mask ^= 1 << channel | 0;
  4761. }
  4762. disable(channel) {
  4763. this.mask &= ~(1 << channel | 0);
  4764. }
  4765. disableAll() {
  4766. this.mask = 0;
  4767. }
  4768. test(layers) {
  4769. return (this.mask & layers.mask) !== 0;
  4770. }
  4771. isEnabled(channel) {
  4772. return (this.mask & (1 << channel | 0)) !== 0;
  4773. }
  4774. }
  4775. let _object3DId = 0;
  4776. const _v1$4 = /*@__PURE__*/new Vector3();
  4777. const _q1 = /*@__PURE__*/new Quaternion();
  4778. const _m1$1 = /*@__PURE__*/new Matrix4();
  4779. const _target = /*@__PURE__*/new Vector3();
  4780. const _position$3 = /*@__PURE__*/new Vector3();
  4781. const _scale$2 = /*@__PURE__*/new Vector3();
  4782. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4783. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4784. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4785. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4786. const _addedEvent = {
  4787. type: 'added'
  4788. };
  4789. const _removedEvent = {
  4790. type: 'removed'
  4791. };
  4792. class Object3D extends EventDispatcher {
  4793. constructor() {
  4794. super();
  4795. this.isObject3D = true;
  4796. Object.defineProperty(this, 'id', {
  4797. value: _object3DId++
  4798. });
  4799. this.uuid = generateUUID();
  4800. this.name = '';
  4801. this.type = 'Object3D';
  4802. this.parent = null;
  4803. this.children = [];
  4804. this.up = Object3D.DefaultUp.clone();
  4805. const position = new Vector3();
  4806. const rotation = new Euler();
  4807. const quaternion = new Quaternion();
  4808. const scale = new Vector3(1, 1, 1);
  4809. function onRotationChange() {
  4810. quaternion.setFromEuler(rotation, false);
  4811. }
  4812. function onQuaternionChange() {
  4813. rotation.setFromQuaternion(quaternion, undefined, false);
  4814. }
  4815. rotation._onChange(onRotationChange);
  4816. quaternion._onChange(onQuaternionChange);
  4817. Object.defineProperties(this, {
  4818. position: {
  4819. configurable: true,
  4820. enumerable: true,
  4821. value: position
  4822. },
  4823. rotation: {
  4824. configurable: true,
  4825. enumerable: true,
  4826. value: rotation
  4827. },
  4828. quaternion: {
  4829. configurable: true,
  4830. enumerable: true,
  4831. value: quaternion
  4832. },
  4833. scale: {
  4834. configurable: true,
  4835. enumerable: true,
  4836. value: scale
  4837. },
  4838. modelViewMatrix: {
  4839. value: new Matrix4()
  4840. },
  4841. normalMatrix: {
  4842. value: new Matrix3()
  4843. }
  4844. });
  4845. this.matrix = new Matrix4();
  4846. this.matrixWorld = new Matrix4();
  4847. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4848. this.matrixWorldNeedsUpdate = false;
  4849. this.matrixWorldAutoUpdate = Object3D.DefaultMatrixWorldAutoUpdate; // checked by the renderer
  4850. this.layers = new Layers();
  4851. this.visible = true;
  4852. this.castShadow = false;
  4853. this.receiveShadow = false;
  4854. this.frustumCulled = true;
  4855. this.renderOrder = 0;
  4856. this.animations = [];
  4857. this.userData = {};
  4858. }
  4859. onBeforeRender() {}
  4860. onAfterRender() {}
  4861. applyMatrix4(matrix) {
  4862. if (this.matrixAutoUpdate) this.updateMatrix();
  4863. this.matrix.premultiply(matrix);
  4864. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4865. }
  4866. applyQuaternion(q) {
  4867. this.quaternion.premultiply(q);
  4868. return this;
  4869. }
  4870. setRotationFromAxisAngle(axis, angle) {
  4871. // assumes axis is normalized
  4872. this.quaternion.setFromAxisAngle(axis, angle);
  4873. }
  4874. setRotationFromEuler(euler) {
  4875. this.quaternion.setFromEuler(euler, true);
  4876. }
  4877. setRotationFromMatrix(m) {
  4878. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4879. this.quaternion.setFromRotationMatrix(m);
  4880. }
  4881. setRotationFromQuaternion(q) {
  4882. // assumes q is normalized
  4883. this.quaternion.copy(q);
  4884. }
  4885. rotateOnAxis(axis, angle) {
  4886. // rotate object on axis in object space
  4887. // axis is assumed to be normalized
  4888. _q1.setFromAxisAngle(axis, angle);
  4889. this.quaternion.multiply(_q1);
  4890. return this;
  4891. }
  4892. rotateOnWorldAxis(axis, angle) {
  4893. // rotate object on axis in world space
  4894. // axis is assumed to be normalized
  4895. // method assumes no rotated parent
  4896. _q1.setFromAxisAngle(axis, angle);
  4897. this.quaternion.premultiply(_q1);
  4898. return this;
  4899. }
  4900. rotateX(angle) {
  4901. return this.rotateOnAxis(_xAxis, angle);
  4902. }
  4903. rotateY(angle) {
  4904. return this.rotateOnAxis(_yAxis, angle);
  4905. }
  4906. rotateZ(angle) {
  4907. return this.rotateOnAxis(_zAxis, angle);
  4908. }
  4909. translateOnAxis(axis, distance) {
  4910. // translate object by distance along axis in object space
  4911. // axis is assumed to be normalized
  4912. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4913. this.position.add(_v1$4.multiplyScalar(distance));
  4914. return this;
  4915. }
  4916. translateX(distance) {
  4917. return this.translateOnAxis(_xAxis, distance);
  4918. }
  4919. translateY(distance) {
  4920. return this.translateOnAxis(_yAxis, distance);
  4921. }
  4922. translateZ(distance) {
  4923. return this.translateOnAxis(_zAxis, distance);
  4924. }
  4925. localToWorld(vector) {
  4926. return vector.applyMatrix4(this.matrixWorld);
  4927. }
  4928. worldToLocal(vector) {
  4929. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4930. }
  4931. lookAt(x, y, z) {
  4932. // This method does not support objects having non-uniformly-scaled parent(s)
  4933. if (x.isVector3) {
  4934. _target.copy(x);
  4935. } else {
  4936. _target.set(x, y, z);
  4937. }
  4938. const parent = this.parent;
  4939. this.updateWorldMatrix(true, false);
  4940. _position$3.setFromMatrixPosition(this.matrixWorld);
  4941. if (this.isCamera || this.isLight) {
  4942. _m1$1.lookAt(_position$3, _target, this.up);
  4943. } else {
  4944. _m1$1.lookAt(_target, _position$3, this.up);
  4945. }
  4946. this.quaternion.setFromRotationMatrix(_m1$1);
  4947. if (parent) {
  4948. _m1$1.extractRotation(parent.matrixWorld);
  4949. _q1.setFromRotationMatrix(_m1$1);
  4950. this.quaternion.premultiply(_q1.invert());
  4951. }
  4952. }
  4953. add(object) {
  4954. if (arguments.length > 1) {
  4955. for (let i = 0; i < arguments.length; i++) {
  4956. this.add(arguments[i]);
  4957. }
  4958. return this;
  4959. }
  4960. if (object === this) {
  4961. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4962. return this;
  4963. }
  4964. if (object && object.isObject3D) {
  4965. if (object.parent !== null) {
  4966. object.parent.remove(object);
  4967. }
  4968. object.parent = this;
  4969. this.children.push(object);
  4970. object.dispatchEvent(_addedEvent);
  4971. } else {
  4972. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4973. }
  4974. return this;
  4975. }
  4976. remove(object) {
  4977. if (arguments.length > 1) {
  4978. for (let i = 0; i < arguments.length; i++) {
  4979. this.remove(arguments[i]);
  4980. }
  4981. return this;
  4982. }
  4983. const index = this.children.indexOf(object);
  4984. if (index !== -1) {
  4985. object.parent = null;
  4986. this.children.splice(index, 1);
  4987. object.dispatchEvent(_removedEvent);
  4988. }
  4989. return this;
  4990. }
  4991. removeFromParent() {
  4992. const parent = this.parent;
  4993. if (parent !== null) {
  4994. parent.remove(this);
  4995. }
  4996. return this;
  4997. }
  4998. clear() {
  4999. for (let i = 0; i < this.children.length; i++) {
  5000. const object = this.children[i];
  5001. object.parent = null;
  5002. object.dispatchEvent(_removedEvent);
  5003. }
  5004. this.children.length = 0;
  5005. return this;
  5006. }
  5007. attach(object) {
  5008. // adds object as a child of this, while maintaining the object's world transform
  5009. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5010. this.updateWorldMatrix(true, false);
  5011. _m1$1.copy(this.matrixWorld).invert();
  5012. if (object.parent !== null) {
  5013. object.parent.updateWorldMatrix(true, false);
  5014. _m1$1.multiply(object.parent.matrixWorld);
  5015. }
  5016. object.applyMatrix4(_m1$1);
  5017. this.add(object);
  5018. object.updateWorldMatrix(false, true);
  5019. return this;
  5020. }
  5021. getObjectById(id) {
  5022. return this.getObjectByProperty('id', id);
  5023. }
  5024. getObjectByName(name) {
  5025. return this.getObjectByProperty('name', name);
  5026. }
  5027. getObjectByProperty(name, value) {
  5028. if (this[name] === value) return this;
  5029. for (let i = 0, l = this.children.length; i < l; i++) {
  5030. const child = this.children[i];
  5031. const object = child.getObjectByProperty(name, value);
  5032. if (object !== undefined) {
  5033. return object;
  5034. }
  5035. }
  5036. return undefined;
  5037. }
  5038. getWorldPosition(target) {
  5039. this.updateWorldMatrix(true, false);
  5040. return target.setFromMatrixPosition(this.matrixWorld);
  5041. }
  5042. getWorldQuaternion(target) {
  5043. this.updateWorldMatrix(true, false);
  5044. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5045. return target;
  5046. }
  5047. getWorldScale(target) {
  5048. this.updateWorldMatrix(true, false);
  5049. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5050. return target;
  5051. }
  5052. getWorldDirection(target) {
  5053. this.updateWorldMatrix(true, false);
  5054. const e = this.matrixWorld.elements;
  5055. return target.set(e[8], e[9], e[10]).normalize();
  5056. }
  5057. raycast() {}
  5058. traverse(callback) {
  5059. callback(this);
  5060. const children = this.children;
  5061. for (let i = 0, l = children.length; i < l; i++) {
  5062. children[i].traverse(callback);
  5063. }
  5064. }
  5065. traverseVisible(callback) {
  5066. if (this.visible === false) return;
  5067. callback(this);
  5068. const children = this.children;
  5069. for (let i = 0, l = children.length; i < l; i++) {
  5070. children[i].traverseVisible(callback);
  5071. }
  5072. }
  5073. traverseAncestors(callback) {
  5074. const parent = this.parent;
  5075. if (parent !== null) {
  5076. callback(parent);
  5077. parent.traverseAncestors(callback);
  5078. }
  5079. }
  5080. updateMatrix() {
  5081. this.matrix.compose(this.position, this.quaternion, this.scale);
  5082. this.matrixWorldNeedsUpdate = true;
  5083. }
  5084. updateMatrixWorld(force) {
  5085. if (this.matrixAutoUpdate) this.updateMatrix();
  5086. if (this.matrixWorldNeedsUpdate || force) {
  5087. if (this.parent === null) {
  5088. this.matrixWorld.copy(this.matrix);
  5089. } else {
  5090. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5091. }
  5092. this.matrixWorldNeedsUpdate = false;
  5093. force = true;
  5094. } // update children
  5095. const children = this.children;
  5096. for (let i = 0, l = children.length; i < l; i++) {
  5097. const child = children[i];
  5098. if (child.matrixWorldAutoUpdate === true || force === true) {
  5099. child.updateMatrixWorld(force);
  5100. }
  5101. }
  5102. }
  5103. updateWorldMatrix(updateParents, updateChildren) {
  5104. const parent = this.parent;
  5105. if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) {
  5106. parent.updateWorldMatrix(true, false);
  5107. }
  5108. if (this.matrixAutoUpdate) this.updateMatrix();
  5109. if (this.parent === null) {
  5110. this.matrixWorld.copy(this.matrix);
  5111. } else {
  5112. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5113. } // update children
  5114. if (updateChildren === true) {
  5115. const children = this.children;
  5116. for (let i = 0, l = children.length; i < l; i++) {
  5117. const child = children[i];
  5118. if (child.matrixWorldAutoUpdate === true) {
  5119. child.updateWorldMatrix(false, true);
  5120. }
  5121. }
  5122. }
  5123. }
  5124. toJSON(meta) {
  5125. // meta is a string when called from JSON.stringify
  5126. const isRootObject = meta === undefined || typeof meta === 'string';
  5127. const output = {}; // meta is a hash used to collect geometries, materials.
  5128. // not providing it implies that this is the root object
  5129. // being serialized.
  5130. if (isRootObject) {
  5131. // initialize meta obj
  5132. meta = {
  5133. geometries: {},
  5134. materials: {},
  5135. textures: {},
  5136. images: {},
  5137. shapes: {},
  5138. skeletons: {},
  5139. animations: {},
  5140. nodes: {}
  5141. };
  5142. output.metadata = {
  5143. version: 4.5,
  5144. type: 'Object',
  5145. generator: 'Object3D.toJSON'
  5146. };
  5147. } // standard Object3D serialization
  5148. const object = {};
  5149. object.uuid = this.uuid;
  5150. object.type = this.type;
  5151. if (this.name !== '') object.name = this.name;
  5152. if (this.castShadow === true) object.castShadow = true;
  5153. if (this.receiveShadow === true) object.receiveShadow = true;
  5154. if (this.visible === false) object.visible = false;
  5155. if (this.frustumCulled === false) object.frustumCulled = false;
  5156. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5157. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5158. object.layers = this.layers.mask;
  5159. object.matrix = this.matrix.toArray();
  5160. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5161. if (this.isInstancedMesh) {
  5162. object.type = 'InstancedMesh';
  5163. object.count = this.count;
  5164. object.instanceMatrix = this.instanceMatrix.toJSON();
  5165. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5166. } //
  5167. function serialize(library, element) {
  5168. if (library[element.uuid] === undefined) {
  5169. library[element.uuid] = element.toJSON(meta);
  5170. }
  5171. return element.uuid;
  5172. }
  5173. if (this.isScene) {
  5174. if (this.background) {
  5175. if (this.background.isColor) {
  5176. object.background = this.background.toJSON();
  5177. } else if (this.background.isTexture) {
  5178. object.background = this.background.toJSON(meta).uuid;
  5179. }
  5180. }
  5181. if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) {
  5182. object.environment = this.environment.toJSON(meta).uuid;
  5183. }
  5184. } else if (this.isMesh || this.isLine || this.isPoints) {
  5185. object.geometry = serialize(meta.geometries, this.geometry);
  5186. const parameters = this.geometry.parameters;
  5187. if (parameters !== undefined && parameters.shapes !== undefined) {
  5188. const shapes = parameters.shapes;
  5189. if (Array.isArray(shapes)) {
  5190. for (let i = 0, l = shapes.length; i < l; i++) {
  5191. const shape = shapes[i];
  5192. serialize(meta.shapes, shape);
  5193. }
  5194. } else {
  5195. serialize(meta.shapes, shapes);
  5196. }
  5197. }
  5198. }
  5199. if (this.isSkinnedMesh) {
  5200. object.bindMode = this.bindMode;
  5201. object.bindMatrix = this.bindMatrix.toArray();
  5202. if (this.skeleton !== undefined) {
  5203. serialize(meta.skeletons, this.skeleton);
  5204. object.skeleton = this.skeleton.uuid;
  5205. }
  5206. }
  5207. if (this.material !== undefined) {
  5208. if (Array.isArray(this.material)) {
  5209. const uuids = [];
  5210. for (let i = 0, l = this.material.length; i < l; i++) {
  5211. uuids.push(serialize(meta.materials, this.material[i]));
  5212. }
  5213. object.material = uuids;
  5214. } else {
  5215. object.material = serialize(meta.materials, this.material);
  5216. }
  5217. } //
  5218. if (this.children.length > 0) {
  5219. object.children = [];
  5220. for (let i = 0; i < this.children.length; i++) {
  5221. object.children.push(this.children[i].toJSON(meta).object);
  5222. }
  5223. } //
  5224. if (this.animations.length > 0) {
  5225. object.animations = [];
  5226. for (let i = 0; i < this.animations.length; i++) {
  5227. const animation = this.animations[i];
  5228. object.animations.push(serialize(meta.animations, animation));
  5229. }
  5230. }
  5231. if (isRootObject) {
  5232. const geometries = extractFromCache(meta.geometries);
  5233. const materials = extractFromCache(meta.materials);
  5234. const textures = extractFromCache(meta.textures);
  5235. const images = extractFromCache(meta.images);
  5236. const shapes = extractFromCache(meta.shapes);
  5237. const skeletons = extractFromCache(meta.skeletons);
  5238. const animations = extractFromCache(meta.animations);
  5239. const nodes = extractFromCache(meta.nodes);
  5240. if (geometries.length > 0) output.geometries = geometries;
  5241. if (materials.length > 0) output.materials = materials;
  5242. if (textures.length > 0) output.textures = textures;
  5243. if (images.length > 0) output.images = images;
  5244. if (shapes.length > 0) output.shapes = shapes;
  5245. if (skeletons.length > 0) output.skeletons = skeletons;
  5246. if (animations.length > 0) output.animations = animations;
  5247. if (nodes.length > 0) output.nodes = nodes;
  5248. }
  5249. output.object = object;
  5250. return output; // extract data from the cache hash
  5251. // remove metadata on each item
  5252. // and return as array
  5253. function extractFromCache(cache) {
  5254. const values = [];
  5255. for (const key in cache) {
  5256. const data = cache[key];
  5257. delete data.metadata;
  5258. values.push(data);
  5259. }
  5260. return values;
  5261. }
  5262. }
  5263. clone(recursive) {
  5264. return new this.constructor().copy(this, recursive);
  5265. }
  5266. copy(source, recursive = true) {
  5267. this.name = source.name;
  5268. this.up.copy(source.up);
  5269. this.position.copy(source.position);
  5270. this.rotation.order = source.rotation.order;
  5271. this.quaternion.copy(source.quaternion);
  5272. this.scale.copy(source.scale);
  5273. this.matrix.copy(source.matrix);
  5274. this.matrixWorld.copy(source.matrixWorld);
  5275. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5276. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5277. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5278. this.layers.mask = source.layers.mask;
  5279. this.visible = source.visible;
  5280. this.castShadow = source.castShadow;
  5281. this.receiveShadow = source.receiveShadow;
  5282. this.frustumCulled = source.frustumCulled;
  5283. this.renderOrder = source.renderOrder;
  5284. this.userData = JSON.parse(JSON.stringify(source.userData));
  5285. if (recursive === true) {
  5286. for (let i = 0; i < source.children.length; i++) {
  5287. const child = source.children[i];
  5288. this.add(child.clone());
  5289. }
  5290. }
  5291. return this;
  5292. }
  5293. }
  5294. Object3D.DefaultUp = /*@__PURE__*/new Vector3(0, 1, 0);
  5295. Object3D.DefaultMatrixAutoUpdate = true;
  5296. Object3D.DefaultMatrixWorldAutoUpdate = true;
  5297. const _v0$1 = /*@__PURE__*/new Vector3();
  5298. const _v1$3 = /*@__PURE__*/new Vector3();
  5299. const _v2$2 = /*@__PURE__*/new Vector3();
  5300. const _v3$1 = /*@__PURE__*/new Vector3();
  5301. const _vab = /*@__PURE__*/new Vector3();
  5302. const _vac = /*@__PURE__*/new Vector3();
  5303. const _vbc = /*@__PURE__*/new Vector3();
  5304. const _vap = /*@__PURE__*/new Vector3();
  5305. const _vbp = /*@__PURE__*/new Vector3();
  5306. const _vcp = /*@__PURE__*/new Vector3();
  5307. class Triangle {
  5308. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5309. this.a = a;
  5310. this.b = b;
  5311. this.c = c;
  5312. }
  5313. static getNormal(a, b, c, target) {
  5314. target.subVectors(c, b);
  5315. _v0$1.subVectors(a, b);
  5316. target.cross(_v0$1);
  5317. const targetLengthSq = target.lengthSq();
  5318. if (targetLengthSq > 0) {
  5319. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5320. }
  5321. return target.set(0, 0, 0);
  5322. } // static/instance method to calculate barycentric coordinates
  5323. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5324. static getBarycoord(point, a, b, c, target) {
  5325. _v0$1.subVectors(c, a);
  5326. _v1$3.subVectors(b, a);
  5327. _v2$2.subVectors(point, a);
  5328. const dot00 = _v0$1.dot(_v0$1);
  5329. const dot01 = _v0$1.dot(_v1$3);
  5330. const dot02 = _v0$1.dot(_v2$2);
  5331. const dot11 = _v1$3.dot(_v1$3);
  5332. const dot12 = _v1$3.dot(_v2$2);
  5333. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  5334. if (denom === 0) {
  5335. // arbitrary location outside of triangle?
  5336. // not sure if this is the best idea, maybe should be returning undefined
  5337. return target.set(-2, -1, -1);
  5338. }
  5339. const invDenom = 1 / denom;
  5340. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5341. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5342. return target.set(1 - u - v, v, u);
  5343. }
  5344. static containsPoint(point, a, b, c) {
  5345. this.getBarycoord(point, a, b, c, _v3$1);
  5346. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5347. }
  5348. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5349. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5350. target.set(0, 0);
  5351. target.addScaledVector(uv1, _v3$1.x);
  5352. target.addScaledVector(uv2, _v3$1.y);
  5353. target.addScaledVector(uv3, _v3$1.z);
  5354. return target;
  5355. }
  5356. static isFrontFacing(a, b, c, direction) {
  5357. _v0$1.subVectors(c, b);
  5358. _v1$3.subVectors(a, b); // strictly front facing
  5359. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5360. }
  5361. set(a, b, c) {
  5362. this.a.copy(a);
  5363. this.b.copy(b);
  5364. this.c.copy(c);
  5365. return this;
  5366. }
  5367. setFromPointsAndIndices(points, i0, i1, i2) {
  5368. this.a.copy(points[i0]);
  5369. this.b.copy(points[i1]);
  5370. this.c.copy(points[i2]);
  5371. return this;
  5372. }
  5373. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5374. this.a.fromBufferAttribute(attribute, i0);
  5375. this.b.fromBufferAttribute(attribute, i1);
  5376. this.c.fromBufferAttribute(attribute, i2);
  5377. return this;
  5378. }
  5379. clone() {
  5380. return new this.constructor().copy(this);
  5381. }
  5382. copy(triangle) {
  5383. this.a.copy(triangle.a);
  5384. this.b.copy(triangle.b);
  5385. this.c.copy(triangle.c);
  5386. return this;
  5387. }
  5388. getArea() {
  5389. _v0$1.subVectors(this.c, this.b);
  5390. _v1$3.subVectors(this.a, this.b);
  5391. return _v0$1.cross(_v1$3).length() * 0.5;
  5392. }
  5393. getMidpoint(target) {
  5394. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5395. }
  5396. getNormal(target) {
  5397. return Triangle.getNormal(this.a, this.b, this.c, target);
  5398. }
  5399. getPlane(target) {
  5400. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5401. }
  5402. getBarycoord(point, target) {
  5403. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5404. }
  5405. getUV(point, uv1, uv2, uv3, target) {
  5406. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5407. }
  5408. containsPoint(point) {
  5409. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5410. }
  5411. isFrontFacing(direction) {
  5412. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5413. }
  5414. intersectsBox(box) {
  5415. return box.intersectsTriangle(this);
  5416. }
  5417. closestPointToPoint(p, target) {
  5418. const a = this.a,
  5419. b = this.b,
  5420. c = this.c;
  5421. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5422. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5423. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5424. // basically, we're distinguishing which of the voronoi regions of the triangle
  5425. // the point lies in with the minimum amount of redundant computation.
  5426. _vab.subVectors(b, a);
  5427. _vac.subVectors(c, a);
  5428. _vap.subVectors(p, a);
  5429. const d1 = _vab.dot(_vap);
  5430. const d2 = _vac.dot(_vap);
  5431. if (d1 <= 0 && d2 <= 0) {
  5432. // vertex region of A; barycentric coords (1, 0, 0)
  5433. return target.copy(a);
  5434. }
  5435. _vbp.subVectors(p, b);
  5436. const d3 = _vab.dot(_vbp);
  5437. const d4 = _vac.dot(_vbp);
  5438. if (d3 >= 0 && d4 <= d3) {
  5439. // vertex region of B; barycentric coords (0, 1, 0)
  5440. return target.copy(b);
  5441. }
  5442. const vc = d1 * d4 - d3 * d2;
  5443. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5444. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5445. return target.copy(a).addScaledVector(_vab, v);
  5446. }
  5447. _vcp.subVectors(p, c);
  5448. const d5 = _vab.dot(_vcp);
  5449. const d6 = _vac.dot(_vcp);
  5450. if (d6 >= 0 && d5 <= d6) {
  5451. // vertex region of C; barycentric coords (0, 0, 1)
  5452. return target.copy(c);
  5453. }
  5454. const vb = d5 * d2 - d1 * d6;
  5455. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5456. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5457. return target.copy(a).addScaledVector(_vac, w);
  5458. }
  5459. const va = d3 * d6 - d5 * d4;
  5460. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5461. _vbc.subVectors(c, b);
  5462. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5463. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5464. } // face region
  5465. const denom = 1 / (va + vb + vc); // u = va * denom
  5466. v = vb * denom;
  5467. w = vc * denom;
  5468. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5469. }
  5470. equals(triangle) {
  5471. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5472. }
  5473. }
  5474. let materialId = 0;
  5475. class Material extends EventDispatcher {
  5476. constructor() {
  5477. super();
  5478. this.isMaterial = true;
  5479. Object.defineProperty(this, 'id', {
  5480. value: materialId++
  5481. });
  5482. this.uuid = generateUUID();
  5483. this.name = '';
  5484. this.type = 'Material';
  5485. this.blending = NormalBlending;
  5486. this.side = FrontSide;
  5487. this.vertexColors = false;
  5488. this.opacity = 1;
  5489. this.transparent = false;
  5490. this.blendSrc = SrcAlphaFactor;
  5491. this.blendDst = OneMinusSrcAlphaFactor;
  5492. this.blendEquation = AddEquation;
  5493. this.blendSrcAlpha = null;
  5494. this.blendDstAlpha = null;
  5495. this.blendEquationAlpha = null;
  5496. this.depthFunc = LessEqualDepth;
  5497. this.depthTest = true;
  5498. this.depthWrite = true;
  5499. this.stencilWriteMask = 0xff;
  5500. this.stencilFunc = AlwaysStencilFunc;
  5501. this.stencilRef = 0;
  5502. this.stencilFuncMask = 0xff;
  5503. this.stencilFail = KeepStencilOp;
  5504. this.stencilZFail = KeepStencilOp;
  5505. this.stencilZPass = KeepStencilOp;
  5506. this.stencilWrite = false;
  5507. this.clippingPlanes = null;
  5508. this.clipIntersection = false;
  5509. this.clipShadows = false;
  5510. this.shadowSide = null;
  5511. this.colorWrite = true;
  5512. this.precision = null; // override the renderer's default precision for this material
  5513. this.polygonOffset = false;
  5514. this.polygonOffsetFactor = 0;
  5515. this.polygonOffsetUnits = 0;
  5516. this.dithering = false;
  5517. this.alphaToCoverage = false;
  5518. this.premultipliedAlpha = false;
  5519. this.visible = true;
  5520. this.toneMapped = true;
  5521. this.userData = {};
  5522. this.version = 0;
  5523. this._alphaTest = 0;
  5524. }
  5525. get alphaTest() {
  5526. return this._alphaTest;
  5527. }
  5528. set alphaTest(value) {
  5529. if (this._alphaTest > 0 !== value > 0) {
  5530. this.version++;
  5531. }
  5532. this._alphaTest = value;
  5533. }
  5534. onBuild() {}
  5535. onBeforeRender() {}
  5536. onBeforeCompile() {}
  5537. customProgramCacheKey() {
  5538. return this.onBeforeCompile.toString();
  5539. }
  5540. setValues(values) {
  5541. if (values === undefined) return;
  5542. for (const key in values) {
  5543. const newValue = values[key];
  5544. if (newValue === undefined) {
  5545. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5546. continue;
  5547. }
  5548. const currentValue = this[key];
  5549. if (currentValue === undefined) {
  5550. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5551. continue;
  5552. }
  5553. if (currentValue && currentValue.isColor) {
  5554. currentValue.set(newValue);
  5555. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5556. currentValue.copy(newValue);
  5557. } else {
  5558. this[key] = newValue;
  5559. }
  5560. }
  5561. }
  5562. toJSON(meta) {
  5563. const isRootObject = meta === undefined || typeof meta === 'string';
  5564. if (isRootObject) {
  5565. meta = {
  5566. textures: {},
  5567. images: {}
  5568. };
  5569. }
  5570. const data = {
  5571. metadata: {
  5572. version: 4.5,
  5573. type: 'Material',
  5574. generator: 'Material.toJSON'
  5575. }
  5576. }; // standard Material serialization
  5577. data.uuid = this.uuid;
  5578. data.type = this.type;
  5579. if (this.name !== '') data.name = this.name;
  5580. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5581. if (this.roughness !== undefined) data.roughness = this.roughness;
  5582. if (this.metalness !== undefined) data.metalness = this.metalness;
  5583. if (this.sheen !== undefined) data.sheen = this.sheen;
  5584. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5585. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5586. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5587. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5588. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5589. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5590. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5591. if (this.shininess !== undefined) data.shininess = this.shininess;
  5592. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5593. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5594. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5595. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5596. }
  5597. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5598. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5599. }
  5600. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5601. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5602. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5603. }
  5604. if (this.iridescence !== undefined) data.iridescence = this.iridescence;
  5605. if (this.iridescenceIOR !== undefined) data.iridescenceIOR = this.iridescenceIOR;
  5606. if (this.iridescenceThicknessRange !== undefined) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5607. if (this.iridescenceMap && this.iridescenceMap.isTexture) {
  5608. data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid;
  5609. }
  5610. if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) {
  5611. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid;
  5612. }
  5613. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5614. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5615. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5616. if (this.lightMap && this.lightMap.isTexture) {
  5617. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5618. data.lightMapIntensity = this.lightMapIntensity;
  5619. }
  5620. if (this.aoMap && this.aoMap.isTexture) {
  5621. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5622. data.aoMapIntensity = this.aoMapIntensity;
  5623. }
  5624. if (this.bumpMap && this.bumpMap.isTexture) {
  5625. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5626. data.bumpScale = this.bumpScale;
  5627. }
  5628. if (this.normalMap && this.normalMap.isTexture) {
  5629. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5630. data.normalMapType = this.normalMapType;
  5631. data.normalScale = this.normalScale.toArray();
  5632. }
  5633. if (this.displacementMap && this.displacementMap.isTexture) {
  5634. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5635. data.displacementScale = this.displacementScale;
  5636. data.displacementBias = this.displacementBias;
  5637. }
  5638. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5639. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5640. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5641. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5642. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5643. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5644. if (this.envMap && this.envMap.isTexture) {
  5645. data.envMap = this.envMap.toJSON(meta).uuid;
  5646. if (this.combine !== undefined) data.combine = this.combine;
  5647. }
  5648. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5649. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5650. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5651. if (this.gradientMap && this.gradientMap.isTexture) {
  5652. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5653. }
  5654. if (this.transmission !== undefined) data.transmission = this.transmission;
  5655. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5656. if (this.thickness !== undefined) data.thickness = this.thickness;
  5657. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5658. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5659. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5660. if (this.size !== undefined) data.size = this.size;
  5661. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5662. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5663. if (this.blending !== NormalBlending) data.blending = this.blending;
  5664. if (this.side !== FrontSide) data.side = this.side;
  5665. if (this.vertexColors) data.vertexColors = true;
  5666. if (this.opacity < 1) data.opacity = this.opacity;
  5667. if (this.transparent === true) data.transparent = this.transparent;
  5668. data.depthFunc = this.depthFunc;
  5669. data.depthTest = this.depthTest;
  5670. data.depthWrite = this.depthWrite;
  5671. data.colorWrite = this.colorWrite;
  5672. data.stencilWrite = this.stencilWrite;
  5673. data.stencilWriteMask = this.stencilWriteMask;
  5674. data.stencilFunc = this.stencilFunc;
  5675. data.stencilRef = this.stencilRef;
  5676. data.stencilFuncMask = this.stencilFuncMask;
  5677. data.stencilFail = this.stencilFail;
  5678. data.stencilZFail = this.stencilZFail;
  5679. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5680. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5681. if (this.polygonOffset === true) data.polygonOffset = true;
  5682. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5683. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5684. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5685. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5686. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5687. if (this.scale !== undefined) data.scale = this.scale;
  5688. if (this.dithering === true) data.dithering = true;
  5689. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5690. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5691. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5692. if (this.wireframe === true) data.wireframe = this.wireframe;
  5693. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5694. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5695. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5696. if (this.flatShading === true) data.flatShading = this.flatShading;
  5697. if (this.visible === false) data.visible = false;
  5698. if (this.toneMapped === false) data.toneMapped = false;
  5699. if (this.fog === false) data.fog = false;
  5700. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5701. function extractFromCache(cache) {
  5702. const values = [];
  5703. for (const key in cache) {
  5704. const data = cache[key];
  5705. delete data.metadata;
  5706. values.push(data);
  5707. }
  5708. return values;
  5709. }
  5710. if (isRootObject) {
  5711. const textures = extractFromCache(meta.textures);
  5712. const images = extractFromCache(meta.images);
  5713. if (textures.length > 0) data.textures = textures;
  5714. if (images.length > 0) data.images = images;
  5715. }
  5716. return data;
  5717. }
  5718. clone() {
  5719. return new this.constructor().copy(this);
  5720. }
  5721. copy(source) {
  5722. this.name = source.name;
  5723. this.blending = source.blending;
  5724. this.side = source.side;
  5725. this.vertexColors = source.vertexColors;
  5726. this.opacity = source.opacity;
  5727. this.transparent = source.transparent;
  5728. this.blendSrc = source.blendSrc;
  5729. this.blendDst = source.blendDst;
  5730. this.blendEquation = source.blendEquation;
  5731. this.blendSrcAlpha = source.blendSrcAlpha;
  5732. this.blendDstAlpha = source.blendDstAlpha;
  5733. this.blendEquationAlpha = source.blendEquationAlpha;
  5734. this.depthFunc = source.depthFunc;
  5735. this.depthTest = source.depthTest;
  5736. this.depthWrite = source.depthWrite;
  5737. this.stencilWriteMask = source.stencilWriteMask;
  5738. this.stencilFunc = source.stencilFunc;
  5739. this.stencilRef = source.stencilRef;
  5740. this.stencilFuncMask = source.stencilFuncMask;
  5741. this.stencilFail = source.stencilFail;
  5742. this.stencilZFail = source.stencilZFail;
  5743. this.stencilZPass = source.stencilZPass;
  5744. this.stencilWrite = source.stencilWrite;
  5745. const srcPlanes = source.clippingPlanes;
  5746. let dstPlanes = null;
  5747. if (srcPlanes !== null) {
  5748. const n = srcPlanes.length;
  5749. dstPlanes = new Array(n);
  5750. for (let i = 0; i !== n; ++i) {
  5751. dstPlanes[i] = srcPlanes[i].clone();
  5752. }
  5753. }
  5754. this.clippingPlanes = dstPlanes;
  5755. this.clipIntersection = source.clipIntersection;
  5756. this.clipShadows = source.clipShadows;
  5757. this.shadowSide = source.shadowSide;
  5758. this.colorWrite = source.colorWrite;
  5759. this.precision = source.precision;
  5760. this.polygonOffset = source.polygonOffset;
  5761. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5762. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5763. this.dithering = source.dithering;
  5764. this.alphaTest = source.alphaTest;
  5765. this.alphaToCoverage = source.alphaToCoverage;
  5766. this.premultipliedAlpha = source.premultipliedAlpha;
  5767. this.visible = source.visible;
  5768. this.toneMapped = source.toneMapped;
  5769. this.userData = JSON.parse(JSON.stringify(source.userData));
  5770. return this;
  5771. }
  5772. dispose() {
  5773. this.dispatchEvent({
  5774. type: 'dispose'
  5775. });
  5776. }
  5777. set needsUpdate(value) {
  5778. if (value === true) this.version++;
  5779. }
  5780. }
  5781. class MeshBasicMaterial extends Material {
  5782. constructor(parameters) {
  5783. super();
  5784. this.isMeshBasicMaterial = true;
  5785. this.type = 'MeshBasicMaterial';
  5786. this.color = new Color(0xffffff); // emissive
  5787. this.map = null;
  5788. this.lightMap = null;
  5789. this.lightMapIntensity = 1.0;
  5790. this.aoMap = null;
  5791. this.aoMapIntensity = 1.0;
  5792. this.specularMap = null;
  5793. this.alphaMap = null;
  5794. this.envMap = null;
  5795. this.combine = MultiplyOperation;
  5796. this.reflectivity = 1;
  5797. this.refractionRatio = 0.98;
  5798. this.wireframe = false;
  5799. this.wireframeLinewidth = 1;
  5800. this.wireframeLinecap = 'round';
  5801. this.wireframeLinejoin = 'round';
  5802. this.fog = true;
  5803. this.setValues(parameters);
  5804. }
  5805. copy(source) {
  5806. super.copy(source);
  5807. this.color.copy(source.color);
  5808. this.map = source.map;
  5809. this.lightMap = source.lightMap;
  5810. this.lightMapIntensity = source.lightMapIntensity;
  5811. this.aoMap = source.aoMap;
  5812. this.aoMapIntensity = source.aoMapIntensity;
  5813. this.specularMap = source.specularMap;
  5814. this.alphaMap = source.alphaMap;
  5815. this.envMap = source.envMap;
  5816. this.combine = source.combine;
  5817. this.reflectivity = source.reflectivity;
  5818. this.refractionRatio = source.refractionRatio;
  5819. this.wireframe = source.wireframe;
  5820. this.wireframeLinewidth = source.wireframeLinewidth;
  5821. this.wireframeLinecap = source.wireframeLinecap;
  5822. this.wireframeLinejoin = source.wireframeLinejoin;
  5823. this.fog = source.fog;
  5824. return this;
  5825. }
  5826. }
  5827. const _vector$9 = /*@__PURE__*/new Vector3();
  5828. const _vector2$1 = /*@__PURE__*/new Vector2();
  5829. class BufferAttribute {
  5830. constructor(array, itemSize, normalized) {
  5831. if (Array.isArray(array)) {
  5832. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5833. }
  5834. this.isBufferAttribute = true;
  5835. this.name = '';
  5836. this.array = array;
  5837. this.itemSize = itemSize;
  5838. this.count = array !== undefined ? array.length / itemSize : 0;
  5839. this.normalized = normalized === true;
  5840. this.usage = StaticDrawUsage;
  5841. this.updateRange = {
  5842. offset: 0,
  5843. count: -1
  5844. };
  5845. this.version = 0;
  5846. }
  5847. onUploadCallback() {}
  5848. set needsUpdate(value) {
  5849. if (value === true) this.version++;
  5850. }
  5851. setUsage(value) {
  5852. this.usage = value;
  5853. return this;
  5854. }
  5855. copy(source) {
  5856. this.name = source.name;
  5857. this.array = new source.array.constructor(source.array);
  5858. this.itemSize = source.itemSize;
  5859. this.count = source.count;
  5860. this.normalized = source.normalized;
  5861. this.usage = source.usage;
  5862. return this;
  5863. }
  5864. copyAt(index1, attribute, index2) {
  5865. index1 *= this.itemSize;
  5866. index2 *= attribute.itemSize;
  5867. for (let i = 0, l = this.itemSize; i < l; i++) {
  5868. this.array[index1 + i] = attribute.array[index2 + i];
  5869. }
  5870. return this;
  5871. }
  5872. copyArray(array) {
  5873. this.array.set(array);
  5874. return this;
  5875. }
  5876. copyColorsArray(colors) {
  5877. const array = this.array;
  5878. let offset = 0;
  5879. for (let i = 0, l = colors.length; i < l; i++) {
  5880. let color = colors[i];
  5881. if (color === undefined) {
  5882. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5883. color = new Color();
  5884. }
  5885. if (this.normalized) {
  5886. array[offset++] = normalize(color.r, array);
  5887. array[offset++] = normalize(color.g, array);
  5888. array[offset++] = normalize(color.b, array);
  5889. } else {
  5890. array[offset++] = color.r;
  5891. array[offset++] = color.g;
  5892. array[offset++] = color.b;
  5893. }
  5894. }
  5895. return this;
  5896. }
  5897. copyVector2sArray(vectors) {
  5898. const array = this.array;
  5899. let offset = 0;
  5900. for (let i = 0, l = vectors.length; i < l; i++) {
  5901. let vector = vectors[i];
  5902. if (vector === undefined) {
  5903. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5904. vector = new Vector2();
  5905. }
  5906. if (this.normalized) {
  5907. array[offset++] = normalize(vector.x, array);
  5908. array[offset++] = normalize(vector.y, array);
  5909. } else {
  5910. array[offset++] = vector.x;
  5911. array[offset++] = vector.y;
  5912. }
  5913. }
  5914. return this;
  5915. }
  5916. copyVector3sArray(vectors) {
  5917. const array = this.array;
  5918. let offset = 0;
  5919. for (let i = 0, l = vectors.length; i < l; i++) {
  5920. let vector = vectors[i];
  5921. if (vector === undefined) {
  5922. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5923. vector = new Vector3();
  5924. }
  5925. if (this.normalized) {
  5926. array[offset++] = normalize(vector.x, array);
  5927. array[offset++] = normalize(vector.y, array);
  5928. array[offset++] = normalize(vector.z, array);
  5929. } else {
  5930. array[offset++] = vector.x;
  5931. array[offset++] = vector.y;
  5932. array[offset++] = vector.z;
  5933. }
  5934. }
  5935. return this;
  5936. }
  5937. copyVector4sArray(vectors) {
  5938. const array = this.array;
  5939. let offset = 0;
  5940. for (let i = 0, l = vectors.length; i < l; i++) {
  5941. let vector = vectors[i];
  5942. if (vector === undefined) {
  5943. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5944. vector = new Vector4();
  5945. }
  5946. if (this.normalized) {
  5947. array[offset++] = normalize(vector.x, array);
  5948. array[offset++] = normalize(vector.y, array);
  5949. array[offset++] = normalize(vector.z, array);
  5950. array[offset++] = normalize(vector.w, array);
  5951. } else {
  5952. array[offset++] = vector.x;
  5953. array[offset++] = vector.y;
  5954. array[offset++] = vector.z;
  5955. array[offset++] = vector.w;
  5956. }
  5957. }
  5958. return this;
  5959. }
  5960. applyMatrix3(m) {
  5961. if (this.itemSize === 2) {
  5962. for (let i = 0, l = this.count; i < l; i++) {
  5963. _vector2$1.fromBufferAttribute(this, i);
  5964. _vector2$1.applyMatrix3(m);
  5965. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5966. }
  5967. } else if (this.itemSize === 3) {
  5968. for (let i = 0, l = this.count; i < l; i++) {
  5969. _vector$9.fromBufferAttribute(this, i);
  5970. _vector$9.applyMatrix3(m);
  5971. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5972. }
  5973. }
  5974. return this;
  5975. }
  5976. applyMatrix4(m) {
  5977. for (let i = 0, l = this.count; i < l; i++) {
  5978. _vector$9.fromBufferAttribute(this, i);
  5979. _vector$9.applyMatrix4(m);
  5980. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5981. }
  5982. return this;
  5983. }
  5984. applyNormalMatrix(m) {
  5985. for (let i = 0, l = this.count; i < l; i++) {
  5986. _vector$9.fromBufferAttribute(this, i);
  5987. _vector$9.applyNormalMatrix(m);
  5988. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5989. }
  5990. return this;
  5991. }
  5992. transformDirection(m) {
  5993. for (let i = 0, l = this.count; i < l; i++) {
  5994. _vector$9.fromBufferAttribute(this, i);
  5995. _vector$9.transformDirection(m);
  5996. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5997. }
  5998. return this;
  5999. }
  6000. set(value, offset = 0) {
  6001. // Matching BufferAttribute constructor, do not normalize the array.
  6002. this.array.set(value, offset);
  6003. return this;
  6004. }
  6005. getX(index) {
  6006. let x = this.array[index * this.itemSize];
  6007. if (this.normalized) x = denormalize(x, this.array);
  6008. return x;
  6009. }
  6010. setX(index, x) {
  6011. if (this.normalized) x = normalize(x, this.array);
  6012. this.array[index * this.itemSize] = x;
  6013. return this;
  6014. }
  6015. getY(index) {
  6016. let y = this.array[index * this.itemSize + 1];
  6017. if (this.normalized) y = denormalize(y, this.array);
  6018. return y;
  6019. }
  6020. setY(index, y) {
  6021. if (this.normalized) y = normalize(y, this.array);
  6022. this.array[index * this.itemSize + 1] = y;
  6023. return this;
  6024. }
  6025. getZ(index) {
  6026. let z = this.array[index * this.itemSize + 2];
  6027. if (this.normalized) z = denormalize(z, this.array);
  6028. return z;
  6029. }
  6030. setZ(index, z) {
  6031. if (this.normalized) z = normalize(z, this.array);
  6032. this.array[index * this.itemSize + 2] = z;
  6033. return this;
  6034. }
  6035. getW(index) {
  6036. let w = this.array[index * this.itemSize + 3];
  6037. if (this.normalized) w = denormalize(w, this.array);
  6038. return w;
  6039. }
  6040. setW(index, w) {
  6041. if (this.normalized) w = normalize(w, this.array);
  6042. this.array[index * this.itemSize + 3] = w;
  6043. return this;
  6044. }
  6045. setXY(index, x, y) {
  6046. index *= this.itemSize;
  6047. if (this.normalized) {
  6048. x = normalize(x, this.array);
  6049. y = normalize(y, this.array);
  6050. }
  6051. this.array[index + 0] = x;
  6052. this.array[index + 1] = y;
  6053. return this;
  6054. }
  6055. setXYZ(index, x, y, z) {
  6056. index *= this.itemSize;
  6057. if (this.normalized) {
  6058. x = normalize(x, this.array);
  6059. y = normalize(y, this.array);
  6060. z = normalize(z, this.array);
  6061. }
  6062. this.array[index + 0] = x;
  6063. this.array[index + 1] = y;
  6064. this.array[index + 2] = z;
  6065. return this;
  6066. }
  6067. setXYZW(index, x, y, z, w) {
  6068. index *= this.itemSize;
  6069. if (this.normalized) {
  6070. x = normalize(x, this.array);
  6071. y = normalize(y, this.array);
  6072. z = normalize(z, this.array);
  6073. w = normalize(w, this.array);
  6074. }
  6075. this.array[index + 0] = x;
  6076. this.array[index + 1] = y;
  6077. this.array[index + 2] = z;
  6078. this.array[index + 3] = w;
  6079. return this;
  6080. }
  6081. onUpload(callback) {
  6082. this.onUploadCallback = callback;
  6083. return this;
  6084. }
  6085. clone() {
  6086. return new this.constructor(this.array, this.itemSize).copy(this);
  6087. }
  6088. toJSON() {
  6089. const data = {
  6090. itemSize: this.itemSize,
  6091. type: this.array.constructor.name,
  6092. array: Array.from(this.array),
  6093. normalized: this.normalized
  6094. };
  6095. if (this.name !== '') data.name = this.name;
  6096. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6097. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6098. return data;
  6099. }
  6100. } //
  6101. class Int8BufferAttribute extends BufferAttribute {
  6102. constructor(array, itemSize, normalized) {
  6103. super(new Int8Array(array), itemSize, normalized);
  6104. }
  6105. }
  6106. class Uint8BufferAttribute extends BufferAttribute {
  6107. constructor(array, itemSize, normalized) {
  6108. super(new Uint8Array(array), itemSize, normalized);
  6109. }
  6110. }
  6111. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6112. constructor(array, itemSize, normalized) {
  6113. super(new Uint8ClampedArray(array), itemSize, normalized);
  6114. }
  6115. }
  6116. class Int16BufferAttribute extends BufferAttribute {
  6117. constructor(array, itemSize, normalized) {
  6118. super(new Int16Array(array), itemSize, normalized);
  6119. }
  6120. }
  6121. class Uint16BufferAttribute extends BufferAttribute {
  6122. constructor(array, itemSize, normalized) {
  6123. super(new Uint16Array(array), itemSize, normalized);
  6124. }
  6125. }
  6126. class Int32BufferAttribute extends BufferAttribute {
  6127. constructor(array, itemSize, normalized) {
  6128. super(new Int32Array(array), itemSize, normalized);
  6129. }
  6130. }
  6131. class Uint32BufferAttribute extends BufferAttribute {
  6132. constructor(array, itemSize, normalized) {
  6133. super(new Uint32Array(array), itemSize, normalized);
  6134. }
  6135. }
  6136. class Float16BufferAttribute extends BufferAttribute {
  6137. constructor(array, itemSize, normalized) {
  6138. super(new Uint16Array(array), itemSize, normalized);
  6139. this.isFloat16BufferAttribute = true;
  6140. }
  6141. }
  6142. class Float32BufferAttribute extends BufferAttribute {
  6143. constructor(array, itemSize, normalized) {
  6144. super(new Float32Array(array), itemSize, normalized);
  6145. }
  6146. }
  6147. class Float64BufferAttribute extends BufferAttribute {
  6148. constructor(array, itemSize, normalized) {
  6149. super(new Float64Array(array), itemSize, normalized);
  6150. }
  6151. } //
  6152. let _id$1 = 0;
  6153. const _m1 = /*@__PURE__*/new Matrix4();
  6154. const _obj = /*@__PURE__*/new Object3D();
  6155. const _offset = /*@__PURE__*/new Vector3();
  6156. const _box$1 = /*@__PURE__*/new Box3();
  6157. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6158. const _vector$8 = /*@__PURE__*/new Vector3();
  6159. class BufferGeometry extends EventDispatcher {
  6160. constructor() {
  6161. super();
  6162. this.isBufferGeometry = true;
  6163. Object.defineProperty(this, 'id', {
  6164. value: _id$1++
  6165. });
  6166. this.uuid = generateUUID();
  6167. this.name = '';
  6168. this.type = 'BufferGeometry';
  6169. this.index = null;
  6170. this.attributes = {};
  6171. this.morphAttributes = {};
  6172. this.morphTargetsRelative = false;
  6173. this.groups = [];
  6174. this.boundingBox = null;
  6175. this.boundingSphere = null;
  6176. this.drawRange = {
  6177. start: 0,
  6178. count: Infinity
  6179. };
  6180. this.userData = {};
  6181. }
  6182. getIndex() {
  6183. return this.index;
  6184. }
  6185. setIndex(index) {
  6186. if (Array.isArray(index)) {
  6187. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6188. } else {
  6189. this.index = index;
  6190. }
  6191. return this;
  6192. }
  6193. getAttribute(name) {
  6194. return this.attributes[name];
  6195. }
  6196. setAttribute(name, attribute) {
  6197. this.attributes[name] = attribute;
  6198. return this;
  6199. }
  6200. deleteAttribute(name) {
  6201. delete this.attributes[name];
  6202. return this;
  6203. }
  6204. hasAttribute(name) {
  6205. return this.attributes[name] !== undefined;
  6206. }
  6207. addGroup(start, count, materialIndex = 0) {
  6208. this.groups.push({
  6209. start: start,
  6210. count: count,
  6211. materialIndex: materialIndex
  6212. });
  6213. }
  6214. clearGroups() {
  6215. this.groups = [];
  6216. }
  6217. setDrawRange(start, count) {
  6218. this.drawRange.start = start;
  6219. this.drawRange.count = count;
  6220. }
  6221. applyMatrix4(matrix) {
  6222. const position = this.attributes.position;
  6223. if (position !== undefined) {
  6224. position.applyMatrix4(matrix);
  6225. position.needsUpdate = true;
  6226. }
  6227. const normal = this.attributes.normal;
  6228. if (normal !== undefined) {
  6229. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6230. normal.applyNormalMatrix(normalMatrix);
  6231. normal.needsUpdate = true;
  6232. }
  6233. const tangent = this.attributes.tangent;
  6234. if (tangent !== undefined) {
  6235. tangent.transformDirection(matrix);
  6236. tangent.needsUpdate = true;
  6237. }
  6238. if (this.boundingBox !== null) {
  6239. this.computeBoundingBox();
  6240. }
  6241. if (this.boundingSphere !== null) {
  6242. this.computeBoundingSphere();
  6243. }
  6244. return this;
  6245. }
  6246. applyQuaternion(q) {
  6247. _m1.makeRotationFromQuaternion(q);
  6248. this.applyMatrix4(_m1);
  6249. return this;
  6250. }
  6251. rotateX(angle) {
  6252. // rotate geometry around world x-axis
  6253. _m1.makeRotationX(angle);
  6254. this.applyMatrix4(_m1);
  6255. return this;
  6256. }
  6257. rotateY(angle) {
  6258. // rotate geometry around world y-axis
  6259. _m1.makeRotationY(angle);
  6260. this.applyMatrix4(_m1);
  6261. return this;
  6262. }
  6263. rotateZ(angle) {
  6264. // rotate geometry around world z-axis
  6265. _m1.makeRotationZ(angle);
  6266. this.applyMatrix4(_m1);
  6267. return this;
  6268. }
  6269. translate(x, y, z) {
  6270. // translate geometry
  6271. _m1.makeTranslation(x, y, z);
  6272. this.applyMatrix4(_m1);
  6273. return this;
  6274. }
  6275. scale(x, y, z) {
  6276. // scale geometry
  6277. _m1.makeScale(x, y, z);
  6278. this.applyMatrix4(_m1);
  6279. return this;
  6280. }
  6281. lookAt(vector) {
  6282. _obj.lookAt(vector);
  6283. _obj.updateMatrix();
  6284. this.applyMatrix4(_obj.matrix);
  6285. return this;
  6286. }
  6287. center() {
  6288. this.computeBoundingBox();
  6289. this.boundingBox.getCenter(_offset).negate();
  6290. this.translate(_offset.x, _offset.y, _offset.z);
  6291. return this;
  6292. }
  6293. setFromPoints(points) {
  6294. const position = [];
  6295. for (let i = 0, l = points.length; i < l; i++) {
  6296. const point = points[i];
  6297. position.push(point.x, point.y, point.z || 0);
  6298. }
  6299. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6300. return this;
  6301. }
  6302. computeBoundingBox() {
  6303. if (this.boundingBox === null) {
  6304. this.boundingBox = new Box3();
  6305. }
  6306. const position = this.attributes.position;
  6307. const morphAttributesPosition = this.morphAttributes.position;
  6308. if (position && position.isGLBufferAttribute) {
  6309. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6310. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6311. return;
  6312. }
  6313. if (position !== undefined) {
  6314. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6315. if (morphAttributesPosition) {
  6316. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6317. const morphAttribute = morphAttributesPosition[i];
  6318. _box$1.setFromBufferAttribute(morphAttribute);
  6319. if (this.morphTargetsRelative) {
  6320. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6321. this.boundingBox.expandByPoint(_vector$8);
  6322. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6323. this.boundingBox.expandByPoint(_vector$8);
  6324. } else {
  6325. this.boundingBox.expandByPoint(_box$1.min);
  6326. this.boundingBox.expandByPoint(_box$1.max);
  6327. }
  6328. }
  6329. }
  6330. } else {
  6331. this.boundingBox.makeEmpty();
  6332. }
  6333. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6334. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6335. }
  6336. }
  6337. computeBoundingSphere() {
  6338. if (this.boundingSphere === null) {
  6339. this.boundingSphere = new Sphere();
  6340. }
  6341. const position = this.attributes.position;
  6342. const morphAttributesPosition = this.morphAttributes.position;
  6343. if (position && position.isGLBufferAttribute) {
  6344. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6345. this.boundingSphere.set(new Vector3(), Infinity);
  6346. return;
  6347. }
  6348. if (position) {
  6349. // first, find the center of the bounding sphere
  6350. const center = this.boundingSphere.center;
  6351. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6352. if (morphAttributesPosition) {
  6353. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6354. const morphAttribute = morphAttributesPosition[i];
  6355. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6356. if (this.morphTargetsRelative) {
  6357. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6358. _box$1.expandByPoint(_vector$8);
  6359. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6360. _box$1.expandByPoint(_vector$8);
  6361. } else {
  6362. _box$1.expandByPoint(_boxMorphTargets.min);
  6363. _box$1.expandByPoint(_boxMorphTargets.max);
  6364. }
  6365. }
  6366. }
  6367. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6368. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6369. let maxRadiusSq = 0;
  6370. for (let i = 0, il = position.count; i < il; i++) {
  6371. _vector$8.fromBufferAttribute(position, i);
  6372. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6373. } // process morph attributes if present
  6374. if (morphAttributesPosition) {
  6375. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6376. const morphAttribute = morphAttributesPosition[i];
  6377. const morphTargetsRelative = this.morphTargetsRelative;
  6378. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6379. _vector$8.fromBufferAttribute(morphAttribute, j);
  6380. if (morphTargetsRelative) {
  6381. _offset.fromBufferAttribute(position, j);
  6382. _vector$8.add(_offset);
  6383. }
  6384. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6385. }
  6386. }
  6387. }
  6388. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6389. if (isNaN(this.boundingSphere.radius)) {
  6390. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6391. }
  6392. }
  6393. }
  6394. computeTangents() {
  6395. const index = this.index;
  6396. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6397. // (per vertex tangents)
  6398. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6399. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6400. return;
  6401. }
  6402. const indices = index.array;
  6403. const positions = attributes.position.array;
  6404. const normals = attributes.normal.array;
  6405. const uvs = attributes.uv.array;
  6406. const nVertices = positions.length / 3;
  6407. if (this.hasAttribute('tangent') === false) {
  6408. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6409. }
  6410. const tangents = this.getAttribute('tangent').array;
  6411. const tan1 = [],
  6412. tan2 = [];
  6413. for (let i = 0; i < nVertices; i++) {
  6414. tan1[i] = new Vector3();
  6415. tan2[i] = new Vector3();
  6416. }
  6417. const vA = new Vector3(),
  6418. vB = new Vector3(),
  6419. vC = new Vector3(),
  6420. uvA = new Vector2(),
  6421. uvB = new Vector2(),
  6422. uvC = new Vector2(),
  6423. sdir = new Vector3(),
  6424. tdir = new Vector3();
  6425. function handleTriangle(a, b, c) {
  6426. vA.fromArray(positions, a * 3);
  6427. vB.fromArray(positions, b * 3);
  6428. vC.fromArray(positions, c * 3);
  6429. uvA.fromArray(uvs, a * 2);
  6430. uvB.fromArray(uvs, b * 2);
  6431. uvC.fromArray(uvs, c * 2);
  6432. vB.sub(vA);
  6433. vC.sub(vA);
  6434. uvB.sub(uvA);
  6435. uvC.sub(uvA);
  6436. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6437. if (!isFinite(r)) return;
  6438. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6439. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6440. tan1[a].add(sdir);
  6441. tan1[b].add(sdir);
  6442. tan1[c].add(sdir);
  6443. tan2[a].add(tdir);
  6444. tan2[b].add(tdir);
  6445. tan2[c].add(tdir);
  6446. }
  6447. let groups = this.groups;
  6448. if (groups.length === 0) {
  6449. groups = [{
  6450. start: 0,
  6451. count: indices.length
  6452. }];
  6453. }
  6454. for (let i = 0, il = groups.length; i < il; ++i) {
  6455. const group = groups[i];
  6456. const start = group.start;
  6457. const count = group.count;
  6458. for (let j = start, jl = start + count; j < jl; j += 3) {
  6459. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6460. }
  6461. }
  6462. const tmp = new Vector3(),
  6463. tmp2 = new Vector3();
  6464. const n = new Vector3(),
  6465. n2 = new Vector3();
  6466. function handleVertex(v) {
  6467. n.fromArray(normals, v * 3);
  6468. n2.copy(n);
  6469. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6470. tmp.copy(t);
  6471. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6472. tmp2.crossVectors(n2, t);
  6473. const test = tmp2.dot(tan2[v]);
  6474. const w = test < 0.0 ? -1.0 : 1.0;
  6475. tangents[v * 4] = tmp.x;
  6476. tangents[v * 4 + 1] = tmp.y;
  6477. tangents[v * 4 + 2] = tmp.z;
  6478. tangents[v * 4 + 3] = w;
  6479. }
  6480. for (let i = 0, il = groups.length; i < il; ++i) {
  6481. const group = groups[i];
  6482. const start = group.start;
  6483. const count = group.count;
  6484. for (let j = start, jl = start + count; j < jl; j += 3) {
  6485. handleVertex(indices[j + 0]);
  6486. handleVertex(indices[j + 1]);
  6487. handleVertex(indices[j + 2]);
  6488. }
  6489. }
  6490. }
  6491. computeVertexNormals() {
  6492. const index = this.index;
  6493. const positionAttribute = this.getAttribute('position');
  6494. if (positionAttribute !== undefined) {
  6495. let normalAttribute = this.getAttribute('normal');
  6496. if (normalAttribute === undefined) {
  6497. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6498. this.setAttribute('normal', normalAttribute);
  6499. } else {
  6500. // reset existing normals to zero
  6501. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6502. normalAttribute.setXYZ(i, 0, 0, 0);
  6503. }
  6504. }
  6505. const pA = new Vector3(),
  6506. pB = new Vector3(),
  6507. pC = new Vector3();
  6508. const nA = new Vector3(),
  6509. nB = new Vector3(),
  6510. nC = new Vector3();
  6511. const cb = new Vector3(),
  6512. ab = new Vector3(); // indexed elements
  6513. if (index) {
  6514. for (let i = 0, il = index.count; i < il; i += 3) {
  6515. const vA = index.getX(i + 0);
  6516. const vB = index.getX(i + 1);
  6517. const vC = index.getX(i + 2);
  6518. pA.fromBufferAttribute(positionAttribute, vA);
  6519. pB.fromBufferAttribute(positionAttribute, vB);
  6520. pC.fromBufferAttribute(positionAttribute, vC);
  6521. cb.subVectors(pC, pB);
  6522. ab.subVectors(pA, pB);
  6523. cb.cross(ab);
  6524. nA.fromBufferAttribute(normalAttribute, vA);
  6525. nB.fromBufferAttribute(normalAttribute, vB);
  6526. nC.fromBufferAttribute(normalAttribute, vC);
  6527. nA.add(cb);
  6528. nB.add(cb);
  6529. nC.add(cb);
  6530. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6531. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6532. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6533. }
  6534. } else {
  6535. // non-indexed elements (unconnected triangle soup)
  6536. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6537. pA.fromBufferAttribute(positionAttribute, i + 0);
  6538. pB.fromBufferAttribute(positionAttribute, i + 1);
  6539. pC.fromBufferAttribute(positionAttribute, i + 2);
  6540. cb.subVectors(pC, pB);
  6541. ab.subVectors(pA, pB);
  6542. cb.cross(ab);
  6543. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6544. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6545. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6546. }
  6547. }
  6548. this.normalizeNormals();
  6549. normalAttribute.needsUpdate = true;
  6550. }
  6551. } // @deprecated since r144
  6552. merge() {
  6553. console.error('THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.');
  6554. return this;
  6555. }
  6556. normalizeNormals() {
  6557. const normals = this.attributes.normal;
  6558. for (let i = 0, il = normals.count; i < il; i++) {
  6559. _vector$8.fromBufferAttribute(normals, i);
  6560. _vector$8.normalize();
  6561. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6562. }
  6563. }
  6564. toNonIndexed() {
  6565. function convertBufferAttribute(attribute, indices) {
  6566. const array = attribute.array;
  6567. const itemSize = attribute.itemSize;
  6568. const normalized = attribute.normalized;
  6569. const array2 = new array.constructor(indices.length * itemSize);
  6570. let index = 0,
  6571. index2 = 0;
  6572. for (let i = 0, l = indices.length; i < l; i++) {
  6573. if (attribute.isInterleavedBufferAttribute) {
  6574. index = indices[i] * attribute.data.stride + attribute.offset;
  6575. } else {
  6576. index = indices[i] * itemSize;
  6577. }
  6578. for (let j = 0; j < itemSize; j++) {
  6579. array2[index2++] = array[index++];
  6580. }
  6581. }
  6582. return new BufferAttribute(array2, itemSize, normalized);
  6583. } //
  6584. if (this.index === null) {
  6585. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6586. return this;
  6587. }
  6588. const geometry2 = new BufferGeometry();
  6589. const indices = this.index.array;
  6590. const attributes = this.attributes; // attributes
  6591. for (const name in attributes) {
  6592. const attribute = attributes[name];
  6593. const newAttribute = convertBufferAttribute(attribute, indices);
  6594. geometry2.setAttribute(name, newAttribute);
  6595. } // morph attributes
  6596. const morphAttributes = this.morphAttributes;
  6597. for (const name in morphAttributes) {
  6598. const morphArray = [];
  6599. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6600. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6601. const attribute = morphAttribute[i];
  6602. const newAttribute = convertBufferAttribute(attribute, indices);
  6603. morphArray.push(newAttribute);
  6604. }
  6605. geometry2.morphAttributes[name] = morphArray;
  6606. }
  6607. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6608. const groups = this.groups;
  6609. for (let i = 0, l = groups.length; i < l; i++) {
  6610. const group = groups[i];
  6611. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6612. }
  6613. return geometry2;
  6614. }
  6615. toJSON() {
  6616. const data = {
  6617. metadata: {
  6618. version: 4.5,
  6619. type: 'BufferGeometry',
  6620. generator: 'BufferGeometry.toJSON'
  6621. }
  6622. }; // standard BufferGeometry serialization
  6623. data.uuid = this.uuid;
  6624. data.type = this.type;
  6625. if (this.name !== '') data.name = this.name;
  6626. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6627. if (this.parameters !== undefined) {
  6628. const parameters = this.parameters;
  6629. for (const key in parameters) {
  6630. if (parameters[key] !== undefined) data[key] = parameters[key];
  6631. }
  6632. return data;
  6633. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6634. data.data = {
  6635. attributes: {}
  6636. };
  6637. const index = this.index;
  6638. if (index !== null) {
  6639. data.data.index = {
  6640. type: index.array.constructor.name,
  6641. array: Array.prototype.slice.call(index.array)
  6642. };
  6643. }
  6644. const attributes = this.attributes;
  6645. for (const key in attributes) {
  6646. const attribute = attributes[key];
  6647. data.data.attributes[key] = attribute.toJSON(data.data);
  6648. }
  6649. const morphAttributes = {};
  6650. let hasMorphAttributes = false;
  6651. for (const key in this.morphAttributes) {
  6652. const attributeArray = this.morphAttributes[key];
  6653. const array = [];
  6654. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6655. const attribute = attributeArray[i];
  6656. array.push(attribute.toJSON(data.data));
  6657. }
  6658. if (array.length > 0) {
  6659. morphAttributes[key] = array;
  6660. hasMorphAttributes = true;
  6661. }
  6662. }
  6663. if (hasMorphAttributes) {
  6664. data.data.morphAttributes = morphAttributes;
  6665. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6666. }
  6667. const groups = this.groups;
  6668. if (groups.length > 0) {
  6669. data.data.groups = JSON.parse(JSON.stringify(groups));
  6670. }
  6671. const boundingSphere = this.boundingSphere;
  6672. if (boundingSphere !== null) {
  6673. data.data.boundingSphere = {
  6674. center: boundingSphere.center.toArray(),
  6675. radius: boundingSphere.radius
  6676. };
  6677. }
  6678. return data;
  6679. }
  6680. clone() {
  6681. return new this.constructor().copy(this);
  6682. }
  6683. copy(source) {
  6684. // reset
  6685. this.index = null;
  6686. this.attributes = {};
  6687. this.morphAttributes = {};
  6688. this.groups = [];
  6689. this.boundingBox = null;
  6690. this.boundingSphere = null; // used for storing cloned, shared data
  6691. const data = {}; // name
  6692. this.name = source.name; // index
  6693. const index = source.index;
  6694. if (index !== null) {
  6695. this.setIndex(index.clone(data));
  6696. } // attributes
  6697. const attributes = source.attributes;
  6698. for (const name in attributes) {
  6699. const attribute = attributes[name];
  6700. this.setAttribute(name, attribute.clone(data));
  6701. } // morph attributes
  6702. const morphAttributes = source.morphAttributes;
  6703. for (const name in morphAttributes) {
  6704. const array = [];
  6705. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6706. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6707. array.push(morphAttribute[i].clone(data));
  6708. }
  6709. this.morphAttributes[name] = array;
  6710. }
  6711. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6712. const groups = source.groups;
  6713. for (let i = 0, l = groups.length; i < l; i++) {
  6714. const group = groups[i];
  6715. this.addGroup(group.start, group.count, group.materialIndex);
  6716. } // bounding box
  6717. const boundingBox = source.boundingBox;
  6718. if (boundingBox !== null) {
  6719. this.boundingBox = boundingBox.clone();
  6720. } // bounding sphere
  6721. const boundingSphere = source.boundingSphere;
  6722. if (boundingSphere !== null) {
  6723. this.boundingSphere = boundingSphere.clone();
  6724. } // draw range
  6725. this.drawRange.start = source.drawRange.start;
  6726. this.drawRange.count = source.drawRange.count; // user data
  6727. this.userData = source.userData; // geometry generator parameters
  6728. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6729. return this;
  6730. }
  6731. dispose() {
  6732. this.dispatchEvent({
  6733. type: 'dispose'
  6734. });
  6735. }
  6736. }
  6737. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6738. const _ray$2 = /*@__PURE__*/new Ray();
  6739. const _sphere$3 = /*@__PURE__*/new Sphere();
  6740. const _vA$1 = /*@__PURE__*/new Vector3();
  6741. const _vB$1 = /*@__PURE__*/new Vector3();
  6742. const _vC$1 = /*@__PURE__*/new Vector3();
  6743. const _tempA = /*@__PURE__*/new Vector3();
  6744. const _tempB = /*@__PURE__*/new Vector3();
  6745. const _tempC = /*@__PURE__*/new Vector3();
  6746. const _morphA = /*@__PURE__*/new Vector3();
  6747. const _morphB = /*@__PURE__*/new Vector3();
  6748. const _morphC = /*@__PURE__*/new Vector3();
  6749. const _uvA$1 = /*@__PURE__*/new Vector2();
  6750. const _uvB$1 = /*@__PURE__*/new Vector2();
  6751. const _uvC$1 = /*@__PURE__*/new Vector2();
  6752. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6753. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6754. class Mesh extends Object3D {
  6755. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6756. super();
  6757. this.isMesh = true;
  6758. this.type = 'Mesh';
  6759. this.geometry = geometry;
  6760. this.material = material;
  6761. this.updateMorphTargets();
  6762. }
  6763. copy(source, recursive) {
  6764. super.copy(source, recursive);
  6765. if (source.morphTargetInfluences !== undefined) {
  6766. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6767. }
  6768. if (source.morphTargetDictionary !== undefined) {
  6769. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6770. }
  6771. this.material = source.material;
  6772. this.geometry = source.geometry;
  6773. return this;
  6774. }
  6775. updateMorphTargets() {
  6776. const geometry = this.geometry;
  6777. const morphAttributes = geometry.morphAttributes;
  6778. const keys = Object.keys(morphAttributes);
  6779. if (keys.length > 0) {
  6780. const morphAttribute = morphAttributes[keys[0]];
  6781. if (morphAttribute !== undefined) {
  6782. this.morphTargetInfluences = [];
  6783. this.morphTargetDictionary = {};
  6784. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6785. const name = morphAttribute[m].name || String(m);
  6786. this.morphTargetInfluences.push(0);
  6787. this.morphTargetDictionary[name] = m;
  6788. }
  6789. }
  6790. }
  6791. }
  6792. raycast(raycaster, intersects) {
  6793. const geometry = this.geometry;
  6794. const material = this.material;
  6795. const matrixWorld = this.matrixWorld;
  6796. if (material === undefined) return; // Checking boundingSphere distance to ray
  6797. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6798. _sphere$3.copy(geometry.boundingSphere);
  6799. _sphere$3.applyMatrix4(matrixWorld);
  6800. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6801. _inverseMatrix$2.copy(matrixWorld).invert();
  6802. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6803. if (geometry.boundingBox !== null) {
  6804. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6805. }
  6806. let intersection;
  6807. const index = geometry.index;
  6808. const position = geometry.attributes.position;
  6809. const morphPosition = geometry.morphAttributes.position;
  6810. const morphTargetsRelative = geometry.morphTargetsRelative;
  6811. const uv = geometry.attributes.uv;
  6812. const uv2 = geometry.attributes.uv2;
  6813. const groups = geometry.groups;
  6814. const drawRange = geometry.drawRange;
  6815. if (index !== null) {
  6816. // indexed buffer geometry
  6817. if (Array.isArray(material)) {
  6818. for (let i = 0, il = groups.length; i < il; i++) {
  6819. const group = groups[i];
  6820. const groupMaterial = material[group.materialIndex];
  6821. const start = Math.max(group.start, drawRange.start);
  6822. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6823. for (let j = start, jl = end; j < jl; j += 3) {
  6824. const a = index.getX(j);
  6825. const b = index.getX(j + 1);
  6826. const c = index.getX(j + 2);
  6827. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6828. if (intersection) {
  6829. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6830. intersection.face.materialIndex = group.materialIndex;
  6831. intersects.push(intersection);
  6832. }
  6833. }
  6834. }
  6835. } else {
  6836. const start = Math.max(0, drawRange.start);
  6837. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6838. for (let i = start, il = end; i < il; i += 3) {
  6839. const a = index.getX(i);
  6840. const b = index.getX(i + 1);
  6841. const c = index.getX(i + 2);
  6842. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6843. if (intersection) {
  6844. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6845. intersects.push(intersection);
  6846. }
  6847. }
  6848. }
  6849. } else if (position !== undefined) {
  6850. // non-indexed buffer geometry
  6851. if (Array.isArray(material)) {
  6852. for (let i = 0, il = groups.length; i < il; i++) {
  6853. const group = groups[i];
  6854. const groupMaterial = material[group.materialIndex];
  6855. const start = Math.max(group.start, drawRange.start);
  6856. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6857. for (let j = start, jl = end; j < jl; j += 3) {
  6858. const a = j;
  6859. const b = j + 1;
  6860. const c = j + 2;
  6861. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6862. if (intersection) {
  6863. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6864. intersection.face.materialIndex = group.materialIndex;
  6865. intersects.push(intersection);
  6866. }
  6867. }
  6868. }
  6869. } else {
  6870. const start = Math.max(0, drawRange.start);
  6871. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6872. for (let i = start, il = end; i < il; i += 3) {
  6873. const a = i;
  6874. const b = i + 1;
  6875. const c = i + 2;
  6876. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6877. if (intersection) {
  6878. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6879. intersects.push(intersection);
  6880. }
  6881. }
  6882. }
  6883. }
  6884. }
  6885. }
  6886. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6887. let intersect;
  6888. if (material.side === BackSide) {
  6889. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6890. } else {
  6891. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6892. }
  6893. if (intersect === null) return null;
  6894. _intersectionPointWorld.copy(point);
  6895. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6896. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6897. if (distance < raycaster.near || distance > raycaster.far) return null;
  6898. return {
  6899. distance: distance,
  6900. point: _intersectionPointWorld.clone(),
  6901. object: object
  6902. };
  6903. }
  6904. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6905. _vA$1.fromBufferAttribute(position, a);
  6906. _vB$1.fromBufferAttribute(position, b);
  6907. _vC$1.fromBufferAttribute(position, c);
  6908. const morphInfluences = object.morphTargetInfluences;
  6909. if (morphPosition && morphInfluences) {
  6910. _morphA.set(0, 0, 0);
  6911. _morphB.set(0, 0, 0);
  6912. _morphC.set(0, 0, 0);
  6913. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6914. const influence = morphInfluences[i];
  6915. const morphAttribute = morphPosition[i];
  6916. if (influence === 0) continue;
  6917. _tempA.fromBufferAttribute(morphAttribute, a);
  6918. _tempB.fromBufferAttribute(morphAttribute, b);
  6919. _tempC.fromBufferAttribute(morphAttribute, c);
  6920. if (morphTargetsRelative) {
  6921. _morphA.addScaledVector(_tempA, influence);
  6922. _morphB.addScaledVector(_tempB, influence);
  6923. _morphC.addScaledVector(_tempC, influence);
  6924. } else {
  6925. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6926. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6927. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6928. }
  6929. }
  6930. _vA$1.add(_morphA);
  6931. _vB$1.add(_morphB);
  6932. _vC$1.add(_morphC);
  6933. }
  6934. if (object.isSkinnedMesh) {
  6935. object.boneTransform(a, _vA$1);
  6936. object.boneTransform(b, _vB$1);
  6937. object.boneTransform(c, _vC$1);
  6938. }
  6939. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6940. if (intersection) {
  6941. if (uv) {
  6942. _uvA$1.fromBufferAttribute(uv, a);
  6943. _uvB$1.fromBufferAttribute(uv, b);
  6944. _uvC$1.fromBufferAttribute(uv, c);
  6945. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6946. }
  6947. if (uv2) {
  6948. _uvA$1.fromBufferAttribute(uv2, a);
  6949. _uvB$1.fromBufferAttribute(uv2, b);
  6950. _uvC$1.fromBufferAttribute(uv2, c);
  6951. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6952. }
  6953. const face = {
  6954. a: a,
  6955. b: b,
  6956. c: c,
  6957. normal: new Vector3(),
  6958. materialIndex: 0
  6959. };
  6960. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6961. intersection.face = face;
  6962. }
  6963. return intersection;
  6964. }
  6965. class BoxGeometry extends BufferGeometry {
  6966. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6967. super();
  6968. this.type = 'BoxGeometry';
  6969. this.parameters = {
  6970. width: width,
  6971. height: height,
  6972. depth: depth,
  6973. widthSegments: widthSegments,
  6974. heightSegments: heightSegments,
  6975. depthSegments: depthSegments
  6976. };
  6977. const scope = this; // segments
  6978. widthSegments = Math.floor(widthSegments);
  6979. heightSegments = Math.floor(heightSegments);
  6980. depthSegments = Math.floor(depthSegments); // buffers
  6981. const indices = [];
  6982. const vertices = [];
  6983. const normals = [];
  6984. const uvs = []; // helper variables
  6985. let numberOfVertices = 0;
  6986. let groupStart = 0; // build each side of the box geometry
  6987. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6988. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6989. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6990. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6991. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6992. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6993. // build geometry
  6994. this.setIndex(indices);
  6995. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6996. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6997. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6998. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6999. const segmentWidth = width / gridX;
  7000. const segmentHeight = height / gridY;
  7001. const widthHalf = width / 2;
  7002. const heightHalf = height / 2;
  7003. const depthHalf = depth / 2;
  7004. const gridX1 = gridX + 1;
  7005. const gridY1 = gridY + 1;
  7006. let vertexCounter = 0;
  7007. let groupCount = 0;
  7008. const vector = new Vector3(); // generate vertices, normals and uvs
  7009. for (let iy = 0; iy < gridY1; iy++) {
  7010. const y = iy * segmentHeight - heightHalf;
  7011. for (let ix = 0; ix < gridX1; ix++) {
  7012. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7013. vector[u] = x * udir;
  7014. vector[v] = y * vdir;
  7015. vector[w] = depthHalf; // now apply vector to vertex buffer
  7016. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7017. vector[u] = 0;
  7018. vector[v] = 0;
  7019. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7020. normals.push(vector.x, vector.y, vector.z); // uvs
  7021. uvs.push(ix / gridX);
  7022. uvs.push(1 - iy / gridY); // counters
  7023. vertexCounter += 1;
  7024. }
  7025. } // indices
  7026. // 1. you need three indices to draw a single face
  7027. // 2. a single segment consists of two faces
  7028. // 3. so we need to generate six (2*3) indices per segment
  7029. for (let iy = 0; iy < gridY; iy++) {
  7030. for (let ix = 0; ix < gridX; ix++) {
  7031. const a = numberOfVertices + ix + gridX1 * iy;
  7032. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7033. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7034. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7035. indices.push(a, b, d);
  7036. indices.push(b, c, d); // increase counter
  7037. groupCount += 6;
  7038. }
  7039. } // add a group to the geometry. this will ensure multi material support
  7040. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7041. groupStart += groupCount; // update total number of vertices
  7042. numberOfVertices += vertexCounter;
  7043. }
  7044. }
  7045. static fromJSON(data) {
  7046. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  7047. }
  7048. }
  7049. /**
  7050. * Uniform Utilities
  7051. */
  7052. function cloneUniforms(src) {
  7053. const dst = {};
  7054. for (const u in src) {
  7055. dst[u] = {};
  7056. for (const p in src[u]) {
  7057. const property = src[u][p];
  7058. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7059. dst[u][p] = property.clone();
  7060. } else if (Array.isArray(property)) {
  7061. dst[u][p] = property.slice();
  7062. } else {
  7063. dst[u][p] = property;
  7064. }
  7065. }
  7066. }
  7067. return dst;
  7068. }
  7069. function mergeUniforms(uniforms) {
  7070. const merged = {};
  7071. for (let u = 0; u < uniforms.length; u++) {
  7072. const tmp = cloneUniforms(uniforms[u]);
  7073. for (const p in tmp) {
  7074. merged[p] = tmp[p];
  7075. }
  7076. }
  7077. return merged;
  7078. }
  7079. function cloneUniformsGroups(src) {
  7080. const dst = [];
  7081. for (let u = 0; u < src.length; u++) {
  7082. dst.push(src[u].clone());
  7083. }
  7084. return dst;
  7085. } // Legacy
  7086. const UniformsUtils = {
  7087. clone: cloneUniforms,
  7088. merge: mergeUniforms
  7089. };
  7090. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7091. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7092. class ShaderMaterial extends Material {
  7093. constructor(parameters) {
  7094. super();
  7095. this.isShaderMaterial = true;
  7096. this.type = 'ShaderMaterial';
  7097. this.defines = {};
  7098. this.uniforms = {};
  7099. this.uniformsGroups = [];
  7100. this.vertexShader = default_vertex;
  7101. this.fragmentShader = default_fragment;
  7102. this.linewidth = 1;
  7103. this.wireframe = false;
  7104. this.wireframeLinewidth = 1;
  7105. this.fog = false; // set to use scene fog
  7106. this.lights = false; // set to use scene lights
  7107. this.clipping = false; // set to use user-defined clipping planes
  7108. this.extensions = {
  7109. derivatives: false,
  7110. // set to use derivatives
  7111. fragDepth: false,
  7112. // set to use fragment depth values
  7113. drawBuffers: false,
  7114. // set to use draw buffers
  7115. shaderTextureLOD: false // set to use shader texture LOD
  7116. }; // When rendered geometry doesn't include these attributes but the material does,
  7117. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7118. this.defaultAttributeValues = {
  7119. 'color': [1, 1, 1],
  7120. 'uv': [0, 0],
  7121. 'uv2': [0, 0]
  7122. };
  7123. this.index0AttributeName = undefined;
  7124. this.uniformsNeedUpdate = false;
  7125. this.glslVersion = null;
  7126. if (parameters !== undefined) {
  7127. this.setValues(parameters);
  7128. }
  7129. }
  7130. copy(source) {
  7131. super.copy(source);
  7132. this.fragmentShader = source.fragmentShader;
  7133. this.vertexShader = source.vertexShader;
  7134. this.uniforms = cloneUniforms(source.uniforms);
  7135. this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups);
  7136. this.defines = Object.assign({}, source.defines);
  7137. this.wireframe = source.wireframe;
  7138. this.wireframeLinewidth = source.wireframeLinewidth;
  7139. this.fog = source.fog;
  7140. this.lights = source.lights;
  7141. this.clipping = source.clipping;
  7142. this.extensions = Object.assign({}, source.extensions);
  7143. this.glslVersion = source.glslVersion;
  7144. return this;
  7145. }
  7146. toJSON(meta) {
  7147. const data = super.toJSON(meta);
  7148. data.glslVersion = this.glslVersion;
  7149. data.uniforms = {};
  7150. for (const name in this.uniforms) {
  7151. const uniform = this.uniforms[name];
  7152. const value = uniform.value;
  7153. if (value && value.isTexture) {
  7154. data.uniforms[name] = {
  7155. type: 't',
  7156. value: value.toJSON(meta).uuid
  7157. };
  7158. } else if (value && value.isColor) {
  7159. data.uniforms[name] = {
  7160. type: 'c',
  7161. value: value.getHex()
  7162. };
  7163. } else if (value && value.isVector2) {
  7164. data.uniforms[name] = {
  7165. type: 'v2',
  7166. value: value.toArray()
  7167. };
  7168. } else if (value && value.isVector3) {
  7169. data.uniforms[name] = {
  7170. type: 'v3',
  7171. value: value.toArray()
  7172. };
  7173. } else if (value && value.isVector4) {
  7174. data.uniforms[name] = {
  7175. type: 'v4',
  7176. value: value.toArray()
  7177. };
  7178. } else if (value && value.isMatrix3) {
  7179. data.uniforms[name] = {
  7180. type: 'm3',
  7181. value: value.toArray()
  7182. };
  7183. } else if (value && value.isMatrix4) {
  7184. data.uniforms[name] = {
  7185. type: 'm4',
  7186. value: value.toArray()
  7187. };
  7188. } else {
  7189. data.uniforms[name] = {
  7190. value: value
  7191. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7192. }
  7193. }
  7194. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7195. data.vertexShader = this.vertexShader;
  7196. data.fragmentShader = this.fragmentShader;
  7197. const extensions = {};
  7198. for (const key in this.extensions) {
  7199. if (this.extensions[key] === true) extensions[key] = true;
  7200. }
  7201. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7202. return data;
  7203. }
  7204. }
  7205. class Camera extends Object3D {
  7206. constructor() {
  7207. super();
  7208. this.isCamera = true;
  7209. this.type = 'Camera';
  7210. this.matrixWorldInverse = new Matrix4();
  7211. this.projectionMatrix = new Matrix4();
  7212. this.projectionMatrixInverse = new Matrix4();
  7213. }
  7214. copy(source, recursive) {
  7215. super.copy(source, recursive);
  7216. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7217. this.projectionMatrix.copy(source.projectionMatrix);
  7218. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7219. return this;
  7220. }
  7221. getWorldDirection(target) {
  7222. this.updateWorldMatrix(true, false);
  7223. const e = this.matrixWorld.elements;
  7224. return target.set(-e[8], -e[9], -e[10]).normalize();
  7225. }
  7226. updateMatrixWorld(force) {
  7227. super.updateMatrixWorld(force);
  7228. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7229. }
  7230. updateWorldMatrix(updateParents, updateChildren) {
  7231. super.updateWorldMatrix(updateParents, updateChildren);
  7232. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7233. }
  7234. clone() {
  7235. return new this.constructor().copy(this);
  7236. }
  7237. }
  7238. class PerspectiveCamera extends Camera {
  7239. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7240. super();
  7241. this.isPerspectiveCamera = true;
  7242. this.type = 'PerspectiveCamera';
  7243. this.fov = fov;
  7244. this.zoom = 1;
  7245. this.near = near;
  7246. this.far = far;
  7247. this.focus = 10;
  7248. this.aspect = aspect;
  7249. this.view = null;
  7250. this.filmGauge = 35; // width of the film (default in millimeters)
  7251. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7252. this.updateProjectionMatrix();
  7253. }
  7254. copy(source, recursive) {
  7255. super.copy(source, recursive);
  7256. this.fov = source.fov;
  7257. this.zoom = source.zoom;
  7258. this.near = source.near;
  7259. this.far = source.far;
  7260. this.focus = source.focus;
  7261. this.aspect = source.aspect;
  7262. this.view = source.view === null ? null : Object.assign({}, source.view);
  7263. this.filmGauge = source.filmGauge;
  7264. this.filmOffset = source.filmOffset;
  7265. return this;
  7266. }
  7267. /**
  7268. * Sets the FOV by focal length in respect to the current .filmGauge.
  7269. *
  7270. * The default film gauge is 35, so that the focal length can be specified for
  7271. * a 35mm (full frame) camera.
  7272. *
  7273. * Values for focal length and film gauge must have the same unit.
  7274. */
  7275. setFocalLength(focalLength) {
  7276. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7277. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7278. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7279. this.updateProjectionMatrix();
  7280. }
  7281. /**
  7282. * Calculates the focal length from the current .fov and .filmGauge.
  7283. */
  7284. getFocalLength() {
  7285. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7286. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7287. }
  7288. getEffectiveFOV() {
  7289. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7290. }
  7291. getFilmWidth() {
  7292. // film not completely covered in portrait format (aspect < 1)
  7293. return this.filmGauge * Math.min(this.aspect, 1);
  7294. }
  7295. getFilmHeight() {
  7296. // film not completely covered in landscape format (aspect > 1)
  7297. return this.filmGauge / Math.max(this.aspect, 1);
  7298. }
  7299. /**
  7300. * Sets an offset in a larger frustum. This is useful for multi-window or
  7301. * multi-monitor/multi-machine setups.
  7302. *
  7303. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7304. * the monitors are in grid like this
  7305. *
  7306. * +---+---+---+
  7307. * | A | B | C |
  7308. * +---+---+---+
  7309. * | D | E | F |
  7310. * +---+---+---+
  7311. *
  7312. * then for each monitor you would call it like this
  7313. *
  7314. * const w = 1920;
  7315. * const h = 1080;
  7316. * const fullWidth = w * 3;
  7317. * const fullHeight = h * 2;
  7318. *
  7319. * --A--
  7320. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7321. * --B--
  7322. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7323. * --C--
  7324. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7325. * --D--
  7326. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7327. * --E--
  7328. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7329. * --F--
  7330. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7331. *
  7332. * Note there is no reason monitors have to be the same size or in a grid.
  7333. */
  7334. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7335. this.aspect = fullWidth / fullHeight;
  7336. if (this.view === null) {
  7337. this.view = {
  7338. enabled: true,
  7339. fullWidth: 1,
  7340. fullHeight: 1,
  7341. offsetX: 0,
  7342. offsetY: 0,
  7343. width: 1,
  7344. height: 1
  7345. };
  7346. }
  7347. this.view.enabled = true;
  7348. this.view.fullWidth = fullWidth;
  7349. this.view.fullHeight = fullHeight;
  7350. this.view.offsetX = x;
  7351. this.view.offsetY = y;
  7352. this.view.width = width;
  7353. this.view.height = height;
  7354. this.updateProjectionMatrix();
  7355. }
  7356. clearViewOffset() {
  7357. if (this.view !== null) {
  7358. this.view.enabled = false;
  7359. }
  7360. this.updateProjectionMatrix();
  7361. }
  7362. updateProjectionMatrix() {
  7363. const near = this.near;
  7364. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7365. let height = 2 * top;
  7366. let width = this.aspect * height;
  7367. let left = -0.5 * width;
  7368. const view = this.view;
  7369. if (this.view !== null && this.view.enabled) {
  7370. const fullWidth = view.fullWidth,
  7371. fullHeight = view.fullHeight;
  7372. left += view.offsetX * width / fullWidth;
  7373. top -= view.offsetY * height / fullHeight;
  7374. width *= view.width / fullWidth;
  7375. height *= view.height / fullHeight;
  7376. }
  7377. const skew = this.filmOffset;
  7378. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7379. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7380. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7381. }
  7382. toJSON(meta) {
  7383. const data = super.toJSON(meta);
  7384. data.object.fov = this.fov;
  7385. data.object.zoom = this.zoom;
  7386. data.object.near = this.near;
  7387. data.object.far = this.far;
  7388. data.object.focus = this.focus;
  7389. data.object.aspect = this.aspect;
  7390. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7391. data.object.filmGauge = this.filmGauge;
  7392. data.object.filmOffset = this.filmOffset;
  7393. return data;
  7394. }
  7395. }
  7396. const fov = 90,
  7397. aspect = 1;
  7398. class CubeCamera extends Object3D {
  7399. constructor(near, far, renderTarget) {
  7400. super();
  7401. this.type = 'CubeCamera';
  7402. this.renderTarget = renderTarget;
  7403. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7404. cameraPX.layers = this.layers;
  7405. cameraPX.up.set(0, -1, 0);
  7406. cameraPX.lookAt(new Vector3(1, 0, 0));
  7407. this.add(cameraPX);
  7408. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7409. cameraNX.layers = this.layers;
  7410. cameraNX.up.set(0, -1, 0);
  7411. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7412. this.add(cameraNX);
  7413. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7414. cameraPY.layers = this.layers;
  7415. cameraPY.up.set(0, 0, 1);
  7416. cameraPY.lookAt(new Vector3(0, 1, 0));
  7417. this.add(cameraPY);
  7418. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7419. cameraNY.layers = this.layers;
  7420. cameraNY.up.set(0, 0, -1);
  7421. cameraNY.lookAt(new Vector3(0, -1, 0));
  7422. this.add(cameraNY);
  7423. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7424. cameraPZ.layers = this.layers;
  7425. cameraPZ.up.set(0, -1, 0);
  7426. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7427. this.add(cameraPZ);
  7428. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7429. cameraNZ.layers = this.layers;
  7430. cameraNZ.up.set(0, -1, 0);
  7431. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7432. this.add(cameraNZ);
  7433. }
  7434. update(renderer, scene) {
  7435. if (this.parent === null) this.updateMatrixWorld();
  7436. const renderTarget = this.renderTarget;
  7437. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7438. const currentRenderTarget = renderer.getRenderTarget();
  7439. const currentToneMapping = renderer.toneMapping;
  7440. const currentXrEnabled = renderer.xr.enabled;
  7441. renderer.toneMapping = NoToneMapping;
  7442. renderer.xr.enabled = false;
  7443. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7444. renderTarget.texture.generateMipmaps = false;
  7445. renderer.setRenderTarget(renderTarget, 0);
  7446. renderer.render(scene, cameraPX);
  7447. renderer.setRenderTarget(renderTarget, 1);
  7448. renderer.render(scene, cameraNX);
  7449. renderer.setRenderTarget(renderTarget, 2);
  7450. renderer.render(scene, cameraPY);
  7451. renderer.setRenderTarget(renderTarget, 3);
  7452. renderer.render(scene, cameraNY);
  7453. renderer.setRenderTarget(renderTarget, 4);
  7454. renderer.render(scene, cameraPZ);
  7455. renderTarget.texture.generateMipmaps = generateMipmaps;
  7456. renderer.setRenderTarget(renderTarget, 5);
  7457. renderer.render(scene, cameraNZ);
  7458. renderer.setRenderTarget(currentRenderTarget);
  7459. renderer.toneMapping = currentToneMapping;
  7460. renderer.xr.enabled = currentXrEnabled;
  7461. renderTarget.texture.needsPMREMUpdate = true;
  7462. }
  7463. }
  7464. class CubeTexture extends Texture {
  7465. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7466. images = images !== undefined ? images : [];
  7467. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7468. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7469. this.isCubeTexture = true;
  7470. this.flipY = false;
  7471. }
  7472. get images() {
  7473. return this.image;
  7474. }
  7475. set images(value) {
  7476. this.image = value;
  7477. }
  7478. }
  7479. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7480. constructor(size, options = {}) {
  7481. super(size, size, options);
  7482. this.isWebGLCubeRenderTarget = true;
  7483. const image = {
  7484. width: size,
  7485. height: size,
  7486. depth: 1
  7487. };
  7488. const images = [image, image, image, image, image, image];
  7489. this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7490. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7491. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7492. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7493. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7494. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7495. this.texture.isRenderTargetTexture = true;
  7496. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7497. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7498. }
  7499. fromEquirectangularTexture(renderer, texture) {
  7500. this.texture.type = texture.type;
  7501. this.texture.encoding = texture.encoding;
  7502. this.texture.generateMipmaps = texture.generateMipmaps;
  7503. this.texture.minFilter = texture.minFilter;
  7504. this.texture.magFilter = texture.magFilter;
  7505. const shader = {
  7506. uniforms: {
  7507. tEquirect: {
  7508. value: null
  7509. }
  7510. },
  7511. vertexShader:
  7512. /* glsl */
  7513. `
  7514. varying vec3 vWorldDirection;
  7515. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7516. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7517. }
  7518. void main() {
  7519. vWorldDirection = transformDirection( position, modelMatrix );
  7520. #include <begin_vertex>
  7521. #include <project_vertex>
  7522. }
  7523. `,
  7524. fragmentShader:
  7525. /* glsl */
  7526. `
  7527. uniform sampler2D tEquirect;
  7528. varying vec3 vWorldDirection;
  7529. #include <common>
  7530. void main() {
  7531. vec3 direction = normalize( vWorldDirection );
  7532. vec2 sampleUV = equirectUv( direction );
  7533. gl_FragColor = texture2D( tEquirect, sampleUV );
  7534. }
  7535. `
  7536. };
  7537. const geometry = new BoxGeometry(5, 5, 5);
  7538. const material = new ShaderMaterial({
  7539. name: 'CubemapFromEquirect',
  7540. uniforms: cloneUniforms(shader.uniforms),
  7541. vertexShader: shader.vertexShader,
  7542. fragmentShader: shader.fragmentShader,
  7543. side: BackSide,
  7544. blending: NoBlending
  7545. });
  7546. material.uniforms.tEquirect.value = texture;
  7547. const mesh = new Mesh(geometry, material);
  7548. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7549. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7550. const camera = new CubeCamera(1, 10, this);
  7551. camera.update(renderer, mesh);
  7552. texture.minFilter = currentMinFilter;
  7553. mesh.geometry.dispose();
  7554. mesh.material.dispose();
  7555. return this;
  7556. }
  7557. clear(renderer, color, depth, stencil) {
  7558. const currentRenderTarget = renderer.getRenderTarget();
  7559. for (let i = 0; i < 6; i++) {
  7560. renderer.setRenderTarget(this, i);
  7561. renderer.clear(color, depth, stencil);
  7562. }
  7563. renderer.setRenderTarget(currentRenderTarget);
  7564. }
  7565. }
  7566. const _vector1 = /*@__PURE__*/new Vector3();
  7567. const _vector2 = /*@__PURE__*/new Vector3();
  7568. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7569. class Plane {
  7570. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7571. this.isPlane = true; // normal is assumed to be normalized
  7572. this.normal = normal;
  7573. this.constant = constant;
  7574. }
  7575. set(normal, constant) {
  7576. this.normal.copy(normal);
  7577. this.constant = constant;
  7578. return this;
  7579. }
  7580. setComponents(x, y, z, w) {
  7581. this.normal.set(x, y, z);
  7582. this.constant = w;
  7583. return this;
  7584. }
  7585. setFromNormalAndCoplanarPoint(normal, point) {
  7586. this.normal.copy(normal);
  7587. this.constant = -point.dot(this.normal);
  7588. return this;
  7589. }
  7590. setFromCoplanarPoints(a, b, c) {
  7591. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7592. this.setFromNormalAndCoplanarPoint(normal, a);
  7593. return this;
  7594. }
  7595. copy(plane) {
  7596. this.normal.copy(plane.normal);
  7597. this.constant = plane.constant;
  7598. return this;
  7599. }
  7600. normalize() {
  7601. // Note: will lead to a divide by zero if the plane is invalid.
  7602. const inverseNormalLength = 1.0 / this.normal.length();
  7603. this.normal.multiplyScalar(inverseNormalLength);
  7604. this.constant *= inverseNormalLength;
  7605. return this;
  7606. }
  7607. negate() {
  7608. this.constant *= -1;
  7609. this.normal.negate();
  7610. return this;
  7611. }
  7612. distanceToPoint(point) {
  7613. return this.normal.dot(point) + this.constant;
  7614. }
  7615. distanceToSphere(sphere) {
  7616. return this.distanceToPoint(sphere.center) - sphere.radius;
  7617. }
  7618. projectPoint(point, target) {
  7619. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7620. }
  7621. intersectLine(line, target) {
  7622. const direction = line.delta(_vector1);
  7623. const denominator = this.normal.dot(direction);
  7624. if (denominator === 0) {
  7625. // line is coplanar, return origin
  7626. if (this.distanceToPoint(line.start) === 0) {
  7627. return target.copy(line.start);
  7628. } // Unsure if this is the correct method to handle this case.
  7629. return null;
  7630. }
  7631. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7632. if (t < 0 || t > 1) {
  7633. return null;
  7634. }
  7635. return target.copy(direction).multiplyScalar(t).add(line.start);
  7636. }
  7637. intersectsLine(line) {
  7638. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7639. const startSign = this.distanceToPoint(line.start);
  7640. const endSign = this.distanceToPoint(line.end);
  7641. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7642. }
  7643. intersectsBox(box) {
  7644. return box.intersectsPlane(this);
  7645. }
  7646. intersectsSphere(sphere) {
  7647. return sphere.intersectsPlane(this);
  7648. }
  7649. coplanarPoint(target) {
  7650. return target.copy(this.normal).multiplyScalar(-this.constant);
  7651. }
  7652. applyMatrix4(matrix, optionalNormalMatrix) {
  7653. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7654. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7655. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7656. this.constant = -referencePoint.dot(normal);
  7657. return this;
  7658. }
  7659. translate(offset) {
  7660. this.constant -= offset.dot(this.normal);
  7661. return this;
  7662. }
  7663. equals(plane) {
  7664. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7665. }
  7666. clone() {
  7667. return new this.constructor().copy(this);
  7668. }
  7669. }
  7670. const _sphere$2 = /*@__PURE__*/new Sphere();
  7671. const _vector$7 = /*@__PURE__*/new Vector3();
  7672. class Frustum {
  7673. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7674. this.planes = [p0, p1, p2, p3, p4, p5];
  7675. }
  7676. set(p0, p1, p2, p3, p4, p5) {
  7677. const planes = this.planes;
  7678. planes[0].copy(p0);
  7679. planes[1].copy(p1);
  7680. planes[2].copy(p2);
  7681. planes[3].copy(p3);
  7682. planes[4].copy(p4);
  7683. planes[5].copy(p5);
  7684. return this;
  7685. }
  7686. copy(frustum) {
  7687. const planes = this.planes;
  7688. for (let i = 0; i < 6; i++) {
  7689. planes[i].copy(frustum.planes[i]);
  7690. }
  7691. return this;
  7692. }
  7693. setFromProjectionMatrix(m) {
  7694. const planes = this.planes;
  7695. const me = m.elements;
  7696. const me0 = me[0],
  7697. me1 = me[1],
  7698. me2 = me[2],
  7699. me3 = me[3];
  7700. const me4 = me[4],
  7701. me5 = me[5],
  7702. me6 = me[6],
  7703. me7 = me[7];
  7704. const me8 = me[8],
  7705. me9 = me[9],
  7706. me10 = me[10],
  7707. me11 = me[11];
  7708. const me12 = me[12],
  7709. me13 = me[13],
  7710. me14 = me[14],
  7711. me15 = me[15];
  7712. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7713. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7714. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7715. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7716. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7717. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7718. return this;
  7719. }
  7720. intersectsObject(object) {
  7721. const geometry = object.geometry;
  7722. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7723. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7724. return this.intersectsSphere(_sphere$2);
  7725. }
  7726. intersectsSprite(sprite) {
  7727. _sphere$2.center.set(0, 0, 0);
  7728. _sphere$2.radius = 0.7071067811865476;
  7729. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7730. return this.intersectsSphere(_sphere$2);
  7731. }
  7732. intersectsSphere(sphere) {
  7733. const planes = this.planes;
  7734. const center = sphere.center;
  7735. const negRadius = -sphere.radius;
  7736. for (let i = 0; i < 6; i++) {
  7737. const distance = planes[i].distanceToPoint(center);
  7738. if (distance < negRadius) {
  7739. return false;
  7740. }
  7741. }
  7742. return true;
  7743. }
  7744. intersectsBox(box) {
  7745. const planes = this.planes;
  7746. for (let i = 0; i < 6; i++) {
  7747. const plane = planes[i]; // corner at max distance
  7748. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7749. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7750. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7751. if (plane.distanceToPoint(_vector$7) < 0) {
  7752. return false;
  7753. }
  7754. }
  7755. return true;
  7756. }
  7757. containsPoint(point) {
  7758. const planes = this.planes;
  7759. for (let i = 0; i < 6; i++) {
  7760. if (planes[i].distanceToPoint(point) < 0) {
  7761. return false;
  7762. }
  7763. }
  7764. return true;
  7765. }
  7766. clone() {
  7767. return new this.constructor().copy(this);
  7768. }
  7769. }
  7770. function WebGLAnimation() {
  7771. let context = null;
  7772. let isAnimating = false;
  7773. let animationLoop = null;
  7774. let requestId = null;
  7775. function onAnimationFrame(time, frame) {
  7776. animationLoop(time, frame);
  7777. requestId = context.requestAnimationFrame(onAnimationFrame);
  7778. }
  7779. return {
  7780. start: function () {
  7781. if (isAnimating === true) return;
  7782. if (animationLoop === null) return;
  7783. requestId = context.requestAnimationFrame(onAnimationFrame);
  7784. isAnimating = true;
  7785. },
  7786. stop: function () {
  7787. context.cancelAnimationFrame(requestId);
  7788. isAnimating = false;
  7789. },
  7790. setAnimationLoop: function (callback) {
  7791. animationLoop = callback;
  7792. },
  7793. setContext: function (value) {
  7794. context = value;
  7795. }
  7796. };
  7797. }
  7798. function WebGLAttributes(gl, capabilities) {
  7799. const isWebGL2 = capabilities.isWebGL2;
  7800. const buffers = new WeakMap();
  7801. function createBuffer(attribute, bufferType) {
  7802. const array = attribute.array;
  7803. const usage = attribute.usage;
  7804. const buffer = gl.createBuffer();
  7805. gl.bindBuffer(bufferType, buffer);
  7806. gl.bufferData(bufferType, array, usage);
  7807. attribute.onUploadCallback();
  7808. let type;
  7809. if (array instanceof Float32Array) {
  7810. type = gl.FLOAT;
  7811. } else if (array instanceof Uint16Array) {
  7812. if (attribute.isFloat16BufferAttribute) {
  7813. if (isWebGL2) {
  7814. type = gl.HALF_FLOAT;
  7815. } else {
  7816. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7817. }
  7818. } else {
  7819. type = gl.UNSIGNED_SHORT;
  7820. }
  7821. } else if (array instanceof Int16Array) {
  7822. type = gl.SHORT;
  7823. } else if (array instanceof Uint32Array) {
  7824. type = gl.UNSIGNED_INT;
  7825. } else if (array instanceof Int32Array) {
  7826. type = gl.INT;
  7827. } else if (array instanceof Int8Array) {
  7828. type = gl.BYTE;
  7829. } else if (array instanceof Uint8Array) {
  7830. type = gl.UNSIGNED_BYTE;
  7831. } else if (array instanceof Uint8ClampedArray) {
  7832. type = gl.UNSIGNED_BYTE;
  7833. } else {
  7834. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7835. }
  7836. return {
  7837. buffer: buffer,
  7838. type: type,
  7839. bytesPerElement: array.BYTES_PER_ELEMENT,
  7840. version: attribute.version
  7841. };
  7842. }
  7843. function updateBuffer(buffer, attribute, bufferType) {
  7844. const array = attribute.array;
  7845. const updateRange = attribute.updateRange;
  7846. gl.bindBuffer(bufferType, buffer);
  7847. if (updateRange.count === -1) {
  7848. // Not using update ranges
  7849. gl.bufferSubData(bufferType, 0, array);
  7850. } else {
  7851. if (isWebGL2) {
  7852. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7853. } else {
  7854. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7855. }
  7856. updateRange.count = -1; // reset range
  7857. }
  7858. } //
  7859. function get(attribute) {
  7860. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7861. return buffers.get(attribute);
  7862. }
  7863. function remove(attribute) {
  7864. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7865. const data = buffers.get(attribute);
  7866. if (data) {
  7867. gl.deleteBuffer(data.buffer);
  7868. buffers.delete(attribute);
  7869. }
  7870. }
  7871. function update(attribute, bufferType) {
  7872. if (attribute.isGLBufferAttribute) {
  7873. const cached = buffers.get(attribute);
  7874. if (!cached || cached.version < attribute.version) {
  7875. buffers.set(attribute, {
  7876. buffer: attribute.buffer,
  7877. type: attribute.type,
  7878. bytesPerElement: attribute.elementSize,
  7879. version: attribute.version
  7880. });
  7881. }
  7882. return;
  7883. }
  7884. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7885. const data = buffers.get(attribute);
  7886. if (data === undefined) {
  7887. buffers.set(attribute, createBuffer(attribute, bufferType));
  7888. } else if (data.version < attribute.version) {
  7889. updateBuffer(data.buffer, attribute, bufferType);
  7890. data.version = attribute.version;
  7891. }
  7892. }
  7893. return {
  7894. get: get,
  7895. remove: remove,
  7896. update: update
  7897. };
  7898. }
  7899. class PlaneGeometry extends BufferGeometry {
  7900. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7901. super();
  7902. this.type = 'PlaneGeometry';
  7903. this.parameters = {
  7904. width: width,
  7905. height: height,
  7906. widthSegments: widthSegments,
  7907. heightSegments: heightSegments
  7908. };
  7909. const width_half = width / 2;
  7910. const height_half = height / 2;
  7911. const gridX = Math.floor(widthSegments);
  7912. const gridY = Math.floor(heightSegments);
  7913. const gridX1 = gridX + 1;
  7914. const gridY1 = gridY + 1;
  7915. const segment_width = width / gridX;
  7916. const segment_height = height / gridY; //
  7917. const indices = [];
  7918. const vertices = [];
  7919. const normals = [];
  7920. const uvs = [];
  7921. for (let iy = 0; iy < gridY1; iy++) {
  7922. const y = iy * segment_height - height_half;
  7923. for (let ix = 0; ix < gridX1; ix++) {
  7924. const x = ix * segment_width - width_half;
  7925. vertices.push(x, -y, 0);
  7926. normals.push(0, 0, 1);
  7927. uvs.push(ix / gridX);
  7928. uvs.push(1 - iy / gridY);
  7929. }
  7930. }
  7931. for (let iy = 0; iy < gridY; iy++) {
  7932. for (let ix = 0; ix < gridX; ix++) {
  7933. const a = ix + gridX1 * iy;
  7934. const b = ix + gridX1 * (iy + 1);
  7935. const c = ix + 1 + gridX1 * (iy + 1);
  7936. const d = ix + 1 + gridX1 * iy;
  7937. indices.push(a, b, d);
  7938. indices.push(b, c, d);
  7939. }
  7940. }
  7941. this.setIndex(indices);
  7942. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7943. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7944. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7945. }
  7946. static fromJSON(data) {
  7947. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7948. }
  7949. }
  7950. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7951. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7952. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7953. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7954. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7955. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7956. var begin_vertex = "vec3 transformed = vec3( position );";
  7957. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7958. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7959. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\t return vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat R21 = R12;\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  7960. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7961. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  7962. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7963. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7964. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7965. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7966. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7967. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7968. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  7969. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7970. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  7971. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  7972. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7973. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7974. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7975. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7976. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7977. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  7978. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7979. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  7980. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  7981. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  7982. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  7983. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7984. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7985. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7986. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7987. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  7988. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7989. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7990. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7991. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material )\t(0)";
  7992. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7993. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7994. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7995. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7996. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7997. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7998. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7999. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  8000. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tinSpotLightMap = inSpotLightMap && ( spotColor.a > 0. );\n\t\t\tdirectLight.visible = directLight.visible || inSpotLightMap;\n\t\t\tdirectLight.color = inSpotLightMap ? mix( directLight.color, spotLight.color * spotColor.rgb, spotColor.a ) : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8001. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8002. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  8003. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8004. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8005. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8006. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  8007. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8008. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8009. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8010. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8011. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8012. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8013. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  8014. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  8015. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  8016. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  8017. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8018. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8019. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  8020. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  8021. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  8022. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  8023. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8024. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  8025. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  8026. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8027. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8028. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  8029. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8030. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8031. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8032. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  8033. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8034. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8035. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8036. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8037. var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  8038. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8039. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  8040. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  8041. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  8042. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  8043. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8044. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8045. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8046. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8047. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  8048. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  8049. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8050. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  8051. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8052. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8053. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  8054. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8055. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_MAPS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8056. const vertex$g = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  8057. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8058. const vertex$f = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  8059. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8060. const vertex$e = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8061. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8062. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8063. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8064. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  8065. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8066. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8067. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8068. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8069. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8070. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8071. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8072. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8073. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8074. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8075. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8076. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8077. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8078. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8079. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8080. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8081. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8082. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8083. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8084. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8085. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8086. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8087. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8088. const ShaderChunk = {
  8089. alphamap_fragment: alphamap_fragment,
  8090. alphamap_pars_fragment: alphamap_pars_fragment,
  8091. alphatest_fragment: alphatest_fragment,
  8092. alphatest_pars_fragment: alphatest_pars_fragment,
  8093. aomap_fragment: aomap_fragment,
  8094. aomap_pars_fragment: aomap_pars_fragment,
  8095. begin_vertex: begin_vertex,
  8096. beginnormal_vertex: beginnormal_vertex,
  8097. bsdfs: bsdfs,
  8098. iridescence_fragment: iridescence_fragment,
  8099. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8100. clipping_planes_fragment: clipping_planes_fragment,
  8101. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8102. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8103. clipping_planes_vertex: clipping_planes_vertex,
  8104. color_fragment: color_fragment,
  8105. color_pars_fragment: color_pars_fragment,
  8106. color_pars_vertex: color_pars_vertex,
  8107. color_vertex: color_vertex,
  8108. common: common,
  8109. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8110. defaultnormal_vertex: defaultnormal_vertex,
  8111. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8112. displacementmap_vertex: displacementmap_vertex,
  8113. emissivemap_fragment: emissivemap_fragment,
  8114. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8115. encodings_fragment: encodings_fragment,
  8116. encodings_pars_fragment: encodings_pars_fragment,
  8117. envmap_fragment: envmap_fragment,
  8118. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8119. envmap_pars_fragment: envmap_pars_fragment,
  8120. envmap_pars_vertex: envmap_pars_vertex,
  8121. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8122. envmap_vertex: envmap_vertex,
  8123. fog_vertex: fog_vertex,
  8124. fog_pars_vertex: fog_pars_vertex,
  8125. fog_fragment: fog_fragment,
  8126. fog_pars_fragment: fog_pars_fragment,
  8127. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8128. lightmap_fragment: lightmap_fragment,
  8129. lightmap_pars_fragment: lightmap_pars_fragment,
  8130. lights_lambert_fragment: lights_lambert_fragment,
  8131. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8132. lights_pars_begin: lights_pars_begin,
  8133. lights_toon_fragment: lights_toon_fragment,
  8134. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8135. lights_phong_fragment: lights_phong_fragment,
  8136. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8137. lights_physical_fragment: lights_physical_fragment,
  8138. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8139. lights_fragment_begin: lights_fragment_begin,
  8140. lights_fragment_maps: lights_fragment_maps,
  8141. lights_fragment_end: lights_fragment_end,
  8142. logdepthbuf_fragment: logdepthbuf_fragment,
  8143. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8144. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8145. logdepthbuf_vertex: logdepthbuf_vertex,
  8146. map_fragment: map_fragment,
  8147. map_pars_fragment: map_pars_fragment,
  8148. map_particle_fragment: map_particle_fragment,
  8149. map_particle_pars_fragment: map_particle_pars_fragment,
  8150. metalnessmap_fragment: metalnessmap_fragment,
  8151. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8152. morphcolor_vertex: morphcolor_vertex,
  8153. morphnormal_vertex: morphnormal_vertex,
  8154. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8155. morphtarget_vertex: morphtarget_vertex,
  8156. normal_fragment_begin: normal_fragment_begin,
  8157. normal_fragment_maps: normal_fragment_maps,
  8158. normal_pars_fragment: normal_pars_fragment,
  8159. normal_pars_vertex: normal_pars_vertex,
  8160. normal_vertex: normal_vertex,
  8161. normalmap_pars_fragment: normalmap_pars_fragment,
  8162. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8163. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8164. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8165. iridescence_pars_fragment: iridescence_pars_fragment,
  8166. output_fragment: output_fragment,
  8167. packing: packing,
  8168. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8169. project_vertex: project_vertex,
  8170. dithering_fragment: dithering_fragment,
  8171. dithering_pars_fragment: dithering_pars_fragment,
  8172. roughnessmap_fragment: roughnessmap_fragment,
  8173. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8174. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8175. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8176. shadowmap_vertex: shadowmap_vertex,
  8177. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8178. skinbase_vertex: skinbase_vertex,
  8179. skinning_pars_vertex: skinning_pars_vertex,
  8180. skinning_vertex: skinning_vertex,
  8181. skinnormal_vertex: skinnormal_vertex,
  8182. specularmap_fragment: specularmap_fragment,
  8183. specularmap_pars_fragment: specularmap_pars_fragment,
  8184. tonemapping_fragment: tonemapping_fragment,
  8185. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8186. transmission_fragment: transmission_fragment,
  8187. transmission_pars_fragment: transmission_pars_fragment,
  8188. uv_pars_fragment: uv_pars_fragment,
  8189. uv_pars_vertex: uv_pars_vertex,
  8190. uv_vertex: uv_vertex,
  8191. uv2_pars_fragment: uv2_pars_fragment,
  8192. uv2_pars_vertex: uv2_pars_vertex,
  8193. uv2_vertex: uv2_vertex,
  8194. worldpos_vertex: worldpos_vertex,
  8195. background_vert: vertex$g,
  8196. background_frag: fragment$g,
  8197. cube_vert: vertex$f,
  8198. cube_frag: fragment$f,
  8199. depth_vert: vertex$e,
  8200. depth_frag: fragment$e,
  8201. distanceRGBA_vert: vertex$d,
  8202. distanceRGBA_frag: fragment$d,
  8203. equirect_vert: vertex$c,
  8204. equirect_frag: fragment$c,
  8205. linedashed_vert: vertex$b,
  8206. linedashed_frag: fragment$b,
  8207. meshbasic_vert: vertex$a,
  8208. meshbasic_frag: fragment$a,
  8209. meshlambert_vert: vertex$9,
  8210. meshlambert_frag: fragment$9,
  8211. meshmatcap_vert: vertex$8,
  8212. meshmatcap_frag: fragment$8,
  8213. meshnormal_vert: vertex$7,
  8214. meshnormal_frag: fragment$7,
  8215. meshphong_vert: vertex$6,
  8216. meshphong_frag: fragment$6,
  8217. meshphysical_vert: vertex$5,
  8218. meshphysical_frag: fragment$5,
  8219. meshtoon_vert: vertex$4,
  8220. meshtoon_frag: fragment$4,
  8221. points_vert: vertex$3,
  8222. points_frag: fragment$3,
  8223. shadow_vert: vertex$2,
  8224. shadow_frag: fragment$2,
  8225. sprite_vert: vertex$1,
  8226. sprite_frag: fragment$1
  8227. };
  8228. /**
  8229. * Uniforms library for shared webgl shaders
  8230. */
  8231. const UniformsLib = {
  8232. common: {
  8233. diffuse: {
  8234. value: /*@__PURE__*/new Color(0xffffff)
  8235. },
  8236. opacity: {
  8237. value: 1.0
  8238. },
  8239. map: {
  8240. value: null
  8241. },
  8242. uvTransform: {
  8243. value: /*@__PURE__*/new Matrix3()
  8244. },
  8245. uv2Transform: {
  8246. value: /*@__PURE__*/new Matrix3()
  8247. },
  8248. alphaMap: {
  8249. value: null
  8250. },
  8251. alphaTest: {
  8252. value: 0
  8253. }
  8254. },
  8255. specularmap: {
  8256. specularMap: {
  8257. value: null
  8258. }
  8259. },
  8260. envmap: {
  8261. envMap: {
  8262. value: null
  8263. },
  8264. flipEnvMap: {
  8265. value: -1
  8266. },
  8267. reflectivity: {
  8268. value: 1.0
  8269. },
  8270. // basic, lambert, phong
  8271. ior: {
  8272. value: 1.5
  8273. },
  8274. // physical
  8275. refractionRatio: {
  8276. value: 0.98
  8277. } // basic, lambert, phong
  8278. },
  8279. aomap: {
  8280. aoMap: {
  8281. value: null
  8282. },
  8283. aoMapIntensity: {
  8284. value: 1
  8285. }
  8286. },
  8287. lightmap: {
  8288. lightMap: {
  8289. value: null
  8290. },
  8291. lightMapIntensity: {
  8292. value: 1
  8293. }
  8294. },
  8295. emissivemap: {
  8296. emissiveMap: {
  8297. value: null
  8298. }
  8299. },
  8300. bumpmap: {
  8301. bumpMap: {
  8302. value: null
  8303. },
  8304. bumpScale: {
  8305. value: 1
  8306. }
  8307. },
  8308. normalmap: {
  8309. normalMap: {
  8310. value: null
  8311. },
  8312. normalScale: {
  8313. value: /*@__PURE__*/new Vector2(1, 1)
  8314. }
  8315. },
  8316. displacementmap: {
  8317. displacementMap: {
  8318. value: null
  8319. },
  8320. displacementScale: {
  8321. value: 1
  8322. },
  8323. displacementBias: {
  8324. value: 0
  8325. }
  8326. },
  8327. roughnessmap: {
  8328. roughnessMap: {
  8329. value: null
  8330. }
  8331. },
  8332. metalnessmap: {
  8333. metalnessMap: {
  8334. value: null
  8335. }
  8336. },
  8337. gradientmap: {
  8338. gradientMap: {
  8339. value: null
  8340. }
  8341. },
  8342. fog: {
  8343. fogDensity: {
  8344. value: 0.00025
  8345. },
  8346. fogNear: {
  8347. value: 1
  8348. },
  8349. fogFar: {
  8350. value: 2000
  8351. },
  8352. fogColor: {
  8353. value: /*@__PURE__*/new Color(0xffffff)
  8354. }
  8355. },
  8356. lights: {
  8357. ambientLightColor: {
  8358. value: []
  8359. },
  8360. lightProbe: {
  8361. value: []
  8362. },
  8363. directionalLights: {
  8364. value: [],
  8365. properties: {
  8366. direction: {},
  8367. color: {}
  8368. }
  8369. },
  8370. directionalLightShadows: {
  8371. value: [],
  8372. properties: {
  8373. shadowBias: {},
  8374. shadowNormalBias: {},
  8375. shadowRadius: {},
  8376. shadowMapSize: {}
  8377. }
  8378. },
  8379. directionalShadowMap: {
  8380. value: []
  8381. },
  8382. directionalShadowMatrix: {
  8383. value: []
  8384. },
  8385. spotLights: {
  8386. value: [],
  8387. properties: {
  8388. color: {},
  8389. position: {},
  8390. direction: {},
  8391. distance: {},
  8392. coneCos: {},
  8393. penumbraCos: {},
  8394. decay: {}
  8395. }
  8396. },
  8397. spotLightShadows: {
  8398. value: [],
  8399. properties: {
  8400. shadowBias: {},
  8401. shadowNormalBias: {},
  8402. shadowRadius: {},
  8403. shadowMapSize: {}
  8404. }
  8405. },
  8406. spotLightMap: {
  8407. value: []
  8408. },
  8409. spotShadowMap: {
  8410. value: []
  8411. },
  8412. spotLightMatrix: {
  8413. value: []
  8414. },
  8415. pointLights: {
  8416. value: [],
  8417. properties: {
  8418. color: {},
  8419. position: {},
  8420. decay: {},
  8421. distance: {}
  8422. }
  8423. },
  8424. pointLightShadows: {
  8425. value: [],
  8426. properties: {
  8427. shadowBias: {},
  8428. shadowNormalBias: {},
  8429. shadowRadius: {},
  8430. shadowMapSize: {},
  8431. shadowCameraNear: {},
  8432. shadowCameraFar: {}
  8433. }
  8434. },
  8435. pointShadowMap: {
  8436. value: []
  8437. },
  8438. pointShadowMatrix: {
  8439. value: []
  8440. },
  8441. hemisphereLights: {
  8442. value: [],
  8443. properties: {
  8444. direction: {},
  8445. skyColor: {},
  8446. groundColor: {}
  8447. }
  8448. },
  8449. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8450. rectAreaLights: {
  8451. value: [],
  8452. properties: {
  8453. color: {},
  8454. position: {},
  8455. width: {},
  8456. height: {}
  8457. }
  8458. },
  8459. ltc_1: {
  8460. value: null
  8461. },
  8462. ltc_2: {
  8463. value: null
  8464. }
  8465. },
  8466. points: {
  8467. diffuse: {
  8468. value: /*@__PURE__*/new Color(0xffffff)
  8469. },
  8470. opacity: {
  8471. value: 1.0
  8472. },
  8473. size: {
  8474. value: 1.0
  8475. },
  8476. scale: {
  8477. value: 1.0
  8478. },
  8479. map: {
  8480. value: null
  8481. },
  8482. alphaMap: {
  8483. value: null
  8484. },
  8485. alphaTest: {
  8486. value: 0
  8487. },
  8488. uvTransform: {
  8489. value: /*@__PURE__*/new Matrix3()
  8490. }
  8491. },
  8492. sprite: {
  8493. diffuse: {
  8494. value: /*@__PURE__*/new Color(0xffffff)
  8495. },
  8496. opacity: {
  8497. value: 1.0
  8498. },
  8499. center: {
  8500. value: /*@__PURE__*/new Vector2(0.5, 0.5)
  8501. },
  8502. rotation: {
  8503. value: 0.0
  8504. },
  8505. map: {
  8506. value: null
  8507. },
  8508. alphaMap: {
  8509. value: null
  8510. },
  8511. alphaTest: {
  8512. value: 0
  8513. },
  8514. uvTransform: {
  8515. value: /*@__PURE__*/new Matrix3()
  8516. }
  8517. }
  8518. };
  8519. const ShaderLib = {
  8520. basic: {
  8521. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8522. vertexShader: ShaderChunk.meshbasic_vert,
  8523. fragmentShader: ShaderChunk.meshbasic_frag
  8524. },
  8525. lambert: {
  8526. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8527. emissive: {
  8528. value: /*@__PURE__*/new Color(0x000000)
  8529. }
  8530. }]),
  8531. vertexShader: ShaderChunk.meshlambert_vert,
  8532. fragmentShader: ShaderChunk.meshlambert_frag
  8533. },
  8534. phong: {
  8535. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8536. emissive: {
  8537. value: /*@__PURE__*/new Color(0x000000)
  8538. },
  8539. specular: {
  8540. value: /*@__PURE__*/new Color(0x111111)
  8541. },
  8542. shininess: {
  8543. value: 30
  8544. }
  8545. }]),
  8546. vertexShader: ShaderChunk.meshphong_vert,
  8547. fragmentShader: ShaderChunk.meshphong_frag
  8548. },
  8549. standard: {
  8550. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  8551. emissive: {
  8552. value: /*@__PURE__*/new Color(0x000000)
  8553. },
  8554. roughness: {
  8555. value: 1.0
  8556. },
  8557. metalness: {
  8558. value: 0.0
  8559. },
  8560. envMapIntensity: {
  8561. value: 1
  8562. } // temporary
  8563. }]),
  8564. vertexShader: ShaderChunk.meshphysical_vert,
  8565. fragmentShader: ShaderChunk.meshphysical_frag
  8566. },
  8567. toon: {
  8568. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8569. emissive: {
  8570. value: /*@__PURE__*/new Color(0x000000)
  8571. }
  8572. }]),
  8573. vertexShader: ShaderChunk.meshtoon_vert,
  8574. fragmentShader: ShaderChunk.meshtoon_frag
  8575. },
  8576. matcap: {
  8577. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8578. matcap: {
  8579. value: null
  8580. }
  8581. }]),
  8582. vertexShader: ShaderChunk.meshmatcap_vert,
  8583. fragmentShader: ShaderChunk.meshmatcap_frag
  8584. },
  8585. points: {
  8586. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8587. vertexShader: ShaderChunk.points_vert,
  8588. fragmentShader: ShaderChunk.points_frag
  8589. },
  8590. dashed: {
  8591. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8592. scale: {
  8593. value: 1
  8594. },
  8595. dashSize: {
  8596. value: 1
  8597. },
  8598. totalSize: {
  8599. value: 2
  8600. }
  8601. }]),
  8602. vertexShader: ShaderChunk.linedashed_vert,
  8603. fragmentShader: ShaderChunk.linedashed_frag
  8604. },
  8605. depth: {
  8606. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8607. vertexShader: ShaderChunk.depth_vert,
  8608. fragmentShader: ShaderChunk.depth_frag
  8609. },
  8610. normal: {
  8611. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8612. opacity: {
  8613. value: 1.0
  8614. }
  8615. }]),
  8616. vertexShader: ShaderChunk.meshnormal_vert,
  8617. fragmentShader: ShaderChunk.meshnormal_frag
  8618. },
  8619. sprite: {
  8620. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8621. vertexShader: ShaderChunk.sprite_vert,
  8622. fragmentShader: ShaderChunk.sprite_frag
  8623. },
  8624. background: {
  8625. uniforms: {
  8626. uvTransform: {
  8627. value: /*@__PURE__*/new Matrix3()
  8628. },
  8629. t2D: {
  8630. value: null
  8631. }
  8632. },
  8633. vertexShader: ShaderChunk.background_vert,
  8634. fragmentShader: ShaderChunk.background_frag
  8635. },
  8636. cube: {
  8637. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.envmap, {
  8638. opacity: {
  8639. value: 1.0
  8640. }
  8641. }]),
  8642. vertexShader: ShaderChunk.cube_vert,
  8643. fragmentShader: ShaderChunk.cube_frag
  8644. },
  8645. equirect: {
  8646. uniforms: {
  8647. tEquirect: {
  8648. value: null
  8649. }
  8650. },
  8651. vertexShader: ShaderChunk.equirect_vert,
  8652. fragmentShader: ShaderChunk.equirect_frag
  8653. },
  8654. distanceRGBA: {
  8655. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8656. referencePosition: {
  8657. value: /*@__PURE__*/new Vector3()
  8658. },
  8659. nearDistance: {
  8660. value: 1
  8661. },
  8662. farDistance: {
  8663. value: 1000
  8664. }
  8665. }]),
  8666. vertexShader: ShaderChunk.distanceRGBA_vert,
  8667. fragmentShader: ShaderChunk.distanceRGBA_frag
  8668. },
  8669. shadow: {
  8670. uniforms: /*@__PURE__*/mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8671. color: {
  8672. value: /*@__PURE__*/new Color(0x00000)
  8673. },
  8674. opacity: {
  8675. value: 1.0
  8676. }
  8677. }]),
  8678. vertexShader: ShaderChunk.shadow_vert,
  8679. fragmentShader: ShaderChunk.shadow_frag
  8680. }
  8681. };
  8682. ShaderLib.physical = {
  8683. uniforms: /*@__PURE__*/mergeUniforms([ShaderLib.standard.uniforms, {
  8684. clearcoat: {
  8685. value: 0
  8686. },
  8687. clearcoatMap: {
  8688. value: null
  8689. },
  8690. clearcoatRoughness: {
  8691. value: 0
  8692. },
  8693. clearcoatRoughnessMap: {
  8694. value: null
  8695. },
  8696. clearcoatNormalScale: {
  8697. value: /*@__PURE__*/new Vector2(1, 1)
  8698. },
  8699. clearcoatNormalMap: {
  8700. value: null
  8701. },
  8702. iridescence: {
  8703. value: 0
  8704. },
  8705. iridescenceMap: {
  8706. value: null
  8707. },
  8708. iridescenceIOR: {
  8709. value: 1.3
  8710. },
  8711. iridescenceThicknessMinimum: {
  8712. value: 100
  8713. },
  8714. iridescenceThicknessMaximum: {
  8715. value: 400
  8716. },
  8717. iridescenceThicknessMap: {
  8718. value: null
  8719. },
  8720. sheen: {
  8721. value: 0
  8722. },
  8723. sheenColor: {
  8724. value: /*@__PURE__*/new Color(0x000000)
  8725. },
  8726. sheenColorMap: {
  8727. value: null
  8728. },
  8729. sheenRoughness: {
  8730. value: 1
  8731. },
  8732. sheenRoughnessMap: {
  8733. value: null
  8734. },
  8735. transmission: {
  8736. value: 0
  8737. },
  8738. transmissionMap: {
  8739. value: null
  8740. },
  8741. transmissionSamplerSize: {
  8742. value: /*@__PURE__*/new Vector2()
  8743. },
  8744. transmissionSamplerMap: {
  8745. value: null
  8746. },
  8747. thickness: {
  8748. value: 0
  8749. },
  8750. thicknessMap: {
  8751. value: null
  8752. },
  8753. attenuationDistance: {
  8754. value: 0
  8755. },
  8756. attenuationColor: {
  8757. value: /*@__PURE__*/new Color(0x000000)
  8758. },
  8759. specularIntensity: {
  8760. value: 1
  8761. },
  8762. specularIntensityMap: {
  8763. value: null
  8764. },
  8765. specularColor: {
  8766. value: /*@__PURE__*/new Color(1, 1, 1)
  8767. },
  8768. specularColorMap: {
  8769. value: null
  8770. }
  8771. }]),
  8772. vertexShader: ShaderChunk.meshphysical_vert,
  8773. fragmentShader: ShaderChunk.meshphysical_frag
  8774. };
  8775. function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
  8776. const clearColor = new Color(0x000000);
  8777. let clearAlpha = alpha === true ? 0 : 1;
  8778. let planeMesh;
  8779. let boxMesh;
  8780. let currentBackground = null;
  8781. let currentBackgroundVersion = 0;
  8782. let currentTonemapping = null;
  8783. function render(renderList, scene) {
  8784. let forceClear = false;
  8785. let background = scene.isScene === true ? scene.background : null;
  8786. if (background && background.isTexture) {
  8787. background = cubemaps.get(background);
  8788. } // Ignore background in AR
  8789. // TODO: Reconsider this.
  8790. const xr = renderer.xr;
  8791. const session = xr.getSession && xr.getSession();
  8792. if (session && session.environmentBlendMode === 'additive') {
  8793. background = null;
  8794. }
  8795. if (background === null) {
  8796. setClear(clearColor, clearAlpha);
  8797. } else if (background && background.isColor) {
  8798. setClear(background, 1);
  8799. forceClear = true;
  8800. }
  8801. if (renderer.autoClear || forceClear) {
  8802. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8803. }
  8804. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8805. if (boxMesh === undefined) {
  8806. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8807. name: 'BackgroundCubeMaterial',
  8808. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8809. vertexShader: ShaderLib.cube.vertexShader,
  8810. fragmentShader: ShaderLib.cube.fragmentShader,
  8811. side: BackSide,
  8812. depthTest: false,
  8813. depthWrite: false,
  8814. fog: false
  8815. }));
  8816. boxMesh.geometry.deleteAttribute('normal');
  8817. boxMesh.geometry.deleteAttribute('uv');
  8818. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8819. this.matrixWorld.copyPosition(camera.matrixWorld);
  8820. }; // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8821. Object.defineProperty(boxMesh.material, 'envMap', {
  8822. get: function () {
  8823. return this.uniforms.envMap.value;
  8824. }
  8825. });
  8826. objects.update(boxMesh);
  8827. }
  8828. boxMesh.material.uniforms.envMap.value = background;
  8829. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8830. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8831. boxMesh.material.needsUpdate = true;
  8832. currentBackground = background;
  8833. currentBackgroundVersion = background.version;
  8834. currentTonemapping = renderer.toneMapping;
  8835. }
  8836. boxMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8837. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8838. } else if (background && background.isTexture) {
  8839. if (planeMesh === undefined) {
  8840. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8841. name: 'BackgroundMaterial',
  8842. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8843. vertexShader: ShaderLib.background.vertexShader,
  8844. fragmentShader: ShaderLib.background.fragmentShader,
  8845. side: FrontSide,
  8846. depthTest: false,
  8847. depthWrite: false,
  8848. fog: false
  8849. }));
  8850. planeMesh.geometry.deleteAttribute('normal'); // add "map" material property so the renderer can evaluate it like for built-in materials
  8851. Object.defineProperty(planeMesh.material, 'map', {
  8852. get: function () {
  8853. return this.uniforms.t2D.value;
  8854. }
  8855. });
  8856. objects.update(planeMesh);
  8857. }
  8858. planeMesh.material.uniforms.t2D.value = background;
  8859. if (background.matrixAutoUpdate === true) {
  8860. background.updateMatrix();
  8861. }
  8862. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8863. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8864. planeMesh.material.needsUpdate = true;
  8865. currentBackground = background;
  8866. currentBackgroundVersion = background.version;
  8867. currentTonemapping = renderer.toneMapping;
  8868. }
  8869. planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8870. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8871. }
  8872. }
  8873. function setClear(color, alpha) {
  8874. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8875. }
  8876. return {
  8877. getClearColor: function () {
  8878. return clearColor;
  8879. },
  8880. setClearColor: function (color, alpha = 1) {
  8881. clearColor.set(color);
  8882. clearAlpha = alpha;
  8883. setClear(clearColor, clearAlpha);
  8884. },
  8885. getClearAlpha: function () {
  8886. return clearAlpha;
  8887. },
  8888. setClearAlpha: function (alpha) {
  8889. clearAlpha = alpha;
  8890. setClear(clearColor, clearAlpha);
  8891. },
  8892. render: render
  8893. };
  8894. }
  8895. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8896. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8897. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8898. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8899. const bindingStates = {};
  8900. const defaultState = createBindingState(null);
  8901. let currentState = defaultState;
  8902. let forceUpdate = false;
  8903. function setup(object, material, program, geometry, index) {
  8904. let updateBuffers = false;
  8905. if (vaoAvailable) {
  8906. const state = getBindingState(geometry, program, material);
  8907. if (currentState !== state) {
  8908. currentState = state;
  8909. bindVertexArrayObject(currentState.object);
  8910. }
  8911. updateBuffers = needsUpdate(object, geometry, program, index);
  8912. if (updateBuffers) saveCache(object, geometry, program, index);
  8913. } else {
  8914. const wireframe = material.wireframe === true;
  8915. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8916. currentState.geometry = geometry.id;
  8917. currentState.program = program.id;
  8918. currentState.wireframe = wireframe;
  8919. updateBuffers = true;
  8920. }
  8921. }
  8922. if (index !== null) {
  8923. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8924. }
  8925. if (updateBuffers || forceUpdate) {
  8926. forceUpdate = false;
  8927. setupVertexAttributes(object, material, program, geometry);
  8928. if (index !== null) {
  8929. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8930. }
  8931. }
  8932. }
  8933. function createVertexArrayObject() {
  8934. if (capabilities.isWebGL2) return gl.createVertexArray();
  8935. return extension.createVertexArrayOES();
  8936. }
  8937. function bindVertexArrayObject(vao) {
  8938. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8939. return extension.bindVertexArrayOES(vao);
  8940. }
  8941. function deleteVertexArrayObject(vao) {
  8942. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8943. return extension.deleteVertexArrayOES(vao);
  8944. }
  8945. function getBindingState(geometry, program, material) {
  8946. const wireframe = material.wireframe === true;
  8947. let programMap = bindingStates[geometry.id];
  8948. if (programMap === undefined) {
  8949. programMap = {};
  8950. bindingStates[geometry.id] = programMap;
  8951. }
  8952. let stateMap = programMap[program.id];
  8953. if (stateMap === undefined) {
  8954. stateMap = {};
  8955. programMap[program.id] = stateMap;
  8956. }
  8957. let state = stateMap[wireframe];
  8958. if (state === undefined) {
  8959. state = createBindingState(createVertexArrayObject());
  8960. stateMap[wireframe] = state;
  8961. }
  8962. return state;
  8963. }
  8964. function createBindingState(vao) {
  8965. const newAttributes = [];
  8966. const enabledAttributes = [];
  8967. const attributeDivisors = [];
  8968. for (let i = 0; i < maxVertexAttributes; i++) {
  8969. newAttributes[i] = 0;
  8970. enabledAttributes[i] = 0;
  8971. attributeDivisors[i] = 0;
  8972. }
  8973. return {
  8974. // for backward compatibility on non-VAO support browser
  8975. geometry: null,
  8976. program: null,
  8977. wireframe: false,
  8978. newAttributes: newAttributes,
  8979. enabledAttributes: enabledAttributes,
  8980. attributeDivisors: attributeDivisors,
  8981. object: vao,
  8982. attributes: {},
  8983. index: null
  8984. };
  8985. }
  8986. function needsUpdate(object, geometry, program, index) {
  8987. const cachedAttributes = currentState.attributes;
  8988. const geometryAttributes = geometry.attributes;
  8989. let attributesNum = 0;
  8990. const programAttributes = program.getAttributes();
  8991. for (const name in programAttributes) {
  8992. const programAttribute = programAttributes[name];
  8993. if (programAttribute.location >= 0) {
  8994. const cachedAttribute = cachedAttributes[name];
  8995. let geometryAttribute = geometryAttributes[name];
  8996. if (geometryAttribute === undefined) {
  8997. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8998. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8999. }
  9000. if (cachedAttribute === undefined) return true;
  9001. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9002. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  9003. attributesNum++;
  9004. }
  9005. }
  9006. if (currentState.attributesNum !== attributesNum) return true;
  9007. if (currentState.index !== index) return true;
  9008. return false;
  9009. }
  9010. function saveCache(object, geometry, program, index) {
  9011. const cache = {};
  9012. const attributes = geometry.attributes;
  9013. let attributesNum = 0;
  9014. const programAttributes = program.getAttributes();
  9015. for (const name in programAttributes) {
  9016. const programAttribute = programAttributes[name];
  9017. if (programAttribute.location >= 0) {
  9018. let attribute = attributes[name];
  9019. if (attribute === undefined) {
  9020. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  9021. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  9022. }
  9023. const data = {};
  9024. data.attribute = attribute;
  9025. if (attribute && attribute.data) {
  9026. data.data = attribute.data;
  9027. }
  9028. cache[name] = data;
  9029. attributesNum++;
  9030. }
  9031. }
  9032. currentState.attributes = cache;
  9033. currentState.attributesNum = attributesNum;
  9034. currentState.index = index;
  9035. }
  9036. function initAttributes() {
  9037. const newAttributes = currentState.newAttributes;
  9038. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9039. newAttributes[i] = 0;
  9040. }
  9041. }
  9042. function enableAttribute(attribute) {
  9043. enableAttributeAndDivisor(attribute, 0);
  9044. }
  9045. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9046. const newAttributes = currentState.newAttributes;
  9047. const enabledAttributes = currentState.enabledAttributes;
  9048. const attributeDivisors = currentState.attributeDivisors;
  9049. newAttributes[attribute] = 1;
  9050. if (enabledAttributes[attribute] === 0) {
  9051. gl.enableVertexAttribArray(attribute);
  9052. enabledAttributes[attribute] = 1;
  9053. }
  9054. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9055. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9056. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9057. attributeDivisors[attribute] = meshPerAttribute;
  9058. }
  9059. }
  9060. function disableUnusedAttributes() {
  9061. const newAttributes = currentState.newAttributes;
  9062. const enabledAttributes = currentState.enabledAttributes;
  9063. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9064. if (enabledAttributes[i] !== newAttributes[i]) {
  9065. gl.disableVertexAttribArray(i);
  9066. enabledAttributes[i] = 0;
  9067. }
  9068. }
  9069. }
  9070. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9071. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9072. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9073. } else {
  9074. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9075. }
  9076. }
  9077. function setupVertexAttributes(object, material, program, geometry) {
  9078. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9079. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9080. }
  9081. initAttributes();
  9082. const geometryAttributes = geometry.attributes;
  9083. const programAttributes = program.getAttributes();
  9084. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9085. for (const name in programAttributes) {
  9086. const programAttribute = programAttributes[name];
  9087. if (programAttribute.location >= 0) {
  9088. let geometryAttribute = geometryAttributes[name];
  9089. if (geometryAttribute === undefined) {
  9090. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9091. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9092. }
  9093. if (geometryAttribute !== undefined) {
  9094. const normalized = geometryAttribute.normalized;
  9095. const size = geometryAttribute.itemSize;
  9096. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9097. if (attribute === undefined) continue;
  9098. const buffer = attribute.buffer;
  9099. const type = attribute.type;
  9100. const bytesPerElement = attribute.bytesPerElement;
  9101. if (geometryAttribute.isInterleavedBufferAttribute) {
  9102. const data = geometryAttribute.data;
  9103. const stride = data.stride;
  9104. const offset = geometryAttribute.offset;
  9105. if (data.isInstancedInterleavedBuffer) {
  9106. for (let i = 0; i < programAttribute.locationSize; i++) {
  9107. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9108. }
  9109. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9110. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9111. }
  9112. } else {
  9113. for (let i = 0; i < programAttribute.locationSize; i++) {
  9114. enableAttribute(programAttribute.location + i);
  9115. }
  9116. }
  9117. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9118. for (let i = 0; i < programAttribute.locationSize; i++) {
  9119. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9120. }
  9121. } else {
  9122. if (geometryAttribute.isInstancedBufferAttribute) {
  9123. for (let i = 0; i < programAttribute.locationSize; i++) {
  9124. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9125. }
  9126. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9127. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9128. }
  9129. } else {
  9130. for (let i = 0; i < programAttribute.locationSize; i++) {
  9131. enableAttribute(programAttribute.location + i);
  9132. }
  9133. }
  9134. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9135. for (let i = 0; i < programAttribute.locationSize; i++) {
  9136. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9137. }
  9138. }
  9139. } else if (materialDefaultAttributeValues !== undefined) {
  9140. const value = materialDefaultAttributeValues[name];
  9141. if (value !== undefined) {
  9142. switch (value.length) {
  9143. case 2:
  9144. gl.vertexAttrib2fv(programAttribute.location, value);
  9145. break;
  9146. case 3:
  9147. gl.vertexAttrib3fv(programAttribute.location, value);
  9148. break;
  9149. case 4:
  9150. gl.vertexAttrib4fv(programAttribute.location, value);
  9151. break;
  9152. default:
  9153. gl.vertexAttrib1fv(programAttribute.location, value);
  9154. }
  9155. }
  9156. }
  9157. }
  9158. }
  9159. disableUnusedAttributes();
  9160. }
  9161. function dispose() {
  9162. reset();
  9163. for (const geometryId in bindingStates) {
  9164. const programMap = bindingStates[geometryId];
  9165. for (const programId in programMap) {
  9166. const stateMap = programMap[programId];
  9167. for (const wireframe in stateMap) {
  9168. deleteVertexArrayObject(stateMap[wireframe].object);
  9169. delete stateMap[wireframe];
  9170. }
  9171. delete programMap[programId];
  9172. }
  9173. delete bindingStates[geometryId];
  9174. }
  9175. }
  9176. function releaseStatesOfGeometry(geometry) {
  9177. if (bindingStates[geometry.id] === undefined) return;
  9178. const programMap = bindingStates[geometry.id];
  9179. for (const programId in programMap) {
  9180. const stateMap = programMap[programId];
  9181. for (const wireframe in stateMap) {
  9182. deleteVertexArrayObject(stateMap[wireframe].object);
  9183. delete stateMap[wireframe];
  9184. }
  9185. delete programMap[programId];
  9186. }
  9187. delete bindingStates[geometry.id];
  9188. }
  9189. function releaseStatesOfProgram(program) {
  9190. for (const geometryId in bindingStates) {
  9191. const programMap = bindingStates[geometryId];
  9192. if (programMap[program.id] === undefined) continue;
  9193. const stateMap = programMap[program.id];
  9194. for (const wireframe in stateMap) {
  9195. deleteVertexArrayObject(stateMap[wireframe].object);
  9196. delete stateMap[wireframe];
  9197. }
  9198. delete programMap[program.id];
  9199. }
  9200. }
  9201. function reset() {
  9202. resetDefaultState();
  9203. forceUpdate = true;
  9204. if (currentState === defaultState) return;
  9205. currentState = defaultState;
  9206. bindVertexArrayObject(currentState.object);
  9207. } // for backward-compatibility
  9208. function resetDefaultState() {
  9209. defaultState.geometry = null;
  9210. defaultState.program = null;
  9211. defaultState.wireframe = false;
  9212. }
  9213. return {
  9214. setup: setup,
  9215. reset: reset,
  9216. resetDefaultState: resetDefaultState,
  9217. dispose: dispose,
  9218. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9219. releaseStatesOfProgram: releaseStatesOfProgram,
  9220. initAttributes: initAttributes,
  9221. enableAttribute: enableAttribute,
  9222. disableUnusedAttributes: disableUnusedAttributes
  9223. };
  9224. }
  9225. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9226. const isWebGL2 = capabilities.isWebGL2;
  9227. let mode;
  9228. function setMode(value) {
  9229. mode = value;
  9230. }
  9231. function render(start, count) {
  9232. gl.drawArrays(mode, start, count);
  9233. info.update(count, mode, 1);
  9234. }
  9235. function renderInstances(start, count, primcount) {
  9236. if (primcount === 0) return;
  9237. let extension, methodName;
  9238. if (isWebGL2) {
  9239. extension = gl;
  9240. methodName = 'drawArraysInstanced';
  9241. } else {
  9242. extension = extensions.get('ANGLE_instanced_arrays');
  9243. methodName = 'drawArraysInstancedANGLE';
  9244. if (extension === null) {
  9245. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9246. return;
  9247. }
  9248. }
  9249. extension[methodName](mode, start, count, primcount);
  9250. info.update(count, mode, primcount);
  9251. } //
  9252. this.setMode = setMode;
  9253. this.render = render;
  9254. this.renderInstances = renderInstances;
  9255. }
  9256. function WebGLCapabilities(gl, extensions, parameters) {
  9257. let maxAnisotropy;
  9258. function getMaxAnisotropy() {
  9259. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9260. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9261. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9262. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9263. } else {
  9264. maxAnisotropy = 0;
  9265. }
  9266. return maxAnisotropy;
  9267. }
  9268. function getMaxPrecision(precision) {
  9269. if (precision === 'highp') {
  9270. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9271. return 'highp';
  9272. }
  9273. precision = 'mediump';
  9274. }
  9275. if (precision === 'mediump') {
  9276. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9277. return 'mediump';
  9278. }
  9279. }
  9280. return 'lowp';
  9281. }
  9282. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9283. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9284. const maxPrecision = getMaxPrecision(precision);
  9285. if (maxPrecision !== precision) {
  9286. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9287. precision = maxPrecision;
  9288. }
  9289. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9290. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9291. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9292. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9293. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9294. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9295. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9296. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9297. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9298. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9299. const vertexTextures = maxVertexTextures > 0;
  9300. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9301. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9302. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9303. return {
  9304. isWebGL2: isWebGL2,
  9305. drawBuffers: drawBuffers,
  9306. getMaxAnisotropy: getMaxAnisotropy,
  9307. getMaxPrecision: getMaxPrecision,
  9308. precision: precision,
  9309. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9310. maxTextures: maxTextures,
  9311. maxVertexTextures: maxVertexTextures,
  9312. maxTextureSize: maxTextureSize,
  9313. maxCubemapSize: maxCubemapSize,
  9314. maxAttributes: maxAttributes,
  9315. maxVertexUniforms: maxVertexUniforms,
  9316. maxVaryings: maxVaryings,
  9317. maxFragmentUniforms: maxFragmentUniforms,
  9318. vertexTextures: vertexTextures,
  9319. floatFragmentTextures: floatFragmentTextures,
  9320. floatVertexTextures: floatVertexTextures,
  9321. maxSamples: maxSamples
  9322. };
  9323. }
  9324. function WebGLClipping(properties) {
  9325. const scope = this;
  9326. let globalState = null,
  9327. numGlobalPlanes = 0,
  9328. localClippingEnabled = false,
  9329. renderingShadows = false;
  9330. const plane = new Plane(),
  9331. viewNormalMatrix = new Matrix3(),
  9332. uniform = {
  9333. value: null,
  9334. needsUpdate: false
  9335. };
  9336. this.uniform = uniform;
  9337. this.numPlanes = 0;
  9338. this.numIntersection = 0;
  9339. this.init = function (planes, enableLocalClipping, camera) {
  9340. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9341. // run another frame in order to reset the state:
  9342. numGlobalPlanes !== 0 || localClippingEnabled;
  9343. localClippingEnabled = enableLocalClipping;
  9344. globalState = projectPlanes(planes, camera, 0);
  9345. numGlobalPlanes = planes.length;
  9346. return enabled;
  9347. };
  9348. this.beginShadows = function () {
  9349. renderingShadows = true;
  9350. projectPlanes(null);
  9351. };
  9352. this.endShadows = function () {
  9353. renderingShadows = false;
  9354. resetGlobalState();
  9355. };
  9356. this.setState = function (material, camera, useCache) {
  9357. const planes = material.clippingPlanes,
  9358. clipIntersection = material.clipIntersection,
  9359. clipShadows = material.clipShadows;
  9360. const materialProperties = properties.get(material);
  9361. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9362. // there's no local clipping
  9363. if (renderingShadows) {
  9364. // there's no global clipping
  9365. projectPlanes(null);
  9366. } else {
  9367. resetGlobalState();
  9368. }
  9369. } else {
  9370. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9371. lGlobal = nGlobal * 4;
  9372. let dstArray = materialProperties.clippingState || null;
  9373. uniform.value = dstArray; // ensure unique state
  9374. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9375. for (let i = 0; i !== lGlobal; ++i) {
  9376. dstArray[i] = globalState[i];
  9377. }
  9378. materialProperties.clippingState = dstArray;
  9379. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9380. this.numPlanes += nGlobal;
  9381. }
  9382. };
  9383. function resetGlobalState() {
  9384. if (uniform.value !== globalState) {
  9385. uniform.value = globalState;
  9386. uniform.needsUpdate = numGlobalPlanes > 0;
  9387. }
  9388. scope.numPlanes = numGlobalPlanes;
  9389. scope.numIntersection = 0;
  9390. }
  9391. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9392. const nPlanes = planes !== null ? planes.length : 0;
  9393. let dstArray = null;
  9394. if (nPlanes !== 0) {
  9395. dstArray = uniform.value;
  9396. if (skipTransform !== true || dstArray === null) {
  9397. const flatSize = dstOffset + nPlanes * 4,
  9398. viewMatrix = camera.matrixWorldInverse;
  9399. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9400. if (dstArray === null || dstArray.length < flatSize) {
  9401. dstArray = new Float32Array(flatSize);
  9402. }
  9403. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9404. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9405. plane.normal.toArray(dstArray, i4);
  9406. dstArray[i4 + 3] = plane.constant;
  9407. }
  9408. }
  9409. uniform.value = dstArray;
  9410. uniform.needsUpdate = true;
  9411. }
  9412. scope.numPlanes = nPlanes;
  9413. scope.numIntersection = 0;
  9414. return dstArray;
  9415. }
  9416. }
  9417. function WebGLCubeMaps(renderer) {
  9418. let cubemaps = new WeakMap();
  9419. function mapTextureMapping(texture, mapping) {
  9420. if (mapping === EquirectangularReflectionMapping) {
  9421. texture.mapping = CubeReflectionMapping;
  9422. } else if (mapping === EquirectangularRefractionMapping) {
  9423. texture.mapping = CubeRefractionMapping;
  9424. }
  9425. return texture;
  9426. }
  9427. function get(texture) {
  9428. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9429. const mapping = texture.mapping;
  9430. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9431. if (cubemaps.has(texture)) {
  9432. const cubemap = cubemaps.get(texture).texture;
  9433. return mapTextureMapping(cubemap, texture.mapping);
  9434. } else {
  9435. const image = texture.image;
  9436. if (image && image.height > 0) {
  9437. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9438. renderTarget.fromEquirectangularTexture(renderer, texture);
  9439. cubemaps.set(texture, renderTarget);
  9440. texture.addEventListener('dispose', onTextureDispose);
  9441. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9442. } else {
  9443. // image not yet ready. try the conversion next frame
  9444. return null;
  9445. }
  9446. }
  9447. }
  9448. }
  9449. return texture;
  9450. }
  9451. function onTextureDispose(event) {
  9452. const texture = event.target;
  9453. texture.removeEventListener('dispose', onTextureDispose);
  9454. const cubemap = cubemaps.get(texture);
  9455. if (cubemap !== undefined) {
  9456. cubemaps.delete(texture);
  9457. cubemap.dispose();
  9458. }
  9459. }
  9460. function dispose() {
  9461. cubemaps = new WeakMap();
  9462. }
  9463. return {
  9464. get: get,
  9465. dispose: dispose
  9466. };
  9467. }
  9468. class OrthographicCamera extends Camera {
  9469. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9470. super();
  9471. this.isOrthographicCamera = true;
  9472. this.type = 'OrthographicCamera';
  9473. this.zoom = 1;
  9474. this.view = null;
  9475. this.left = left;
  9476. this.right = right;
  9477. this.top = top;
  9478. this.bottom = bottom;
  9479. this.near = near;
  9480. this.far = far;
  9481. this.updateProjectionMatrix();
  9482. }
  9483. copy(source, recursive) {
  9484. super.copy(source, recursive);
  9485. this.left = source.left;
  9486. this.right = source.right;
  9487. this.top = source.top;
  9488. this.bottom = source.bottom;
  9489. this.near = source.near;
  9490. this.far = source.far;
  9491. this.zoom = source.zoom;
  9492. this.view = source.view === null ? null : Object.assign({}, source.view);
  9493. return this;
  9494. }
  9495. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9496. if (this.view === null) {
  9497. this.view = {
  9498. enabled: true,
  9499. fullWidth: 1,
  9500. fullHeight: 1,
  9501. offsetX: 0,
  9502. offsetY: 0,
  9503. width: 1,
  9504. height: 1
  9505. };
  9506. }
  9507. this.view.enabled = true;
  9508. this.view.fullWidth = fullWidth;
  9509. this.view.fullHeight = fullHeight;
  9510. this.view.offsetX = x;
  9511. this.view.offsetY = y;
  9512. this.view.width = width;
  9513. this.view.height = height;
  9514. this.updateProjectionMatrix();
  9515. }
  9516. clearViewOffset() {
  9517. if (this.view !== null) {
  9518. this.view.enabled = false;
  9519. }
  9520. this.updateProjectionMatrix();
  9521. }
  9522. updateProjectionMatrix() {
  9523. const dx = (this.right - this.left) / (2 * this.zoom);
  9524. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9525. const cx = (this.right + this.left) / 2;
  9526. const cy = (this.top + this.bottom) / 2;
  9527. let left = cx - dx;
  9528. let right = cx + dx;
  9529. let top = cy + dy;
  9530. let bottom = cy - dy;
  9531. if (this.view !== null && this.view.enabled) {
  9532. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9533. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9534. left += scaleW * this.view.offsetX;
  9535. right = left + scaleW * this.view.width;
  9536. top -= scaleH * this.view.offsetY;
  9537. bottom = top - scaleH * this.view.height;
  9538. }
  9539. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9540. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9541. }
  9542. toJSON(meta) {
  9543. const data = super.toJSON(meta);
  9544. data.object.zoom = this.zoom;
  9545. data.object.left = this.left;
  9546. data.object.right = this.right;
  9547. data.object.top = this.top;
  9548. data.object.bottom = this.bottom;
  9549. data.object.near = this.near;
  9550. data.object.far = this.far;
  9551. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9552. return data;
  9553. }
  9554. }
  9555. const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are
  9556. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9557. // geometric shadowing function. These sigma values squared must match the
  9558. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9559. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9560. // samples and exit early, but not recompile the shader.
  9561. const MAX_SAMPLES = 20;
  9562. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9563. const _clearColor = /*@__PURE__*/new Color();
  9564. let _oldTarget = null; // Golden Ratio
  9565. const PHI = (1 + Math.sqrt(5)) / 2;
  9566. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9567. // same axis), used as axis directions evenly spread on a sphere.
  9568. const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  9569. /**
  9570. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9571. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9572. * blur to be quickly accessed based on material roughness. It is packed into a
  9573. * special CubeUV format that allows us to perform custom interpolation so that
  9574. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9575. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9576. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9577. * higher roughness levels. In this way we maintain resolution to smoothly
  9578. * interpolate diffuse lighting while limiting sampling computation.
  9579. *
  9580. * Paper: Fast, Accurate Image-Based Lighting
  9581. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9582. */
  9583. class PMREMGenerator {
  9584. constructor(renderer) {
  9585. this._renderer = renderer;
  9586. this._pingPongRenderTarget = null;
  9587. this._lodMax = 0;
  9588. this._cubeSize = 0;
  9589. this._lodPlanes = [];
  9590. this._sizeLods = [];
  9591. this._sigmas = [];
  9592. this._blurMaterial = null;
  9593. this._cubemapMaterial = null;
  9594. this._equirectMaterial = null;
  9595. this._compileMaterial(this._blurMaterial);
  9596. }
  9597. /**
  9598. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9599. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9600. * in radians to be applied to the scene before PMREM generation. Optional near
  9601. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9602. * is placed at the origin).
  9603. */
  9604. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9605. _oldTarget = this._renderer.getRenderTarget();
  9606. this._setSize(256);
  9607. const cubeUVRenderTarget = this._allocateTargets();
  9608. cubeUVRenderTarget.depthBuffer = true;
  9609. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9610. if (sigma > 0) {
  9611. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9612. }
  9613. this._applyPMREM(cubeUVRenderTarget);
  9614. this._cleanup(cubeUVRenderTarget);
  9615. return cubeUVRenderTarget;
  9616. }
  9617. /**
  9618. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9619. * or HDR. The ideal input image size is 1k (1024 x 512),
  9620. * as this matches best with the 256 x 256 cubemap output.
  9621. */
  9622. fromEquirectangular(equirectangular, renderTarget = null) {
  9623. return this._fromTexture(equirectangular, renderTarget);
  9624. }
  9625. /**
  9626. * Generates a PMREM from an cubemap texture, which can be either LDR
  9627. * or HDR. The ideal input cube size is 256 x 256,
  9628. * as this matches best with the 256 x 256 cubemap output.
  9629. */
  9630. fromCubemap(cubemap, renderTarget = null) {
  9631. return this._fromTexture(cubemap, renderTarget);
  9632. }
  9633. /**
  9634. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9635. * your texture's network fetch for increased concurrency.
  9636. */
  9637. compileCubemapShader() {
  9638. if (this._cubemapMaterial === null) {
  9639. this._cubemapMaterial = _getCubemapMaterial();
  9640. this._compileMaterial(this._cubemapMaterial);
  9641. }
  9642. }
  9643. /**
  9644. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9645. * your texture's network fetch for increased concurrency.
  9646. */
  9647. compileEquirectangularShader() {
  9648. if (this._equirectMaterial === null) {
  9649. this._equirectMaterial = _getEquirectMaterial();
  9650. this._compileMaterial(this._equirectMaterial);
  9651. }
  9652. }
  9653. /**
  9654. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9655. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9656. * one of them will cause any others to also become unusable.
  9657. */
  9658. dispose() {
  9659. this._dispose();
  9660. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9661. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9662. } // private interface
  9663. _setSize(cubeSize) {
  9664. this._lodMax = Math.floor(Math.log2(cubeSize));
  9665. this._cubeSize = Math.pow(2, this._lodMax);
  9666. }
  9667. _dispose() {
  9668. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9669. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9670. for (let i = 0; i < this._lodPlanes.length; i++) {
  9671. this._lodPlanes[i].dispose();
  9672. }
  9673. }
  9674. _cleanup(outputTarget) {
  9675. this._renderer.setRenderTarget(_oldTarget);
  9676. outputTarget.scissorTest = false;
  9677. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9678. }
  9679. _fromTexture(texture, renderTarget) {
  9680. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9681. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9682. } else {
  9683. // Equirectangular
  9684. this._setSize(texture.image.width / 4);
  9685. }
  9686. _oldTarget = this._renderer.getRenderTarget();
  9687. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9688. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9689. this._applyPMREM(cubeUVRenderTarget);
  9690. this._cleanup(cubeUVRenderTarget);
  9691. return cubeUVRenderTarget;
  9692. }
  9693. _allocateTargets() {
  9694. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9695. const height = 4 * this._cubeSize;
  9696. const params = {
  9697. magFilter: LinearFilter,
  9698. minFilter: LinearFilter,
  9699. generateMipmaps: false,
  9700. type: HalfFloatType,
  9701. format: RGBAFormat,
  9702. encoding: LinearEncoding,
  9703. depthBuffer: false
  9704. };
  9705. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9706. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9707. if (this._pingPongRenderTarget !== null) {
  9708. this._dispose();
  9709. }
  9710. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9711. const {
  9712. _lodMax
  9713. } = this;
  9714. ({
  9715. sizeLods: this._sizeLods,
  9716. lodPlanes: this._lodPlanes,
  9717. sigmas: this._sigmas
  9718. } = _createPlanes(_lodMax));
  9719. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9720. }
  9721. return cubeUVRenderTarget;
  9722. }
  9723. _compileMaterial(material) {
  9724. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9725. this._renderer.compile(tmpMesh, _flatCamera);
  9726. }
  9727. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9728. const fov = 90;
  9729. const aspect = 1;
  9730. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9731. const upSign = [1, -1, 1, 1, 1, 1];
  9732. const forwardSign = [1, 1, 1, -1, -1, -1];
  9733. const renderer = this._renderer;
  9734. const originalAutoClear = renderer.autoClear;
  9735. const toneMapping = renderer.toneMapping;
  9736. renderer.getClearColor(_clearColor);
  9737. renderer.toneMapping = NoToneMapping;
  9738. renderer.autoClear = false;
  9739. const backgroundMaterial = new MeshBasicMaterial({
  9740. name: 'PMREM.Background',
  9741. side: BackSide,
  9742. depthWrite: false,
  9743. depthTest: false
  9744. });
  9745. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9746. let useSolidColor = false;
  9747. const background = scene.background;
  9748. if (background) {
  9749. if (background.isColor) {
  9750. backgroundMaterial.color.copy(background);
  9751. scene.background = null;
  9752. useSolidColor = true;
  9753. }
  9754. } else {
  9755. backgroundMaterial.color.copy(_clearColor);
  9756. useSolidColor = true;
  9757. }
  9758. for (let i = 0; i < 6; i++) {
  9759. const col = i % 3;
  9760. if (col === 0) {
  9761. cubeCamera.up.set(0, upSign[i], 0);
  9762. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9763. } else if (col === 1) {
  9764. cubeCamera.up.set(0, 0, upSign[i]);
  9765. cubeCamera.lookAt(0, forwardSign[i], 0);
  9766. } else {
  9767. cubeCamera.up.set(0, upSign[i], 0);
  9768. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9769. }
  9770. const size = this._cubeSize;
  9771. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9772. renderer.setRenderTarget(cubeUVRenderTarget);
  9773. if (useSolidColor) {
  9774. renderer.render(backgroundBox, cubeCamera);
  9775. }
  9776. renderer.render(scene, cubeCamera);
  9777. }
  9778. backgroundBox.geometry.dispose();
  9779. backgroundBox.material.dispose();
  9780. renderer.toneMapping = toneMapping;
  9781. renderer.autoClear = originalAutoClear;
  9782. scene.background = background;
  9783. }
  9784. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9785. const renderer = this._renderer;
  9786. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9787. if (isCubeTexture) {
  9788. if (this._cubemapMaterial === null) {
  9789. this._cubemapMaterial = _getCubemapMaterial();
  9790. }
  9791. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9792. } else {
  9793. if (this._equirectMaterial === null) {
  9794. this._equirectMaterial = _getEquirectMaterial();
  9795. }
  9796. }
  9797. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9798. const mesh = new Mesh(this._lodPlanes[0], material);
  9799. const uniforms = material.uniforms;
  9800. uniforms['envMap'].value = texture;
  9801. const size = this._cubeSize;
  9802. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9803. renderer.setRenderTarget(cubeUVRenderTarget);
  9804. renderer.render(mesh, _flatCamera);
  9805. }
  9806. _applyPMREM(cubeUVRenderTarget) {
  9807. const renderer = this._renderer;
  9808. const autoClear = renderer.autoClear;
  9809. renderer.autoClear = false;
  9810. for (let i = 1; i < this._lodPlanes.length; i++) {
  9811. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9812. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9813. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9814. }
  9815. renderer.autoClear = autoClear;
  9816. }
  9817. /**
  9818. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9819. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9820. * the blur latitudinally (around the poles), and then longitudinally (towards
  9821. * the poles) to approximate the orthogonally-separable blur. It is least
  9822. * accurate at the poles, but still does a decent job.
  9823. */
  9824. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9825. const pingPongRenderTarget = this._pingPongRenderTarget;
  9826. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9827. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9828. }
  9829. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9830. const renderer = this._renderer;
  9831. const blurMaterial = this._blurMaterial;
  9832. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9833. console.error('blur direction must be either latitudinal or longitudinal!');
  9834. } // Number of standard deviations at which to cut off the discrete approximation.
  9835. const STANDARD_DEVIATIONS = 3;
  9836. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9837. const blurUniforms = blurMaterial.uniforms;
  9838. const pixels = this._sizeLods[lodIn] - 1;
  9839. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9840. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9841. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9842. if (samples > MAX_SAMPLES) {
  9843. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9844. }
  9845. const weights = [];
  9846. let sum = 0;
  9847. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9848. const x = i / sigmaPixels;
  9849. const weight = Math.exp(-x * x / 2);
  9850. weights.push(weight);
  9851. if (i === 0) {
  9852. sum += weight;
  9853. } else if (i < samples) {
  9854. sum += 2 * weight;
  9855. }
  9856. }
  9857. for (let i = 0; i < weights.length; i++) {
  9858. weights[i] = weights[i] / sum;
  9859. }
  9860. blurUniforms['envMap'].value = targetIn.texture;
  9861. blurUniforms['samples'].value = samples;
  9862. blurUniforms['weights'].value = weights;
  9863. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9864. if (poleAxis) {
  9865. blurUniforms['poleAxis'].value = poleAxis;
  9866. }
  9867. const {
  9868. _lodMax
  9869. } = this;
  9870. blurUniforms['dTheta'].value = radiansPerPixel;
  9871. blurUniforms['mipInt'].value = _lodMax - lodIn;
  9872. const outputSize = this._sizeLods[lodOut];
  9873. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  9874. const y = 4 * (this._cubeSize - outputSize);
  9875. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9876. renderer.setRenderTarget(targetOut);
  9877. renderer.render(blurMesh, _flatCamera);
  9878. }
  9879. }
  9880. function _createPlanes(lodMax) {
  9881. const lodPlanes = [];
  9882. const sizeLods = [];
  9883. const sigmas = [];
  9884. let lod = lodMax;
  9885. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9886. for (let i = 0; i < totalLods; i++) {
  9887. const sizeLod = Math.pow(2, lod);
  9888. sizeLods.push(sizeLod);
  9889. let sigma = 1.0 / sizeLod;
  9890. if (i > lodMax - LOD_MIN) {
  9891. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  9892. } else if (i === 0) {
  9893. sigma = 0;
  9894. }
  9895. sigmas.push(sigma);
  9896. const texelSize = 1.0 / (sizeLod - 2);
  9897. const min = -texelSize;
  9898. const max = 1 + texelSize;
  9899. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9900. const cubeFaces = 6;
  9901. const vertices = 6;
  9902. const positionSize = 3;
  9903. const uvSize = 2;
  9904. const faceIndexSize = 1;
  9905. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9906. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9907. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9908. for (let face = 0; face < cubeFaces; face++) {
  9909. const x = face % 3 * 2 / 3 - 1;
  9910. const y = face > 2 ? 0 : -1;
  9911. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  9912. position.set(coordinates, positionSize * vertices * face);
  9913. uv.set(uv1, uvSize * vertices * face);
  9914. const fill = [face, face, face, face, face, face];
  9915. faceIndex.set(fill, faceIndexSize * vertices * face);
  9916. }
  9917. const planes = new BufferGeometry();
  9918. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9919. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9920. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9921. lodPlanes.push(planes);
  9922. if (lod > LOD_MIN) {
  9923. lod--;
  9924. }
  9925. }
  9926. return {
  9927. lodPlanes,
  9928. sizeLods,
  9929. sigmas
  9930. };
  9931. }
  9932. function _createRenderTarget(width, height, params) {
  9933. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  9934. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9935. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9936. cubeUVRenderTarget.scissorTest = true;
  9937. return cubeUVRenderTarget;
  9938. }
  9939. function _setViewport(target, x, y, width, height) {
  9940. target.viewport.set(x, y, width, height);
  9941. target.scissor.set(x, y, width, height);
  9942. }
  9943. function _getBlurShader(lodMax, width, height) {
  9944. const weights = new Float32Array(MAX_SAMPLES);
  9945. const poleAxis = new Vector3(0, 1, 0);
  9946. const shaderMaterial = new ShaderMaterial({
  9947. name: 'SphericalGaussianBlur',
  9948. defines: {
  9949. 'n': MAX_SAMPLES,
  9950. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9951. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9952. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  9953. },
  9954. uniforms: {
  9955. 'envMap': {
  9956. value: null
  9957. },
  9958. 'samples': {
  9959. value: 1
  9960. },
  9961. 'weights': {
  9962. value: weights
  9963. },
  9964. 'latitudinal': {
  9965. value: false
  9966. },
  9967. 'dTheta': {
  9968. value: 0
  9969. },
  9970. 'mipInt': {
  9971. value: 0
  9972. },
  9973. 'poleAxis': {
  9974. value: poleAxis
  9975. }
  9976. },
  9977. vertexShader: _getCommonVertexShader(),
  9978. fragmentShader:
  9979. /* glsl */
  9980. `
  9981. precision mediump float;
  9982. precision mediump int;
  9983. varying vec3 vOutputDirection;
  9984. uniform sampler2D envMap;
  9985. uniform int samples;
  9986. uniform float weights[ n ];
  9987. uniform bool latitudinal;
  9988. uniform float dTheta;
  9989. uniform float mipInt;
  9990. uniform vec3 poleAxis;
  9991. #define ENVMAP_TYPE_CUBE_UV
  9992. #include <cube_uv_reflection_fragment>
  9993. vec3 getSample( float theta, vec3 axis ) {
  9994. float cosTheta = cos( theta );
  9995. // Rodrigues' axis-angle rotation
  9996. vec3 sampleDirection = vOutputDirection * cosTheta
  9997. + cross( axis, vOutputDirection ) * sin( theta )
  9998. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9999. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10000. }
  10001. void main() {
  10002. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10003. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10004. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10005. }
  10006. axis = normalize( axis );
  10007. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10008. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10009. for ( int i = 1; i < n; i++ ) {
  10010. if ( i >= samples ) {
  10011. break;
  10012. }
  10013. float theta = dTheta * float( i );
  10014. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10015. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10016. }
  10017. }
  10018. `,
  10019. blending: NoBlending,
  10020. depthTest: false,
  10021. depthWrite: false
  10022. });
  10023. return shaderMaterial;
  10024. }
  10025. function _getEquirectMaterial() {
  10026. return new ShaderMaterial({
  10027. name: 'EquirectangularToCubeUV',
  10028. uniforms: {
  10029. 'envMap': {
  10030. value: null
  10031. }
  10032. },
  10033. vertexShader: _getCommonVertexShader(),
  10034. fragmentShader:
  10035. /* glsl */
  10036. `
  10037. precision mediump float;
  10038. precision mediump int;
  10039. varying vec3 vOutputDirection;
  10040. uniform sampler2D envMap;
  10041. #include <common>
  10042. void main() {
  10043. vec3 outputDirection = normalize( vOutputDirection );
  10044. vec2 uv = equirectUv( outputDirection );
  10045. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10046. }
  10047. `,
  10048. blending: NoBlending,
  10049. depthTest: false,
  10050. depthWrite: false
  10051. });
  10052. }
  10053. function _getCubemapMaterial() {
  10054. return new ShaderMaterial({
  10055. name: 'CubemapToCubeUV',
  10056. uniforms: {
  10057. 'envMap': {
  10058. value: null
  10059. },
  10060. 'flipEnvMap': {
  10061. value: -1
  10062. }
  10063. },
  10064. vertexShader: _getCommonVertexShader(),
  10065. fragmentShader:
  10066. /* glsl */
  10067. `
  10068. precision mediump float;
  10069. precision mediump int;
  10070. uniform float flipEnvMap;
  10071. varying vec3 vOutputDirection;
  10072. uniform samplerCube envMap;
  10073. void main() {
  10074. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10075. }
  10076. `,
  10077. blending: NoBlending,
  10078. depthTest: false,
  10079. depthWrite: false
  10080. });
  10081. }
  10082. function _getCommonVertexShader() {
  10083. return (
  10084. /* glsl */
  10085. `
  10086. precision mediump float;
  10087. precision mediump int;
  10088. attribute float faceIndex;
  10089. varying vec3 vOutputDirection;
  10090. // RH coordinate system; PMREM face-indexing convention
  10091. vec3 getDirection( vec2 uv, float face ) {
  10092. uv = 2.0 * uv - 1.0;
  10093. vec3 direction = vec3( uv, 1.0 );
  10094. if ( face == 0.0 ) {
  10095. direction = direction.zyx; // ( 1, v, u ) pos x
  10096. } else if ( face == 1.0 ) {
  10097. direction = direction.xzy;
  10098. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10099. } else if ( face == 2.0 ) {
  10100. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10101. } else if ( face == 3.0 ) {
  10102. direction = direction.zyx;
  10103. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10104. } else if ( face == 4.0 ) {
  10105. direction = direction.xzy;
  10106. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10107. } else if ( face == 5.0 ) {
  10108. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10109. }
  10110. return direction;
  10111. }
  10112. void main() {
  10113. vOutputDirection = getDirection( uv, faceIndex );
  10114. gl_Position = vec4( position, 1.0 );
  10115. }
  10116. `
  10117. );
  10118. }
  10119. function WebGLCubeUVMaps(renderer) {
  10120. let cubeUVmaps = new WeakMap();
  10121. let pmremGenerator = null;
  10122. function get(texture) {
  10123. if (texture && texture.isTexture) {
  10124. const mapping = texture.mapping;
  10125. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10126. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
  10127. if (isEquirectMap || isCubeMap) {
  10128. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10129. texture.needsPMREMUpdate = false;
  10130. let renderTarget = cubeUVmaps.get(texture);
  10131. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10132. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10133. cubeUVmaps.set(texture, renderTarget);
  10134. return renderTarget.texture;
  10135. } else {
  10136. if (cubeUVmaps.has(texture)) {
  10137. return cubeUVmaps.get(texture).texture;
  10138. } else {
  10139. const image = texture.image;
  10140. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10141. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10142. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10143. cubeUVmaps.set(texture, renderTarget);
  10144. texture.addEventListener('dispose', onTextureDispose);
  10145. return renderTarget.texture;
  10146. } else {
  10147. // image not yet ready. try the conversion next frame
  10148. return null;
  10149. }
  10150. }
  10151. }
  10152. }
  10153. }
  10154. return texture;
  10155. }
  10156. function isCubeTextureComplete(image) {
  10157. let count = 0;
  10158. const length = 6;
  10159. for (let i = 0; i < length; i++) {
  10160. if (image[i] !== undefined) count++;
  10161. }
  10162. return count === length;
  10163. }
  10164. function onTextureDispose(event) {
  10165. const texture = event.target;
  10166. texture.removeEventListener('dispose', onTextureDispose);
  10167. const cubemapUV = cubeUVmaps.get(texture);
  10168. if (cubemapUV !== undefined) {
  10169. cubeUVmaps.delete(texture);
  10170. cubemapUV.dispose();
  10171. }
  10172. }
  10173. function dispose() {
  10174. cubeUVmaps = new WeakMap();
  10175. if (pmremGenerator !== null) {
  10176. pmremGenerator.dispose();
  10177. pmremGenerator = null;
  10178. }
  10179. }
  10180. return {
  10181. get: get,
  10182. dispose: dispose
  10183. };
  10184. }
  10185. function WebGLExtensions(gl) {
  10186. const extensions = {};
  10187. function getExtension(name) {
  10188. if (extensions[name] !== undefined) {
  10189. return extensions[name];
  10190. }
  10191. let extension;
  10192. switch (name) {
  10193. case 'WEBGL_depth_texture':
  10194. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10195. break;
  10196. case 'EXT_texture_filter_anisotropic':
  10197. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10198. break;
  10199. case 'WEBGL_compressed_texture_s3tc':
  10200. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10201. break;
  10202. case 'WEBGL_compressed_texture_pvrtc':
  10203. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10204. break;
  10205. default:
  10206. extension = gl.getExtension(name);
  10207. }
  10208. extensions[name] = extension;
  10209. return extension;
  10210. }
  10211. return {
  10212. has: function (name) {
  10213. return getExtension(name) !== null;
  10214. },
  10215. init: function (capabilities) {
  10216. if (capabilities.isWebGL2) {
  10217. getExtension('EXT_color_buffer_float');
  10218. } else {
  10219. getExtension('WEBGL_depth_texture');
  10220. getExtension('OES_texture_float');
  10221. getExtension('OES_texture_half_float');
  10222. getExtension('OES_texture_half_float_linear');
  10223. getExtension('OES_standard_derivatives');
  10224. getExtension('OES_element_index_uint');
  10225. getExtension('OES_vertex_array_object');
  10226. getExtension('ANGLE_instanced_arrays');
  10227. }
  10228. getExtension('OES_texture_float_linear');
  10229. getExtension('EXT_color_buffer_half_float');
  10230. getExtension('WEBGL_multisampled_render_to_texture');
  10231. },
  10232. get: function (name) {
  10233. const extension = getExtension(name);
  10234. if (extension === null) {
  10235. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10236. }
  10237. return extension;
  10238. }
  10239. };
  10240. }
  10241. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10242. const geometries = {};
  10243. const wireframeAttributes = new WeakMap();
  10244. function onGeometryDispose(event) {
  10245. const geometry = event.target;
  10246. if (geometry.index !== null) {
  10247. attributes.remove(geometry.index);
  10248. }
  10249. for (const name in geometry.attributes) {
  10250. attributes.remove(geometry.attributes[name]);
  10251. }
  10252. geometry.removeEventListener('dispose', onGeometryDispose);
  10253. delete geometries[geometry.id];
  10254. const attribute = wireframeAttributes.get(geometry);
  10255. if (attribute) {
  10256. attributes.remove(attribute);
  10257. wireframeAttributes.delete(geometry);
  10258. }
  10259. bindingStates.releaseStatesOfGeometry(geometry);
  10260. if (geometry.isInstancedBufferGeometry === true) {
  10261. delete geometry._maxInstanceCount;
  10262. } //
  10263. info.memory.geometries--;
  10264. }
  10265. function get(object, geometry) {
  10266. if (geometries[geometry.id] === true) return geometry;
  10267. geometry.addEventListener('dispose', onGeometryDispose);
  10268. geometries[geometry.id] = true;
  10269. info.memory.geometries++;
  10270. return geometry;
  10271. }
  10272. function update(geometry) {
  10273. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10274. for (const name in geometryAttributes) {
  10275. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10276. } // morph targets
  10277. const morphAttributes = geometry.morphAttributes;
  10278. for (const name in morphAttributes) {
  10279. const array = morphAttributes[name];
  10280. for (let i = 0, l = array.length; i < l; i++) {
  10281. attributes.update(array[i], gl.ARRAY_BUFFER);
  10282. }
  10283. }
  10284. }
  10285. function updateWireframeAttribute(geometry) {
  10286. const indices = [];
  10287. const geometryIndex = geometry.index;
  10288. const geometryPosition = geometry.attributes.position;
  10289. let version = 0;
  10290. if (geometryIndex !== null) {
  10291. const array = geometryIndex.array;
  10292. version = geometryIndex.version;
  10293. for (let i = 0, l = array.length; i < l; i += 3) {
  10294. const a = array[i + 0];
  10295. const b = array[i + 1];
  10296. const c = array[i + 2];
  10297. indices.push(a, b, b, c, c, a);
  10298. }
  10299. } else {
  10300. const array = geometryPosition.array;
  10301. version = geometryPosition.version;
  10302. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10303. const a = i + 0;
  10304. const b = i + 1;
  10305. const c = i + 2;
  10306. indices.push(a, b, b, c, c, a);
  10307. }
  10308. }
  10309. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10310. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10311. //
  10312. const previousAttribute = wireframeAttributes.get(geometry);
  10313. if (previousAttribute) attributes.remove(previousAttribute); //
  10314. wireframeAttributes.set(geometry, attribute);
  10315. }
  10316. function getWireframeAttribute(geometry) {
  10317. const currentAttribute = wireframeAttributes.get(geometry);
  10318. if (currentAttribute) {
  10319. const geometryIndex = geometry.index;
  10320. if (geometryIndex !== null) {
  10321. // if the attribute is obsolete, create a new one
  10322. if (currentAttribute.version < geometryIndex.version) {
  10323. updateWireframeAttribute(geometry);
  10324. }
  10325. }
  10326. } else {
  10327. updateWireframeAttribute(geometry);
  10328. }
  10329. return wireframeAttributes.get(geometry);
  10330. }
  10331. return {
  10332. get: get,
  10333. update: update,
  10334. getWireframeAttribute: getWireframeAttribute
  10335. };
  10336. }
  10337. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10338. const isWebGL2 = capabilities.isWebGL2;
  10339. let mode;
  10340. function setMode(value) {
  10341. mode = value;
  10342. }
  10343. let type, bytesPerElement;
  10344. function setIndex(value) {
  10345. type = value.type;
  10346. bytesPerElement = value.bytesPerElement;
  10347. }
  10348. function render(start, count) {
  10349. gl.drawElements(mode, count, type, start * bytesPerElement);
  10350. info.update(count, mode, 1);
  10351. }
  10352. function renderInstances(start, count, primcount) {
  10353. if (primcount === 0) return;
  10354. let extension, methodName;
  10355. if (isWebGL2) {
  10356. extension = gl;
  10357. methodName = 'drawElementsInstanced';
  10358. } else {
  10359. extension = extensions.get('ANGLE_instanced_arrays');
  10360. methodName = 'drawElementsInstancedANGLE';
  10361. if (extension === null) {
  10362. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10363. return;
  10364. }
  10365. }
  10366. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10367. info.update(count, mode, primcount);
  10368. } //
  10369. this.setMode = setMode;
  10370. this.setIndex = setIndex;
  10371. this.render = render;
  10372. this.renderInstances = renderInstances;
  10373. }
  10374. function WebGLInfo(gl) {
  10375. const memory = {
  10376. geometries: 0,
  10377. textures: 0
  10378. };
  10379. const render = {
  10380. frame: 0,
  10381. calls: 0,
  10382. triangles: 0,
  10383. points: 0,
  10384. lines: 0
  10385. };
  10386. function update(count, mode, instanceCount) {
  10387. render.calls++;
  10388. switch (mode) {
  10389. case gl.TRIANGLES:
  10390. render.triangles += instanceCount * (count / 3);
  10391. break;
  10392. case gl.LINES:
  10393. render.lines += instanceCount * (count / 2);
  10394. break;
  10395. case gl.LINE_STRIP:
  10396. render.lines += instanceCount * (count - 1);
  10397. break;
  10398. case gl.LINE_LOOP:
  10399. render.lines += instanceCount * count;
  10400. break;
  10401. case gl.POINTS:
  10402. render.points += instanceCount * count;
  10403. break;
  10404. default:
  10405. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10406. break;
  10407. }
  10408. }
  10409. function reset() {
  10410. render.frame++;
  10411. render.calls = 0;
  10412. render.triangles = 0;
  10413. render.points = 0;
  10414. render.lines = 0;
  10415. }
  10416. return {
  10417. memory: memory,
  10418. render: render,
  10419. programs: null,
  10420. autoReset: true,
  10421. reset: reset,
  10422. update: update
  10423. };
  10424. }
  10425. function numericalSort(a, b) {
  10426. return a[0] - b[0];
  10427. }
  10428. function absNumericalSort(a, b) {
  10429. return Math.abs(b[1]) - Math.abs(a[1]);
  10430. }
  10431. function WebGLMorphtargets(gl, capabilities, textures) {
  10432. const influencesList = {};
  10433. const morphInfluences = new Float32Array(8);
  10434. const morphTextures = new WeakMap();
  10435. const morph = new Vector4();
  10436. const workInfluences = [];
  10437. for (let i = 0; i < 8; i++) {
  10438. workInfluences[i] = [i, 0];
  10439. }
  10440. function update(object, geometry, material, program) {
  10441. const objectInfluences = object.morphTargetInfluences;
  10442. if (capabilities.isWebGL2 === true) {
  10443. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10444. // into an array of data textures. Each layer represents a single morph target.
  10445. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10446. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10447. let entry = morphTextures.get(geometry);
  10448. if (entry === undefined || entry.count !== morphTargetsCount) {
  10449. if (entry !== undefined) entry.texture.dispose();
  10450. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10451. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10452. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10453. const morphTargets = geometry.morphAttributes.position || [];
  10454. const morphNormals = geometry.morphAttributes.normal || [];
  10455. const morphColors = geometry.morphAttributes.color || [];
  10456. let vertexDataCount = 0;
  10457. if (hasMorphPosition === true) vertexDataCount = 1;
  10458. if (hasMorphNormals === true) vertexDataCount = 2;
  10459. if (hasMorphColors === true) vertexDataCount = 3;
  10460. let width = geometry.attributes.position.count * vertexDataCount;
  10461. let height = 1;
  10462. if (width > capabilities.maxTextureSize) {
  10463. height = Math.ceil(width / capabilities.maxTextureSize);
  10464. width = capabilities.maxTextureSize;
  10465. }
  10466. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10467. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10468. texture.type = FloatType;
  10469. texture.needsUpdate = true; // fill buffer
  10470. const vertexDataStride = vertexDataCount * 4;
  10471. for (let i = 0; i < morphTargetsCount; i++) {
  10472. const morphTarget = morphTargets[i];
  10473. const morphNormal = morphNormals[i];
  10474. const morphColor = morphColors[i];
  10475. const offset = width * height * 4 * i;
  10476. for (let j = 0; j < morphTarget.count; j++) {
  10477. const stride = j * vertexDataStride;
  10478. if (hasMorphPosition === true) {
  10479. morph.fromBufferAttribute(morphTarget, j);
  10480. buffer[offset + stride + 0] = morph.x;
  10481. buffer[offset + stride + 1] = morph.y;
  10482. buffer[offset + stride + 2] = morph.z;
  10483. buffer[offset + stride + 3] = 0;
  10484. }
  10485. if (hasMorphNormals === true) {
  10486. morph.fromBufferAttribute(morphNormal, j);
  10487. buffer[offset + stride + 4] = morph.x;
  10488. buffer[offset + stride + 5] = morph.y;
  10489. buffer[offset + stride + 6] = morph.z;
  10490. buffer[offset + stride + 7] = 0;
  10491. }
  10492. if (hasMorphColors === true) {
  10493. morph.fromBufferAttribute(morphColor, j);
  10494. buffer[offset + stride + 8] = morph.x;
  10495. buffer[offset + stride + 9] = morph.y;
  10496. buffer[offset + stride + 10] = morph.z;
  10497. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10498. }
  10499. }
  10500. }
  10501. entry = {
  10502. count: morphTargetsCount,
  10503. texture: texture,
  10504. size: new Vector2(width, height)
  10505. };
  10506. morphTextures.set(geometry, entry);
  10507. function disposeTexture() {
  10508. texture.dispose();
  10509. morphTextures.delete(geometry);
  10510. geometry.removeEventListener('dispose', disposeTexture);
  10511. }
  10512. geometry.addEventListener('dispose', disposeTexture);
  10513. } //
  10514. let morphInfluencesSum = 0;
  10515. for (let i = 0; i < objectInfluences.length; i++) {
  10516. morphInfluencesSum += objectInfluences[i];
  10517. }
  10518. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10519. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10520. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10521. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10522. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10523. } else {
  10524. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10525. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10526. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10527. let influences = influencesList[geometry.id];
  10528. if (influences === undefined || influences.length !== length) {
  10529. // initialise list
  10530. influences = [];
  10531. for (let i = 0; i < length; i++) {
  10532. influences[i] = [i, 0];
  10533. }
  10534. influencesList[geometry.id] = influences;
  10535. } // Collect influences
  10536. for (let i = 0; i < length; i++) {
  10537. const influence = influences[i];
  10538. influence[0] = i;
  10539. influence[1] = objectInfluences[i];
  10540. }
  10541. influences.sort(absNumericalSort);
  10542. for (let i = 0; i < 8; i++) {
  10543. if (i < length && influences[i][1]) {
  10544. workInfluences[i][0] = influences[i][0];
  10545. workInfluences[i][1] = influences[i][1];
  10546. } else {
  10547. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10548. workInfluences[i][1] = 0;
  10549. }
  10550. }
  10551. workInfluences.sort(numericalSort);
  10552. const morphTargets = geometry.morphAttributes.position;
  10553. const morphNormals = geometry.morphAttributes.normal;
  10554. let morphInfluencesSum = 0;
  10555. for (let i = 0; i < 8; i++) {
  10556. const influence = workInfluences[i];
  10557. const index = influence[0];
  10558. const value = influence[1];
  10559. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10560. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10561. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10562. }
  10563. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10564. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10565. }
  10566. morphInfluences[i] = value;
  10567. morphInfluencesSum += value;
  10568. } else {
  10569. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10570. geometry.deleteAttribute('morphTarget' + i);
  10571. }
  10572. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10573. geometry.deleteAttribute('morphNormal' + i);
  10574. }
  10575. morphInfluences[i] = 0;
  10576. }
  10577. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10578. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10579. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10580. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10581. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10582. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10583. }
  10584. }
  10585. return {
  10586. update: update
  10587. };
  10588. }
  10589. function WebGLObjects(gl, geometries, attributes, info) {
  10590. let updateMap = new WeakMap();
  10591. function update(object) {
  10592. const frame = info.render.frame;
  10593. const geometry = object.geometry;
  10594. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10595. if (updateMap.get(buffergeometry) !== frame) {
  10596. geometries.update(buffergeometry);
  10597. updateMap.set(buffergeometry, frame);
  10598. }
  10599. if (object.isInstancedMesh) {
  10600. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10601. object.addEventListener('dispose', onInstancedMeshDispose);
  10602. }
  10603. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10604. if (object.instanceColor !== null) {
  10605. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10606. }
  10607. }
  10608. return buffergeometry;
  10609. }
  10610. function dispose() {
  10611. updateMap = new WeakMap();
  10612. }
  10613. function onInstancedMeshDispose(event) {
  10614. const instancedMesh = event.target;
  10615. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10616. attributes.remove(instancedMesh.instanceMatrix);
  10617. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10618. }
  10619. return {
  10620. update: update,
  10621. dispose: dispose
  10622. };
  10623. }
  10624. /**
  10625. * Uniforms of a program.
  10626. * Those form a tree structure with a special top-level container for the root,
  10627. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10628. *
  10629. *
  10630. * Properties of inner nodes including the top-level container:
  10631. *
  10632. * .seq - array of nested uniforms
  10633. * .map - nested uniforms by name
  10634. *
  10635. *
  10636. * Methods of all nodes except the top-level container:
  10637. *
  10638. * .setValue( gl, value, [textures] )
  10639. *
  10640. * uploads a uniform value(s)
  10641. * the 'textures' parameter is needed for sampler uniforms
  10642. *
  10643. *
  10644. * Static methods of the top-level container (textures factorizations):
  10645. *
  10646. * .upload( gl, seq, values, textures )
  10647. *
  10648. * sets uniforms in 'seq' to 'values[id].value'
  10649. *
  10650. * .seqWithValue( seq, values ) : filteredSeq
  10651. *
  10652. * filters 'seq' entries with corresponding entry in values
  10653. *
  10654. *
  10655. * Methods of the top-level container (textures factorizations):
  10656. *
  10657. * .setValue( gl, name, value, textures )
  10658. *
  10659. * sets uniform with name 'name' to 'value'
  10660. *
  10661. * .setOptional( gl, obj, prop )
  10662. *
  10663. * like .set for an optional property of the object
  10664. *
  10665. */
  10666. const emptyTexture = /*@__PURE__*/new Texture();
  10667. const emptyArrayTexture = /*@__PURE__*/new DataArrayTexture();
  10668. const empty3dTexture = /*@__PURE__*/new Data3DTexture();
  10669. const emptyCubeTexture = /*@__PURE__*/new CubeTexture(); // --- Utilities ---
  10670. // Array Caches (provide typed arrays for temporary by size)
  10671. const arrayCacheF32 = [];
  10672. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10673. const mat4array = new Float32Array(16);
  10674. const mat3array = new Float32Array(9);
  10675. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10676. function flatten(array, nBlocks, blockSize) {
  10677. const firstElem = array[0];
  10678. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10679. // see http://jacksondunstan.com/articles/983
  10680. const n = nBlocks * blockSize;
  10681. let r = arrayCacheF32[n];
  10682. if (r === undefined) {
  10683. r = new Float32Array(n);
  10684. arrayCacheF32[n] = r;
  10685. }
  10686. if (nBlocks !== 0) {
  10687. firstElem.toArray(r, 0);
  10688. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10689. offset += blockSize;
  10690. array[i].toArray(r, offset);
  10691. }
  10692. }
  10693. return r;
  10694. }
  10695. function arraysEqual(a, b) {
  10696. if (a.length !== b.length) return false;
  10697. for (let i = 0, l = a.length; i < l; i++) {
  10698. if (a[i] !== b[i]) return false;
  10699. }
  10700. return true;
  10701. }
  10702. function copyArray(a, b) {
  10703. for (let i = 0, l = b.length; i < l; i++) {
  10704. a[i] = b[i];
  10705. }
  10706. } // Texture unit allocation
  10707. function allocTexUnits(textures, n) {
  10708. let r = arrayCacheI32[n];
  10709. if (r === undefined) {
  10710. r = new Int32Array(n);
  10711. arrayCacheI32[n] = r;
  10712. }
  10713. for (let i = 0; i !== n; ++i) {
  10714. r[i] = textures.allocateTextureUnit();
  10715. }
  10716. return r;
  10717. } // --- Setters ---
  10718. // Note: Defining these methods externally, because they come in a bunch
  10719. // and this way their names minify.
  10720. // Single scalar
  10721. function setValueV1f(gl, v) {
  10722. const cache = this.cache;
  10723. if (cache[0] === v) return;
  10724. gl.uniform1f(this.addr, v);
  10725. cache[0] = v;
  10726. } // Single float vector (from flat array or THREE.VectorN)
  10727. function setValueV2f(gl, v) {
  10728. const cache = this.cache;
  10729. if (v.x !== undefined) {
  10730. if (cache[0] !== v.x || cache[1] !== v.y) {
  10731. gl.uniform2f(this.addr, v.x, v.y);
  10732. cache[0] = v.x;
  10733. cache[1] = v.y;
  10734. }
  10735. } else {
  10736. if (arraysEqual(cache, v)) return;
  10737. gl.uniform2fv(this.addr, v);
  10738. copyArray(cache, v);
  10739. }
  10740. }
  10741. function setValueV3f(gl, v) {
  10742. const cache = this.cache;
  10743. if (v.x !== undefined) {
  10744. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10745. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10746. cache[0] = v.x;
  10747. cache[1] = v.y;
  10748. cache[2] = v.z;
  10749. }
  10750. } else if (v.r !== undefined) {
  10751. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10752. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10753. cache[0] = v.r;
  10754. cache[1] = v.g;
  10755. cache[2] = v.b;
  10756. }
  10757. } else {
  10758. if (arraysEqual(cache, v)) return;
  10759. gl.uniform3fv(this.addr, v);
  10760. copyArray(cache, v);
  10761. }
  10762. }
  10763. function setValueV4f(gl, v) {
  10764. const cache = this.cache;
  10765. if (v.x !== undefined) {
  10766. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10767. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10768. cache[0] = v.x;
  10769. cache[1] = v.y;
  10770. cache[2] = v.z;
  10771. cache[3] = v.w;
  10772. }
  10773. } else {
  10774. if (arraysEqual(cache, v)) return;
  10775. gl.uniform4fv(this.addr, v);
  10776. copyArray(cache, v);
  10777. }
  10778. } // Single matrix (from flat array or THREE.MatrixN)
  10779. function setValueM2(gl, v) {
  10780. const cache = this.cache;
  10781. const elements = v.elements;
  10782. if (elements === undefined) {
  10783. if (arraysEqual(cache, v)) return;
  10784. gl.uniformMatrix2fv(this.addr, false, v);
  10785. copyArray(cache, v);
  10786. } else {
  10787. if (arraysEqual(cache, elements)) return;
  10788. mat2array.set(elements);
  10789. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10790. copyArray(cache, elements);
  10791. }
  10792. }
  10793. function setValueM3(gl, v) {
  10794. const cache = this.cache;
  10795. const elements = v.elements;
  10796. if (elements === undefined) {
  10797. if (arraysEqual(cache, v)) return;
  10798. gl.uniformMatrix3fv(this.addr, false, v);
  10799. copyArray(cache, v);
  10800. } else {
  10801. if (arraysEqual(cache, elements)) return;
  10802. mat3array.set(elements);
  10803. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10804. copyArray(cache, elements);
  10805. }
  10806. }
  10807. function setValueM4(gl, v) {
  10808. const cache = this.cache;
  10809. const elements = v.elements;
  10810. if (elements === undefined) {
  10811. if (arraysEqual(cache, v)) return;
  10812. gl.uniformMatrix4fv(this.addr, false, v);
  10813. copyArray(cache, v);
  10814. } else {
  10815. if (arraysEqual(cache, elements)) return;
  10816. mat4array.set(elements);
  10817. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10818. copyArray(cache, elements);
  10819. }
  10820. } // Single integer / boolean
  10821. function setValueV1i(gl, v) {
  10822. const cache = this.cache;
  10823. if (cache[0] === v) return;
  10824. gl.uniform1i(this.addr, v);
  10825. cache[0] = v;
  10826. } // Single integer / boolean vector (from flat array)
  10827. function setValueV2i(gl, v) {
  10828. const cache = this.cache;
  10829. if (arraysEqual(cache, v)) return;
  10830. gl.uniform2iv(this.addr, v);
  10831. copyArray(cache, v);
  10832. }
  10833. function setValueV3i(gl, v) {
  10834. const cache = this.cache;
  10835. if (arraysEqual(cache, v)) return;
  10836. gl.uniform3iv(this.addr, v);
  10837. copyArray(cache, v);
  10838. }
  10839. function setValueV4i(gl, v) {
  10840. const cache = this.cache;
  10841. if (arraysEqual(cache, v)) return;
  10842. gl.uniform4iv(this.addr, v);
  10843. copyArray(cache, v);
  10844. } // Single unsigned integer
  10845. function setValueV1ui(gl, v) {
  10846. const cache = this.cache;
  10847. if (cache[0] === v) return;
  10848. gl.uniform1ui(this.addr, v);
  10849. cache[0] = v;
  10850. } // Single unsigned integer vector (from flat array)
  10851. function setValueV2ui(gl, v) {
  10852. const cache = this.cache;
  10853. if (arraysEqual(cache, v)) return;
  10854. gl.uniform2uiv(this.addr, v);
  10855. copyArray(cache, v);
  10856. }
  10857. function setValueV3ui(gl, v) {
  10858. const cache = this.cache;
  10859. if (arraysEqual(cache, v)) return;
  10860. gl.uniform3uiv(this.addr, v);
  10861. copyArray(cache, v);
  10862. }
  10863. function setValueV4ui(gl, v) {
  10864. const cache = this.cache;
  10865. if (arraysEqual(cache, v)) return;
  10866. gl.uniform4uiv(this.addr, v);
  10867. copyArray(cache, v);
  10868. } // Single texture (2D / Cube)
  10869. function setValueT1(gl, v, textures) {
  10870. const cache = this.cache;
  10871. const unit = textures.allocateTextureUnit();
  10872. if (cache[0] !== unit) {
  10873. gl.uniform1i(this.addr, unit);
  10874. cache[0] = unit;
  10875. }
  10876. textures.setTexture2D(v || emptyTexture, unit);
  10877. }
  10878. function setValueT3D1(gl, v, textures) {
  10879. const cache = this.cache;
  10880. const unit = textures.allocateTextureUnit();
  10881. if (cache[0] !== unit) {
  10882. gl.uniform1i(this.addr, unit);
  10883. cache[0] = unit;
  10884. }
  10885. textures.setTexture3D(v || empty3dTexture, unit);
  10886. }
  10887. function setValueT6(gl, v, textures) {
  10888. const cache = this.cache;
  10889. const unit = textures.allocateTextureUnit();
  10890. if (cache[0] !== unit) {
  10891. gl.uniform1i(this.addr, unit);
  10892. cache[0] = unit;
  10893. }
  10894. textures.setTextureCube(v || emptyCubeTexture, unit);
  10895. }
  10896. function setValueT2DArray1(gl, v, textures) {
  10897. const cache = this.cache;
  10898. const unit = textures.allocateTextureUnit();
  10899. if (cache[0] !== unit) {
  10900. gl.uniform1i(this.addr, unit);
  10901. cache[0] = unit;
  10902. }
  10903. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  10904. } // Helper to pick the right setter for the singular case
  10905. function getSingularSetter(type) {
  10906. switch (type) {
  10907. case 0x1406:
  10908. return setValueV1f;
  10909. // FLOAT
  10910. case 0x8b50:
  10911. return setValueV2f;
  10912. // _VEC2
  10913. case 0x8b51:
  10914. return setValueV3f;
  10915. // _VEC3
  10916. case 0x8b52:
  10917. return setValueV4f;
  10918. // _VEC4
  10919. case 0x8b5a:
  10920. return setValueM2;
  10921. // _MAT2
  10922. case 0x8b5b:
  10923. return setValueM3;
  10924. // _MAT3
  10925. case 0x8b5c:
  10926. return setValueM4;
  10927. // _MAT4
  10928. case 0x1404:
  10929. case 0x8b56:
  10930. return setValueV1i;
  10931. // INT, BOOL
  10932. case 0x8b53:
  10933. case 0x8b57:
  10934. return setValueV2i;
  10935. // _VEC2
  10936. case 0x8b54:
  10937. case 0x8b58:
  10938. return setValueV3i;
  10939. // _VEC3
  10940. case 0x8b55:
  10941. case 0x8b59:
  10942. return setValueV4i;
  10943. // _VEC4
  10944. case 0x1405:
  10945. return setValueV1ui;
  10946. // UINT
  10947. case 0x8dc6:
  10948. return setValueV2ui;
  10949. // _VEC2
  10950. case 0x8dc7:
  10951. return setValueV3ui;
  10952. // _VEC3
  10953. case 0x8dc8:
  10954. return setValueV4ui;
  10955. // _VEC4
  10956. case 0x8b5e: // SAMPLER_2D
  10957. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10958. case 0x8dca: // INT_SAMPLER_2D
  10959. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10960. case 0x8b62:
  10961. // SAMPLER_2D_SHADOW
  10962. return setValueT1;
  10963. case 0x8b5f: // SAMPLER_3D
  10964. case 0x8dcb: // INT_SAMPLER_3D
  10965. case 0x8dd3:
  10966. // UNSIGNED_INT_SAMPLER_3D
  10967. return setValueT3D1;
  10968. case 0x8b60: // SAMPLER_CUBE
  10969. case 0x8dcc: // INT_SAMPLER_CUBE
  10970. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10971. case 0x8dc5:
  10972. // SAMPLER_CUBE_SHADOW
  10973. return setValueT6;
  10974. case 0x8dc1: // SAMPLER_2D_ARRAY
  10975. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10976. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10977. case 0x8dc4:
  10978. // SAMPLER_2D_ARRAY_SHADOW
  10979. return setValueT2DArray1;
  10980. }
  10981. } // Array of scalars
  10982. function setValueV1fArray(gl, v) {
  10983. gl.uniform1fv(this.addr, v);
  10984. } // Array of vectors (from flat array or array of THREE.VectorN)
  10985. function setValueV2fArray(gl, v) {
  10986. const data = flatten(v, this.size, 2);
  10987. gl.uniform2fv(this.addr, data);
  10988. }
  10989. function setValueV3fArray(gl, v) {
  10990. const data = flatten(v, this.size, 3);
  10991. gl.uniform3fv(this.addr, data);
  10992. }
  10993. function setValueV4fArray(gl, v) {
  10994. const data = flatten(v, this.size, 4);
  10995. gl.uniform4fv(this.addr, data);
  10996. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10997. function setValueM2Array(gl, v) {
  10998. const data = flatten(v, this.size, 4);
  10999. gl.uniformMatrix2fv(this.addr, false, data);
  11000. }
  11001. function setValueM3Array(gl, v) {
  11002. const data = flatten(v, this.size, 9);
  11003. gl.uniformMatrix3fv(this.addr, false, data);
  11004. }
  11005. function setValueM4Array(gl, v) {
  11006. const data = flatten(v, this.size, 16);
  11007. gl.uniformMatrix4fv(this.addr, false, data);
  11008. } // Array of integer / boolean
  11009. function setValueV1iArray(gl, v) {
  11010. gl.uniform1iv(this.addr, v);
  11011. } // Array of integer / boolean vectors (from flat array)
  11012. function setValueV2iArray(gl, v) {
  11013. gl.uniform2iv(this.addr, v);
  11014. }
  11015. function setValueV3iArray(gl, v) {
  11016. gl.uniform3iv(this.addr, v);
  11017. }
  11018. function setValueV4iArray(gl, v) {
  11019. gl.uniform4iv(this.addr, v);
  11020. } // Array of unsigned integer
  11021. function setValueV1uiArray(gl, v) {
  11022. gl.uniform1uiv(this.addr, v);
  11023. } // Array of unsigned integer vectors (from flat array)
  11024. function setValueV2uiArray(gl, v) {
  11025. gl.uniform2uiv(this.addr, v);
  11026. }
  11027. function setValueV3uiArray(gl, v) {
  11028. gl.uniform3uiv(this.addr, v);
  11029. }
  11030. function setValueV4uiArray(gl, v) {
  11031. gl.uniform4uiv(this.addr, v);
  11032. } // Array of textures (2D / 3D / Cube / 2DArray)
  11033. function setValueT1Array(gl, v, textures) {
  11034. const n = v.length;
  11035. const units = allocTexUnits(textures, n);
  11036. gl.uniform1iv(this.addr, units);
  11037. for (let i = 0; i !== n; ++i) {
  11038. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  11039. }
  11040. }
  11041. function setValueT3DArray(gl, v, textures) {
  11042. const n = v.length;
  11043. const units = allocTexUnits(textures, n);
  11044. gl.uniform1iv(this.addr, units);
  11045. for (let i = 0; i !== n; ++i) {
  11046. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  11047. }
  11048. }
  11049. function setValueT6Array(gl, v, textures) {
  11050. const n = v.length;
  11051. const units = allocTexUnits(textures, n);
  11052. gl.uniform1iv(this.addr, units);
  11053. for (let i = 0; i !== n; ++i) {
  11054. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11055. }
  11056. }
  11057. function setValueT2DArrayArray(gl, v, textures) {
  11058. const n = v.length;
  11059. const units = allocTexUnits(textures, n);
  11060. gl.uniform1iv(this.addr, units);
  11061. for (let i = 0; i !== n; ++i) {
  11062. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11063. }
  11064. } // Helper to pick the right setter for a pure (bottom-level) array
  11065. function getPureArraySetter(type) {
  11066. switch (type) {
  11067. case 0x1406:
  11068. return setValueV1fArray;
  11069. // FLOAT
  11070. case 0x8b50:
  11071. return setValueV2fArray;
  11072. // _VEC2
  11073. case 0x8b51:
  11074. return setValueV3fArray;
  11075. // _VEC3
  11076. case 0x8b52:
  11077. return setValueV4fArray;
  11078. // _VEC4
  11079. case 0x8b5a:
  11080. return setValueM2Array;
  11081. // _MAT2
  11082. case 0x8b5b:
  11083. return setValueM3Array;
  11084. // _MAT3
  11085. case 0x8b5c:
  11086. return setValueM4Array;
  11087. // _MAT4
  11088. case 0x1404:
  11089. case 0x8b56:
  11090. return setValueV1iArray;
  11091. // INT, BOOL
  11092. case 0x8b53:
  11093. case 0x8b57:
  11094. return setValueV2iArray;
  11095. // _VEC2
  11096. case 0x8b54:
  11097. case 0x8b58:
  11098. return setValueV3iArray;
  11099. // _VEC3
  11100. case 0x8b55:
  11101. case 0x8b59:
  11102. return setValueV4iArray;
  11103. // _VEC4
  11104. case 0x1405:
  11105. return setValueV1uiArray;
  11106. // UINT
  11107. case 0x8dc6:
  11108. return setValueV2uiArray;
  11109. // _VEC2
  11110. case 0x8dc7:
  11111. return setValueV3uiArray;
  11112. // _VEC3
  11113. case 0x8dc8:
  11114. return setValueV4uiArray;
  11115. // _VEC4
  11116. case 0x8b5e: // SAMPLER_2D
  11117. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11118. case 0x8dca: // INT_SAMPLER_2D
  11119. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11120. case 0x8b62:
  11121. // SAMPLER_2D_SHADOW
  11122. return setValueT1Array;
  11123. case 0x8b5f: // SAMPLER_3D
  11124. case 0x8dcb: // INT_SAMPLER_3D
  11125. case 0x8dd3:
  11126. // UNSIGNED_INT_SAMPLER_3D
  11127. return setValueT3DArray;
  11128. case 0x8b60: // SAMPLER_CUBE
  11129. case 0x8dcc: // INT_SAMPLER_CUBE
  11130. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11131. case 0x8dc5:
  11132. // SAMPLER_CUBE_SHADOW
  11133. return setValueT6Array;
  11134. case 0x8dc1: // SAMPLER_2D_ARRAY
  11135. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11136. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11137. case 0x8dc4:
  11138. // SAMPLER_2D_ARRAY_SHADOW
  11139. return setValueT2DArrayArray;
  11140. }
  11141. } // --- Uniform Classes ---
  11142. class SingleUniform {
  11143. constructor(id, activeInfo, addr) {
  11144. this.id = id;
  11145. this.addr = addr;
  11146. this.cache = [];
  11147. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11148. }
  11149. }
  11150. class PureArrayUniform {
  11151. constructor(id, activeInfo, addr) {
  11152. this.id = id;
  11153. this.addr = addr;
  11154. this.cache = [];
  11155. this.size = activeInfo.size;
  11156. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11157. }
  11158. }
  11159. class StructuredUniform {
  11160. constructor(id) {
  11161. this.id = id;
  11162. this.seq = [];
  11163. this.map = {};
  11164. }
  11165. setValue(gl, value, textures) {
  11166. const seq = this.seq;
  11167. for (let i = 0, n = seq.length; i !== n; ++i) {
  11168. const u = seq[i];
  11169. u.setValue(gl, value[u.id], textures);
  11170. }
  11171. }
  11172. } // --- Top-level ---
  11173. // Parser - builds up the property tree from the path strings
  11174. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11175. // - the identifier (member name or array index)
  11176. // - followed by an optional right bracket (found when array index)
  11177. // - followed by an optional left bracket or dot (type of subscript)
  11178. //
  11179. // Note: These portions can be read in a non-overlapping fashion and
  11180. // allow straightforward parsing of the hierarchy that WebGL encodes
  11181. // in the uniform names.
  11182. function addUniform(container, uniformObject) {
  11183. container.seq.push(uniformObject);
  11184. container.map[uniformObject.id] = uniformObject;
  11185. }
  11186. function parseUniform(activeInfo, addr, container) {
  11187. const path = activeInfo.name,
  11188. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11189. RePathPart.lastIndex = 0;
  11190. while (true) {
  11191. const match = RePathPart.exec(path),
  11192. matchEnd = RePathPart.lastIndex;
  11193. let id = match[1];
  11194. const idIsIndex = match[2] === ']',
  11195. subscript = match[3];
  11196. if (idIsIndex) id = id | 0; // convert to integer
  11197. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11198. // bare name or "pure" bottom-level array "[0]" suffix
  11199. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11200. break;
  11201. } else {
  11202. // step into inner node / create it in case it doesn't exist
  11203. const map = container.map;
  11204. let next = map[id];
  11205. if (next === undefined) {
  11206. next = new StructuredUniform(id);
  11207. addUniform(container, next);
  11208. }
  11209. container = next;
  11210. }
  11211. }
  11212. } // Root Container
  11213. class WebGLUniforms {
  11214. constructor(gl, program) {
  11215. this.seq = [];
  11216. this.map = {};
  11217. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11218. for (let i = 0; i < n; ++i) {
  11219. const info = gl.getActiveUniform(program, i),
  11220. addr = gl.getUniformLocation(program, info.name);
  11221. parseUniform(info, addr, this);
  11222. }
  11223. }
  11224. setValue(gl, name, value, textures) {
  11225. const u = this.map[name];
  11226. if (u !== undefined) u.setValue(gl, value, textures);
  11227. }
  11228. setOptional(gl, object, name) {
  11229. const v = object[name];
  11230. if (v !== undefined) this.setValue(gl, name, v);
  11231. }
  11232. static upload(gl, seq, values, textures) {
  11233. for (let i = 0, n = seq.length; i !== n; ++i) {
  11234. const u = seq[i],
  11235. v = values[u.id];
  11236. if (v.needsUpdate !== false) {
  11237. // note: always updating when .needsUpdate is undefined
  11238. u.setValue(gl, v.value, textures);
  11239. }
  11240. }
  11241. }
  11242. static seqWithValue(seq, values) {
  11243. const r = [];
  11244. for (let i = 0, n = seq.length; i !== n; ++i) {
  11245. const u = seq[i];
  11246. if (u.id in values) r.push(u);
  11247. }
  11248. return r;
  11249. }
  11250. }
  11251. function WebGLShader(gl, type, string) {
  11252. const shader = gl.createShader(type);
  11253. gl.shaderSource(shader, string);
  11254. gl.compileShader(shader);
  11255. return shader;
  11256. }
  11257. let programIdCount = 0;
  11258. function handleSource(string, errorLine) {
  11259. const lines = string.split('\n');
  11260. const lines2 = [];
  11261. const from = Math.max(errorLine - 6, 0);
  11262. const to = Math.min(errorLine + 6, lines.length);
  11263. for (let i = from; i < to; i++) {
  11264. const line = i + 1;
  11265. lines2.push(`${line === errorLine ? '>' : ' '} ${line}: ${lines[i]}`);
  11266. }
  11267. return lines2.join('\n');
  11268. }
  11269. function getEncodingComponents(encoding) {
  11270. switch (encoding) {
  11271. case LinearEncoding:
  11272. return ['Linear', '( value )'];
  11273. case sRGBEncoding:
  11274. return ['sRGB', '( value )'];
  11275. default:
  11276. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11277. return ['Linear', '( value )'];
  11278. }
  11279. }
  11280. function getShaderErrors(gl, shader, type) {
  11281. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11282. const errors = gl.getShaderInfoLog(shader).trim();
  11283. if (status && errors === '') return '';
  11284. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11285. if (errorMatches) {
  11286. // --enable-privileged-webgl-extension
  11287. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11288. const errorLine = parseInt(errorMatches[1]);
  11289. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11290. } else {
  11291. return errors;
  11292. }
  11293. }
  11294. function getTexelEncodingFunction(functionName, encoding) {
  11295. const components = getEncodingComponents(encoding);
  11296. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11297. }
  11298. function getToneMappingFunction(functionName, toneMapping) {
  11299. let toneMappingName;
  11300. switch (toneMapping) {
  11301. case LinearToneMapping:
  11302. toneMappingName = 'Linear';
  11303. break;
  11304. case ReinhardToneMapping:
  11305. toneMappingName = 'Reinhard';
  11306. break;
  11307. case CineonToneMapping:
  11308. toneMappingName = 'OptimizedCineon';
  11309. break;
  11310. case ACESFilmicToneMapping:
  11311. toneMappingName = 'ACESFilmic';
  11312. break;
  11313. case CustomToneMapping:
  11314. toneMappingName = 'Custom';
  11315. break;
  11316. default:
  11317. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11318. toneMappingName = 'Linear';
  11319. }
  11320. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11321. }
  11322. function generateExtensions(parameters) {
  11323. const chunks = [parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11324. return chunks.filter(filterEmptyLine).join('\n');
  11325. }
  11326. function generateDefines(defines) {
  11327. const chunks = [];
  11328. for (const name in defines) {
  11329. const value = defines[name];
  11330. if (value === false) continue;
  11331. chunks.push('#define ' + name + ' ' + value);
  11332. }
  11333. return chunks.join('\n');
  11334. }
  11335. function fetchAttributeLocations(gl, program) {
  11336. const attributes = {};
  11337. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11338. for (let i = 0; i < n; i++) {
  11339. const info = gl.getActiveAttrib(program, i);
  11340. const name = info.name;
  11341. let locationSize = 1;
  11342. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11343. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11344. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11345. attributes[name] = {
  11346. type: info.type,
  11347. location: gl.getAttribLocation(program, name),
  11348. locationSize: locationSize
  11349. };
  11350. }
  11351. return attributes;
  11352. }
  11353. function filterEmptyLine(string) {
  11354. return string !== '';
  11355. }
  11356. function replaceLightNums(string, parameters) {
  11357. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11358. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11359. }
  11360. function replaceClippingPlaneNums(string, parameters) {
  11361. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11362. } // Resolve Includes
  11363. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11364. function resolveIncludes(string) {
  11365. return string.replace(includePattern, includeReplacer);
  11366. }
  11367. function includeReplacer(match, include) {
  11368. const string = ShaderChunk[include];
  11369. if (string === undefined) {
  11370. throw new Error('Can not resolve #include <' + include + '>');
  11371. }
  11372. return resolveIncludes(string);
  11373. } // Unroll Loops
  11374. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11375. function unrollLoops(string) {
  11376. return string.replace(unrollLoopPattern, loopReplacer);
  11377. }
  11378. function loopReplacer(match, start, end, snippet) {
  11379. let string = '';
  11380. for (let i = parseInt(start); i < parseInt(end); i++) {
  11381. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11382. }
  11383. return string;
  11384. } //
  11385. function generatePrecision(parameters) {
  11386. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11387. if (parameters.precision === 'highp') {
  11388. precisionstring += '\n#define HIGH_PRECISION';
  11389. } else if (parameters.precision === 'mediump') {
  11390. precisionstring += '\n#define MEDIUM_PRECISION';
  11391. } else if (parameters.precision === 'lowp') {
  11392. precisionstring += '\n#define LOW_PRECISION';
  11393. }
  11394. return precisionstring;
  11395. }
  11396. function generateShadowMapTypeDefine(parameters) {
  11397. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11398. if (parameters.shadowMapType === PCFShadowMap) {
  11399. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11400. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11401. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11402. } else if (parameters.shadowMapType === VSMShadowMap) {
  11403. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11404. }
  11405. return shadowMapTypeDefine;
  11406. }
  11407. function generateEnvMapTypeDefine(parameters) {
  11408. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11409. if (parameters.envMap) {
  11410. switch (parameters.envMapMode) {
  11411. case CubeReflectionMapping:
  11412. case CubeRefractionMapping:
  11413. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11414. break;
  11415. case CubeUVReflectionMapping:
  11416. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11417. break;
  11418. }
  11419. }
  11420. return envMapTypeDefine;
  11421. }
  11422. function generateEnvMapModeDefine(parameters) {
  11423. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11424. if (parameters.envMap) {
  11425. switch (parameters.envMapMode) {
  11426. case CubeRefractionMapping:
  11427. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11428. break;
  11429. }
  11430. }
  11431. return envMapModeDefine;
  11432. }
  11433. function generateEnvMapBlendingDefine(parameters) {
  11434. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11435. if (parameters.envMap) {
  11436. switch (parameters.combine) {
  11437. case MultiplyOperation:
  11438. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11439. break;
  11440. case MixOperation:
  11441. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11442. break;
  11443. case AddOperation:
  11444. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11445. break;
  11446. }
  11447. }
  11448. return envMapBlendingDefine;
  11449. }
  11450. function generateCubeUVSize(parameters) {
  11451. const imageHeight = parameters.envMapCubeUVHeight;
  11452. if (imageHeight === null) return null;
  11453. const maxMip = Math.log2(imageHeight) - 2;
  11454. const texelHeight = 1.0 / imageHeight;
  11455. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11456. return {
  11457. texelWidth,
  11458. texelHeight,
  11459. maxMip
  11460. };
  11461. }
  11462. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11463. // TODO Send this event to Three.js DevTools
  11464. // console.log( 'WebGLProgram', cacheKey );
  11465. const gl = renderer.getContext();
  11466. const defines = parameters.defines;
  11467. let vertexShader = parameters.vertexShader;
  11468. let fragmentShader = parameters.fragmentShader;
  11469. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11470. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11471. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11472. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11473. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11474. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11475. const customDefines = generateDefines(defines);
  11476. const program = gl.createProgram();
  11477. let prefixVertex, prefixFragment;
  11478. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11479. if (parameters.isRawShaderMaterial) {
  11480. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11481. if (prefixVertex.length > 0) {
  11482. prefixVertex += '\n';
  11483. }
  11484. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11485. if (prefixFragment.length > 0) {
  11486. prefixFragment += '\n';
  11487. }
  11488. } else {
  11489. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphColors && parameters.isWebGL2 ? '#define USE_MORPHCOLORS' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11490. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.iridescence ? '#define USE_IRIDESCENCE' : '', parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '', parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11491. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11492. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11493. }
  11494. vertexShader = resolveIncludes(vertexShader);
  11495. vertexShader = replaceLightNums(vertexShader, parameters);
  11496. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11497. fragmentShader = resolveIncludes(fragmentShader);
  11498. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11499. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11500. vertexShader = unrollLoops(vertexShader);
  11501. fragmentShader = unrollLoops(fragmentShader);
  11502. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11503. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11504. versionString = '#version 300 es\n';
  11505. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11506. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11507. }
  11508. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11509. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11510. // console.log( '*FRAGMENT*', fragmentGlsl );
  11511. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11512. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11513. gl.attachShader(program, glVertexShader);
  11514. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11515. if (parameters.index0AttributeName !== undefined) {
  11516. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11517. } else if (parameters.morphTargets === true) {
  11518. // programs with morphTargets displace position out of attribute 0
  11519. gl.bindAttribLocation(program, 0, 'position');
  11520. }
  11521. gl.linkProgram(program); // check for link errors
  11522. if (renderer.debug.checkShaderErrors) {
  11523. const programLog = gl.getProgramInfoLog(program).trim();
  11524. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11525. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11526. let runnable = true;
  11527. let haveDiagnostics = true;
  11528. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11529. runnable = false;
  11530. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11531. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11532. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11533. } else if (programLog !== '') {
  11534. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11535. } else if (vertexLog === '' || fragmentLog === '') {
  11536. haveDiagnostics = false;
  11537. }
  11538. if (haveDiagnostics) {
  11539. this.diagnostics = {
  11540. runnable: runnable,
  11541. programLog: programLog,
  11542. vertexShader: {
  11543. log: vertexLog,
  11544. prefix: prefixVertex
  11545. },
  11546. fragmentShader: {
  11547. log: fragmentLog,
  11548. prefix: prefixFragment
  11549. }
  11550. };
  11551. }
  11552. } // Clean up
  11553. // Crashes in iOS9 and iOS10. #18402
  11554. // gl.detachShader( program, glVertexShader );
  11555. // gl.detachShader( program, glFragmentShader );
  11556. gl.deleteShader(glVertexShader);
  11557. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11558. let cachedUniforms;
  11559. this.getUniforms = function () {
  11560. if (cachedUniforms === undefined) {
  11561. cachedUniforms = new WebGLUniforms(gl, program);
  11562. }
  11563. return cachedUniforms;
  11564. }; // set up caching for attribute locations
  11565. let cachedAttributes;
  11566. this.getAttributes = function () {
  11567. if (cachedAttributes === undefined) {
  11568. cachedAttributes = fetchAttributeLocations(gl, program);
  11569. }
  11570. return cachedAttributes;
  11571. }; // free resource
  11572. this.destroy = function () {
  11573. bindingStates.releaseStatesOfProgram(this);
  11574. gl.deleteProgram(program);
  11575. this.program = undefined;
  11576. }; //
  11577. this.name = parameters.shaderName;
  11578. this.id = programIdCount++;
  11579. this.cacheKey = cacheKey;
  11580. this.usedTimes = 1;
  11581. this.program = program;
  11582. this.vertexShader = glVertexShader;
  11583. this.fragmentShader = glFragmentShader;
  11584. return this;
  11585. }
  11586. let _id = 0;
  11587. class WebGLShaderCache {
  11588. constructor() {
  11589. this.shaderCache = new Map();
  11590. this.materialCache = new Map();
  11591. }
  11592. update(material) {
  11593. const vertexShader = material.vertexShader;
  11594. const fragmentShader = material.fragmentShader;
  11595. const vertexShaderStage = this._getShaderStage(vertexShader);
  11596. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11597. const materialShaders = this._getShaderCacheForMaterial(material);
  11598. if (materialShaders.has(vertexShaderStage) === false) {
  11599. materialShaders.add(vertexShaderStage);
  11600. vertexShaderStage.usedTimes++;
  11601. }
  11602. if (materialShaders.has(fragmentShaderStage) === false) {
  11603. materialShaders.add(fragmentShaderStage);
  11604. fragmentShaderStage.usedTimes++;
  11605. }
  11606. return this;
  11607. }
  11608. remove(material) {
  11609. const materialShaders = this.materialCache.get(material);
  11610. for (const shaderStage of materialShaders) {
  11611. shaderStage.usedTimes--;
  11612. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11613. }
  11614. this.materialCache.delete(material);
  11615. return this;
  11616. }
  11617. getVertexShaderID(material) {
  11618. return this._getShaderStage(material.vertexShader).id;
  11619. }
  11620. getFragmentShaderID(material) {
  11621. return this._getShaderStage(material.fragmentShader).id;
  11622. }
  11623. dispose() {
  11624. this.shaderCache.clear();
  11625. this.materialCache.clear();
  11626. }
  11627. _getShaderCacheForMaterial(material) {
  11628. const cache = this.materialCache;
  11629. let set = cache.get(material);
  11630. if (set === undefined) {
  11631. set = new Set();
  11632. cache.set(material, set);
  11633. }
  11634. return set;
  11635. }
  11636. _getShaderStage(code) {
  11637. const cache = this.shaderCache;
  11638. let stage = cache.get(code);
  11639. if (stage === undefined) {
  11640. stage = new WebGLShaderStage(code);
  11641. cache.set(code, stage);
  11642. }
  11643. return stage;
  11644. }
  11645. }
  11646. class WebGLShaderStage {
  11647. constructor(code) {
  11648. this.id = _id++;
  11649. this.code = code;
  11650. this.usedTimes = 0;
  11651. }
  11652. }
  11653. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11654. const _programLayers = new Layers();
  11655. const _customShaders = new WebGLShaderCache();
  11656. const programs = [];
  11657. const isWebGL2 = capabilities.isWebGL2;
  11658. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11659. const vertexTextures = capabilities.vertexTextures;
  11660. let precision = capabilities.precision;
  11661. const shaderIDs = {
  11662. MeshDepthMaterial: 'depth',
  11663. MeshDistanceMaterial: 'distanceRGBA',
  11664. MeshNormalMaterial: 'normal',
  11665. MeshBasicMaterial: 'basic',
  11666. MeshLambertMaterial: 'lambert',
  11667. MeshPhongMaterial: 'phong',
  11668. MeshToonMaterial: 'toon',
  11669. MeshStandardMaterial: 'physical',
  11670. MeshPhysicalMaterial: 'physical',
  11671. MeshMatcapMaterial: 'matcap',
  11672. LineBasicMaterial: 'basic',
  11673. LineDashedMaterial: 'dashed',
  11674. PointsMaterial: 'points',
  11675. ShadowMaterial: 'shadow',
  11676. SpriteMaterial: 'sprite'
  11677. };
  11678. function getParameters(material, lights, shadows, scene, object) {
  11679. const fog = scene.fog;
  11680. const geometry = object.geometry;
  11681. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11682. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11683. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11684. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11685. // (not to blow over maxLights budget)
  11686. if (material.precision !== null) {
  11687. precision = capabilities.getMaxPrecision(material.precision);
  11688. if (precision !== material.precision) {
  11689. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11690. }
  11691. } //
  11692. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11693. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11694. let morphTextureStride = 0;
  11695. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11696. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11697. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3; //
  11698. let vertexShader, fragmentShader;
  11699. let customVertexShaderID, customFragmentShaderID;
  11700. if (shaderID) {
  11701. const shader = ShaderLib[shaderID];
  11702. vertexShader = shader.vertexShader;
  11703. fragmentShader = shader.fragmentShader;
  11704. } else {
  11705. vertexShader = material.vertexShader;
  11706. fragmentShader = material.fragmentShader;
  11707. _customShaders.update(material);
  11708. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11709. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11710. }
  11711. const currentRenderTarget = renderer.getRenderTarget();
  11712. const useAlphaTest = material.alphaTest > 0;
  11713. const useClearcoat = material.clearcoat > 0;
  11714. const useIridescence = material.iridescence > 0;
  11715. const parameters = {
  11716. isWebGL2: isWebGL2,
  11717. shaderID: shaderID,
  11718. shaderName: material.type,
  11719. vertexShader: vertexShader,
  11720. fragmentShader: fragmentShader,
  11721. defines: material.defines,
  11722. customVertexShaderID: customVertexShaderID,
  11723. customFragmentShaderID: customFragmentShaderID,
  11724. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11725. glslVersion: material.glslVersion,
  11726. precision: precision,
  11727. instancing: object.isInstancedMesh === true,
  11728. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11729. supportsVertexTextures: vertexTextures,
  11730. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11731. map: !!material.map,
  11732. matcap: !!material.matcap,
  11733. envMap: !!envMap,
  11734. envMapMode: envMap && envMap.mapping,
  11735. envMapCubeUVHeight: envMapCubeUVHeight,
  11736. lightMap: !!material.lightMap,
  11737. aoMap: !!material.aoMap,
  11738. emissiveMap: !!material.emissiveMap,
  11739. bumpMap: !!material.bumpMap,
  11740. normalMap: !!material.normalMap,
  11741. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11742. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11743. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  11744. clearcoat: useClearcoat,
  11745. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11746. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11747. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11748. iridescence: useIridescence,
  11749. iridescenceMap: useIridescence && !!material.iridescenceMap,
  11750. iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap,
  11751. displacementMap: !!material.displacementMap,
  11752. roughnessMap: !!material.roughnessMap,
  11753. metalnessMap: !!material.metalnessMap,
  11754. specularMap: !!material.specularMap,
  11755. specularIntensityMap: !!material.specularIntensityMap,
  11756. specularColorMap: !!material.specularColorMap,
  11757. opaque: material.transparent === false && material.blending === NormalBlending,
  11758. alphaMap: !!material.alphaMap,
  11759. alphaTest: useAlphaTest,
  11760. gradientMap: !!material.gradientMap,
  11761. sheen: material.sheen > 0,
  11762. sheenColorMap: !!material.sheenColorMap,
  11763. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11764. transmission: material.transmission > 0,
  11765. transmissionMap: !!material.transmissionMap,
  11766. thicknessMap: !!material.thicknessMap,
  11767. combine: material.combine,
  11768. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  11769. vertexColors: material.vertexColors,
  11770. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11771. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  11772. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  11773. fog: !!fog,
  11774. useFog: material.fog === true,
  11775. fogExp2: fog && fog.isFogExp2,
  11776. flatShading: !!material.flatShading,
  11777. sizeAttenuation: material.sizeAttenuation,
  11778. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11779. skinning: object.isSkinnedMesh === true,
  11780. morphTargets: geometry.morphAttributes.position !== undefined,
  11781. morphNormals: geometry.morphAttributes.normal !== undefined,
  11782. morphColors: geometry.morphAttributes.color !== undefined,
  11783. morphTargetsCount: morphTargetsCount,
  11784. morphTextureStride: morphTextureStride,
  11785. numDirLights: lights.directional.length,
  11786. numPointLights: lights.point.length,
  11787. numSpotLights: lights.spot.length,
  11788. numSpotLightMaps: lights.spotLightMap.length,
  11789. numRectAreaLights: lights.rectArea.length,
  11790. numHemiLights: lights.hemi.length,
  11791. numDirLightShadows: lights.directionalShadowMap.length,
  11792. numPointLightShadows: lights.pointShadowMap.length,
  11793. numSpotLightShadows: lights.spotShadowMap.length,
  11794. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11795. numClippingPlanes: clipping.numPlanes,
  11796. numClipIntersection: clipping.numIntersection,
  11797. dithering: material.dithering,
  11798. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11799. shadowMapType: renderer.shadowMap.type,
  11800. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11801. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11802. premultipliedAlpha: material.premultipliedAlpha,
  11803. doubleSided: material.side === DoubleSide,
  11804. flipSided: material.side === BackSide,
  11805. useDepthPacking: !!material.depthPacking,
  11806. depthPacking: material.depthPacking || 0,
  11807. index0AttributeName: material.index0AttributeName,
  11808. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11809. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11810. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11811. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11812. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11813. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11814. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11815. customProgramCacheKey: material.customProgramCacheKey()
  11816. };
  11817. return parameters;
  11818. }
  11819. function getProgramCacheKey(parameters) {
  11820. const array = [];
  11821. if (parameters.shaderID) {
  11822. array.push(parameters.shaderID);
  11823. } else {
  11824. array.push(parameters.customVertexShaderID);
  11825. array.push(parameters.customFragmentShaderID);
  11826. }
  11827. if (parameters.defines !== undefined) {
  11828. for (const name in parameters.defines) {
  11829. array.push(name);
  11830. array.push(parameters.defines[name]);
  11831. }
  11832. }
  11833. if (parameters.isRawShaderMaterial === false) {
  11834. getProgramCacheKeyParameters(array, parameters);
  11835. getProgramCacheKeyBooleans(array, parameters);
  11836. array.push(renderer.outputEncoding);
  11837. }
  11838. array.push(parameters.customProgramCacheKey);
  11839. return array.join();
  11840. }
  11841. function getProgramCacheKeyParameters(array, parameters) {
  11842. array.push(parameters.precision);
  11843. array.push(parameters.outputEncoding);
  11844. array.push(parameters.envMapMode);
  11845. array.push(parameters.envMapCubeUVHeight);
  11846. array.push(parameters.combine);
  11847. array.push(parameters.vertexUvs);
  11848. array.push(parameters.fogExp2);
  11849. array.push(parameters.sizeAttenuation);
  11850. array.push(parameters.morphTargetsCount);
  11851. array.push(parameters.morphAttributeCount);
  11852. array.push(parameters.numDirLights);
  11853. array.push(parameters.numPointLights);
  11854. array.push(parameters.numSpotLights);
  11855. array.push(parameters.numSpotLightMaps);
  11856. array.push(parameters.numHemiLights);
  11857. array.push(parameters.numRectAreaLights);
  11858. array.push(parameters.numDirLightShadows);
  11859. array.push(parameters.numPointLightShadows);
  11860. array.push(parameters.numSpotLightShadows);
  11861. array.push(parameters.numSpotLightShadowsWithMaps);
  11862. array.push(parameters.shadowMapType);
  11863. array.push(parameters.toneMapping);
  11864. array.push(parameters.numClippingPlanes);
  11865. array.push(parameters.numClipIntersection);
  11866. array.push(parameters.depthPacking);
  11867. }
  11868. function getProgramCacheKeyBooleans(array, parameters) {
  11869. _programLayers.disableAll();
  11870. if (parameters.isWebGL2) _programLayers.enable(0);
  11871. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11872. if (parameters.instancing) _programLayers.enable(2);
  11873. if (parameters.instancingColor) _programLayers.enable(3);
  11874. if (parameters.map) _programLayers.enable(4);
  11875. if (parameters.matcap) _programLayers.enable(5);
  11876. if (parameters.envMap) _programLayers.enable(6);
  11877. if (parameters.lightMap) _programLayers.enable(7);
  11878. if (parameters.aoMap) _programLayers.enable(8);
  11879. if (parameters.emissiveMap) _programLayers.enable(9);
  11880. if (parameters.bumpMap) _programLayers.enable(10);
  11881. if (parameters.normalMap) _programLayers.enable(11);
  11882. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  11883. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  11884. if (parameters.clearcoat) _programLayers.enable(14);
  11885. if (parameters.clearcoatMap) _programLayers.enable(15);
  11886. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  11887. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  11888. if (parameters.iridescence) _programLayers.enable(18);
  11889. if (parameters.iridescenceMap) _programLayers.enable(19);
  11890. if (parameters.iridescenceThicknessMap) _programLayers.enable(20);
  11891. if (parameters.displacementMap) _programLayers.enable(21);
  11892. if (parameters.specularMap) _programLayers.enable(22);
  11893. if (parameters.roughnessMap) _programLayers.enable(23);
  11894. if (parameters.metalnessMap) _programLayers.enable(24);
  11895. if (parameters.gradientMap) _programLayers.enable(25);
  11896. if (parameters.alphaMap) _programLayers.enable(26);
  11897. if (parameters.alphaTest) _programLayers.enable(27);
  11898. if (parameters.vertexColors) _programLayers.enable(28);
  11899. if (parameters.vertexAlphas) _programLayers.enable(29);
  11900. if (parameters.vertexUvs) _programLayers.enable(30);
  11901. if (parameters.vertexTangents) _programLayers.enable(31);
  11902. if (parameters.uvsVertexOnly) _programLayers.enable(32);
  11903. array.push(_programLayers.mask);
  11904. _programLayers.disableAll();
  11905. if (parameters.fog) _programLayers.enable(0);
  11906. if (parameters.useFog) _programLayers.enable(1);
  11907. if (parameters.flatShading) _programLayers.enable(2);
  11908. if (parameters.logarithmicDepthBuffer) _programLayers.enable(3);
  11909. if (parameters.skinning) _programLayers.enable(4);
  11910. if (parameters.morphTargets) _programLayers.enable(5);
  11911. if (parameters.morphNormals) _programLayers.enable(6);
  11912. if (parameters.morphColors) _programLayers.enable(7);
  11913. if (parameters.premultipliedAlpha) _programLayers.enable(8);
  11914. if (parameters.shadowMapEnabled) _programLayers.enable(9);
  11915. if (parameters.physicallyCorrectLights) _programLayers.enable(10);
  11916. if (parameters.doubleSided) _programLayers.enable(11);
  11917. if (parameters.flipSided) _programLayers.enable(12);
  11918. if (parameters.useDepthPacking) _programLayers.enable(13);
  11919. if (parameters.dithering) _programLayers.enable(14);
  11920. if (parameters.specularIntensityMap) _programLayers.enable(15);
  11921. if (parameters.specularColorMap) _programLayers.enable(16);
  11922. if (parameters.transmission) _programLayers.enable(17);
  11923. if (parameters.transmissionMap) _programLayers.enable(18);
  11924. if (parameters.thicknessMap) _programLayers.enable(19);
  11925. if (parameters.sheen) _programLayers.enable(20);
  11926. if (parameters.sheenColorMap) _programLayers.enable(21);
  11927. if (parameters.sheenRoughnessMap) _programLayers.enable(22);
  11928. if (parameters.decodeVideoTexture) _programLayers.enable(23);
  11929. if (parameters.opaque) _programLayers.enable(24);
  11930. array.push(_programLayers.mask);
  11931. }
  11932. function getUniforms(material) {
  11933. const shaderID = shaderIDs[material.type];
  11934. let uniforms;
  11935. if (shaderID) {
  11936. const shader = ShaderLib[shaderID];
  11937. uniforms = UniformsUtils.clone(shader.uniforms);
  11938. } else {
  11939. uniforms = material.uniforms;
  11940. }
  11941. return uniforms;
  11942. }
  11943. function acquireProgram(parameters, cacheKey) {
  11944. let program; // Check if code has been already compiled
  11945. for (let p = 0, pl = programs.length; p < pl; p++) {
  11946. const preexistingProgram = programs[p];
  11947. if (preexistingProgram.cacheKey === cacheKey) {
  11948. program = preexistingProgram;
  11949. ++program.usedTimes;
  11950. break;
  11951. }
  11952. }
  11953. if (program === undefined) {
  11954. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11955. programs.push(program);
  11956. }
  11957. return program;
  11958. }
  11959. function releaseProgram(program) {
  11960. if (--program.usedTimes === 0) {
  11961. // Remove from unordered set
  11962. const i = programs.indexOf(program);
  11963. programs[i] = programs[programs.length - 1];
  11964. programs.pop(); // Free WebGL resources
  11965. program.destroy();
  11966. }
  11967. }
  11968. function releaseShaderCache(material) {
  11969. _customShaders.remove(material);
  11970. }
  11971. function dispose() {
  11972. _customShaders.dispose();
  11973. }
  11974. return {
  11975. getParameters: getParameters,
  11976. getProgramCacheKey: getProgramCacheKey,
  11977. getUniforms: getUniforms,
  11978. acquireProgram: acquireProgram,
  11979. releaseProgram: releaseProgram,
  11980. releaseShaderCache: releaseShaderCache,
  11981. // Exposed for resource monitoring & error feedback via renderer.info:
  11982. programs: programs,
  11983. dispose: dispose
  11984. };
  11985. }
  11986. function WebGLProperties() {
  11987. let properties = new WeakMap();
  11988. function get(object) {
  11989. let map = properties.get(object);
  11990. if (map === undefined) {
  11991. map = {};
  11992. properties.set(object, map);
  11993. }
  11994. return map;
  11995. }
  11996. function remove(object) {
  11997. properties.delete(object);
  11998. }
  11999. function update(object, key, value) {
  12000. properties.get(object)[key] = value;
  12001. }
  12002. function dispose() {
  12003. properties = new WeakMap();
  12004. }
  12005. return {
  12006. get: get,
  12007. remove: remove,
  12008. update: update,
  12009. dispose: dispose
  12010. };
  12011. }
  12012. function painterSortStable(a, b) {
  12013. if (a.groupOrder !== b.groupOrder) {
  12014. return a.groupOrder - b.groupOrder;
  12015. } else if (a.renderOrder !== b.renderOrder) {
  12016. return a.renderOrder - b.renderOrder;
  12017. } else if (a.material.id !== b.material.id) {
  12018. return a.material.id - b.material.id;
  12019. } else if (a.z !== b.z) {
  12020. return a.z - b.z;
  12021. } else {
  12022. return a.id - b.id;
  12023. }
  12024. }
  12025. function reversePainterSortStable(a, b) {
  12026. if (a.groupOrder !== b.groupOrder) {
  12027. return a.groupOrder - b.groupOrder;
  12028. } else if (a.renderOrder !== b.renderOrder) {
  12029. return a.renderOrder - b.renderOrder;
  12030. } else if (a.z !== b.z) {
  12031. return b.z - a.z;
  12032. } else {
  12033. return a.id - b.id;
  12034. }
  12035. }
  12036. function WebGLRenderList() {
  12037. const renderItems = [];
  12038. let renderItemsIndex = 0;
  12039. const opaque = [];
  12040. const transmissive = [];
  12041. const transparent = [];
  12042. function init() {
  12043. renderItemsIndex = 0;
  12044. opaque.length = 0;
  12045. transmissive.length = 0;
  12046. transparent.length = 0;
  12047. }
  12048. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12049. let renderItem = renderItems[renderItemsIndex];
  12050. if (renderItem === undefined) {
  12051. renderItem = {
  12052. id: object.id,
  12053. object: object,
  12054. geometry: geometry,
  12055. material: material,
  12056. groupOrder: groupOrder,
  12057. renderOrder: object.renderOrder,
  12058. z: z,
  12059. group: group
  12060. };
  12061. renderItems[renderItemsIndex] = renderItem;
  12062. } else {
  12063. renderItem.id = object.id;
  12064. renderItem.object = object;
  12065. renderItem.geometry = geometry;
  12066. renderItem.material = material;
  12067. renderItem.groupOrder = groupOrder;
  12068. renderItem.renderOrder = object.renderOrder;
  12069. renderItem.z = z;
  12070. renderItem.group = group;
  12071. }
  12072. renderItemsIndex++;
  12073. return renderItem;
  12074. }
  12075. function push(object, geometry, material, groupOrder, z, group) {
  12076. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12077. if (material.transmission > 0.0) {
  12078. transmissive.push(renderItem);
  12079. } else if (material.transparent === true) {
  12080. transparent.push(renderItem);
  12081. } else {
  12082. opaque.push(renderItem);
  12083. }
  12084. }
  12085. function unshift(object, geometry, material, groupOrder, z, group) {
  12086. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12087. if (material.transmission > 0.0) {
  12088. transmissive.unshift(renderItem);
  12089. } else if (material.transparent === true) {
  12090. transparent.unshift(renderItem);
  12091. } else {
  12092. opaque.unshift(renderItem);
  12093. }
  12094. }
  12095. function sort(customOpaqueSort, customTransparentSort) {
  12096. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12097. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12098. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12099. }
  12100. function finish() {
  12101. // Clear references from inactive renderItems in the list
  12102. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12103. const renderItem = renderItems[i];
  12104. if (renderItem.id === null) break;
  12105. renderItem.id = null;
  12106. renderItem.object = null;
  12107. renderItem.geometry = null;
  12108. renderItem.material = null;
  12109. renderItem.group = null;
  12110. }
  12111. }
  12112. return {
  12113. opaque: opaque,
  12114. transmissive: transmissive,
  12115. transparent: transparent,
  12116. init: init,
  12117. push: push,
  12118. unshift: unshift,
  12119. finish: finish,
  12120. sort: sort
  12121. };
  12122. }
  12123. function WebGLRenderLists() {
  12124. let lists = new WeakMap();
  12125. function get(scene, renderCallDepth) {
  12126. const listArray = lists.get(scene);
  12127. let list;
  12128. if (listArray === undefined) {
  12129. list = new WebGLRenderList();
  12130. lists.set(scene, [list]);
  12131. } else {
  12132. if (renderCallDepth >= listArray.length) {
  12133. list = new WebGLRenderList();
  12134. listArray.push(list);
  12135. } else {
  12136. list = listArray[renderCallDepth];
  12137. }
  12138. }
  12139. return list;
  12140. }
  12141. function dispose() {
  12142. lists = new WeakMap();
  12143. }
  12144. return {
  12145. get: get,
  12146. dispose: dispose
  12147. };
  12148. }
  12149. function UniformsCache() {
  12150. const lights = {};
  12151. return {
  12152. get: function (light) {
  12153. if (lights[light.id] !== undefined) {
  12154. return lights[light.id];
  12155. }
  12156. let uniforms;
  12157. switch (light.type) {
  12158. case 'DirectionalLight':
  12159. uniforms = {
  12160. direction: new Vector3(),
  12161. color: new Color()
  12162. };
  12163. break;
  12164. case 'SpotLight':
  12165. uniforms = {
  12166. position: new Vector3(),
  12167. direction: new Vector3(),
  12168. color: new Color(),
  12169. distance: 0,
  12170. coneCos: 0,
  12171. penumbraCos: 0,
  12172. decay: 0
  12173. };
  12174. break;
  12175. case 'PointLight':
  12176. uniforms = {
  12177. position: new Vector3(),
  12178. color: new Color(),
  12179. distance: 0,
  12180. decay: 0
  12181. };
  12182. break;
  12183. case 'HemisphereLight':
  12184. uniforms = {
  12185. direction: new Vector3(),
  12186. skyColor: new Color(),
  12187. groundColor: new Color()
  12188. };
  12189. break;
  12190. case 'RectAreaLight':
  12191. uniforms = {
  12192. color: new Color(),
  12193. position: new Vector3(),
  12194. halfWidth: new Vector3(),
  12195. halfHeight: new Vector3()
  12196. };
  12197. break;
  12198. }
  12199. lights[light.id] = uniforms;
  12200. return uniforms;
  12201. }
  12202. };
  12203. }
  12204. function ShadowUniformsCache() {
  12205. const lights = {};
  12206. return {
  12207. get: function (light) {
  12208. if (lights[light.id] !== undefined) {
  12209. return lights[light.id];
  12210. }
  12211. let uniforms;
  12212. switch (light.type) {
  12213. case 'DirectionalLight':
  12214. uniforms = {
  12215. shadowBias: 0,
  12216. shadowNormalBias: 0,
  12217. shadowRadius: 1,
  12218. shadowMapSize: new Vector2()
  12219. };
  12220. break;
  12221. case 'SpotLight':
  12222. uniforms = {
  12223. shadowBias: 0,
  12224. shadowNormalBias: 0,
  12225. shadowRadius: 1,
  12226. shadowMapSize: new Vector2()
  12227. };
  12228. break;
  12229. case 'PointLight':
  12230. uniforms = {
  12231. shadowBias: 0,
  12232. shadowNormalBias: 0,
  12233. shadowRadius: 1,
  12234. shadowMapSize: new Vector2(),
  12235. shadowCameraNear: 1,
  12236. shadowCameraFar: 1000
  12237. };
  12238. break;
  12239. // TODO (abelnation): set RectAreaLight shadow uniforms
  12240. }
  12241. lights[light.id] = uniforms;
  12242. return uniforms;
  12243. }
  12244. };
  12245. }
  12246. let nextVersion = 0;
  12247. function shadowCastingAndTexturingLightsFirst(lightA, lightB) {
  12248. return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0);
  12249. }
  12250. function WebGLLights(extensions, capabilities) {
  12251. const cache = new UniformsCache();
  12252. const shadowCache = ShadowUniformsCache();
  12253. const state = {
  12254. version: 0,
  12255. hash: {
  12256. directionalLength: -1,
  12257. pointLength: -1,
  12258. spotLength: -1,
  12259. rectAreaLength: -1,
  12260. hemiLength: -1,
  12261. numDirectionalShadows: -1,
  12262. numPointShadows: -1,
  12263. numSpotShadows: -1,
  12264. numSpotMaps: -1
  12265. },
  12266. ambient: [0, 0, 0],
  12267. probe: [],
  12268. directional: [],
  12269. directionalShadow: [],
  12270. directionalShadowMap: [],
  12271. directionalShadowMatrix: [],
  12272. spot: [],
  12273. spotLightMap: [],
  12274. spotShadow: [],
  12275. spotShadowMap: [],
  12276. spotLightMatrix: [],
  12277. rectArea: [],
  12278. rectAreaLTC1: null,
  12279. rectAreaLTC2: null,
  12280. point: [],
  12281. pointShadow: [],
  12282. pointShadowMap: [],
  12283. pointShadowMatrix: [],
  12284. hemi: [],
  12285. numSpotLightShadowsWithMaps: 0
  12286. };
  12287. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12288. const vector3 = new Vector3();
  12289. const matrix4 = new Matrix4();
  12290. const matrix42 = new Matrix4();
  12291. function setup(lights, physicallyCorrectLights) {
  12292. let r = 0,
  12293. g = 0,
  12294. b = 0;
  12295. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12296. let directionalLength = 0;
  12297. let pointLength = 0;
  12298. let spotLength = 0;
  12299. let rectAreaLength = 0;
  12300. let hemiLength = 0;
  12301. let numDirectionalShadows = 0;
  12302. let numPointShadows = 0;
  12303. let numSpotShadows = 0;
  12304. let numSpotMaps = 0;
  12305. let numSpotShadowsWithMaps = 0; // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12306. lights.sort(shadowCastingAndTexturingLightsFirst); // artist-friendly light intensity scaling factor
  12307. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12308. for (let i = 0, l = lights.length; i < l; i++) {
  12309. const light = lights[i];
  12310. const color = light.color;
  12311. const intensity = light.intensity;
  12312. const distance = light.distance;
  12313. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12314. if (light.isAmbientLight) {
  12315. r += color.r * intensity * scaleFactor;
  12316. g += color.g * intensity * scaleFactor;
  12317. b += color.b * intensity * scaleFactor;
  12318. } else if (light.isLightProbe) {
  12319. for (let j = 0; j < 9; j++) {
  12320. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12321. }
  12322. } else if (light.isDirectionalLight) {
  12323. const uniforms = cache.get(light);
  12324. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12325. if (light.castShadow) {
  12326. const shadow = light.shadow;
  12327. const shadowUniforms = shadowCache.get(light);
  12328. shadowUniforms.shadowBias = shadow.bias;
  12329. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12330. shadowUniforms.shadowRadius = shadow.radius;
  12331. shadowUniforms.shadowMapSize = shadow.mapSize;
  12332. state.directionalShadow[directionalLength] = shadowUniforms;
  12333. state.directionalShadowMap[directionalLength] = shadowMap;
  12334. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12335. numDirectionalShadows++;
  12336. }
  12337. state.directional[directionalLength] = uniforms;
  12338. directionalLength++;
  12339. } else if (light.isSpotLight) {
  12340. const uniforms = cache.get(light);
  12341. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12342. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12343. uniforms.distance = distance;
  12344. uniforms.coneCos = Math.cos(light.angle);
  12345. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12346. uniforms.decay = light.decay;
  12347. state.spot[spotLength] = uniforms;
  12348. const shadow = light.shadow;
  12349. if (light.map) {
  12350. state.spotLightMap[numSpotMaps] = light.map;
  12351. numSpotMaps++; // make sure the lightMatrix is up to date
  12352. // TODO : do it if required only
  12353. shadow.updateMatrices(light);
  12354. if (light.castShadow) numSpotShadowsWithMaps++;
  12355. }
  12356. state.spotLightMatrix[spotLength] = shadow.matrix;
  12357. if (light.castShadow) {
  12358. const shadowUniforms = shadowCache.get(light);
  12359. shadowUniforms.shadowBias = shadow.bias;
  12360. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12361. shadowUniforms.shadowRadius = shadow.radius;
  12362. shadowUniforms.shadowMapSize = shadow.mapSize;
  12363. state.spotShadow[spotLength] = shadowUniforms;
  12364. state.spotShadowMap[spotLength] = shadowMap;
  12365. numSpotShadows++;
  12366. }
  12367. spotLength++;
  12368. } else if (light.isRectAreaLight) {
  12369. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12370. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12371. // (b) intensity is the brightness of the light
  12372. uniforms.color.copy(color).multiplyScalar(intensity);
  12373. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12374. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12375. state.rectArea[rectAreaLength] = uniforms;
  12376. rectAreaLength++;
  12377. } else if (light.isPointLight) {
  12378. const uniforms = cache.get(light);
  12379. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12380. uniforms.distance = light.distance;
  12381. uniforms.decay = light.decay;
  12382. if (light.castShadow) {
  12383. const shadow = light.shadow;
  12384. const shadowUniforms = shadowCache.get(light);
  12385. shadowUniforms.shadowBias = shadow.bias;
  12386. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12387. shadowUniforms.shadowRadius = shadow.radius;
  12388. shadowUniforms.shadowMapSize = shadow.mapSize;
  12389. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12390. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12391. state.pointShadow[pointLength] = shadowUniforms;
  12392. state.pointShadowMap[pointLength] = shadowMap;
  12393. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12394. numPointShadows++;
  12395. }
  12396. state.point[pointLength] = uniforms;
  12397. pointLength++;
  12398. } else if (light.isHemisphereLight) {
  12399. const uniforms = cache.get(light);
  12400. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12401. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12402. state.hemi[hemiLength] = uniforms;
  12403. hemiLength++;
  12404. }
  12405. }
  12406. if (rectAreaLength > 0) {
  12407. if (capabilities.isWebGL2) {
  12408. // WebGL 2
  12409. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12410. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12411. } else {
  12412. // WebGL 1
  12413. if (extensions.has('OES_texture_float_linear') === true) {
  12414. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12415. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12416. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12417. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12418. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12419. } else {
  12420. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12421. }
  12422. }
  12423. }
  12424. state.ambient[0] = r;
  12425. state.ambient[1] = g;
  12426. state.ambient[2] = b;
  12427. const hash = state.hash;
  12428. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps) {
  12429. state.directional.length = directionalLength;
  12430. state.spot.length = spotLength;
  12431. state.rectArea.length = rectAreaLength;
  12432. state.point.length = pointLength;
  12433. state.hemi.length = hemiLength;
  12434. state.directionalShadow.length = numDirectionalShadows;
  12435. state.directionalShadowMap.length = numDirectionalShadows;
  12436. state.pointShadow.length = numPointShadows;
  12437. state.pointShadowMap.length = numPointShadows;
  12438. state.spotShadow.length = numSpotShadows;
  12439. state.spotShadowMap.length = numSpotShadows;
  12440. state.directionalShadowMatrix.length = numDirectionalShadows;
  12441. state.pointShadowMatrix.length = numPointShadows;
  12442. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12443. state.spotLightMap.length = numSpotMaps;
  12444. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12445. hash.directionalLength = directionalLength;
  12446. hash.pointLength = pointLength;
  12447. hash.spotLength = spotLength;
  12448. hash.rectAreaLength = rectAreaLength;
  12449. hash.hemiLength = hemiLength;
  12450. hash.numDirectionalShadows = numDirectionalShadows;
  12451. hash.numPointShadows = numPointShadows;
  12452. hash.numSpotShadows = numSpotShadows;
  12453. hash.numSpotMaps = numSpotMaps;
  12454. state.version = nextVersion++;
  12455. }
  12456. }
  12457. function setupView(lights, camera) {
  12458. let directionalLength = 0;
  12459. let pointLength = 0;
  12460. let spotLength = 0;
  12461. let rectAreaLength = 0;
  12462. let hemiLength = 0;
  12463. const viewMatrix = camera.matrixWorldInverse;
  12464. for (let i = 0, l = lights.length; i < l; i++) {
  12465. const light = lights[i];
  12466. if (light.isDirectionalLight) {
  12467. const uniforms = state.directional[directionalLength];
  12468. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12469. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12470. uniforms.direction.sub(vector3);
  12471. uniforms.direction.transformDirection(viewMatrix);
  12472. directionalLength++;
  12473. } else if (light.isSpotLight) {
  12474. const uniforms = state.spot[spotLength];
  12475. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12476. uniforms.position.applyMatrix4(viewMatrix);
  12477. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12478. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12479. uniforms.direction.sub(vector3);
  12480. uniforms.direction.transformDirection(viewMatrix);
  12481. spotLength++;
  12482. } else if (light.isRectAreaLight) {
  12483. const uniforms = state.rectArea[rectAreaLength];
  12484. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12485. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12486. matrix42.identity();
  12487. matrix4.copy(light.matrixWorld);
  12488. matrix4.premultiply(viewMatrix);
  12489. matrix42.extractRotation(matrix4);
  12490. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12491. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12492. uniforms.halfWidth.applyMatrix4(matrix42);
  12493. uniforms.halfHeight.applyMatrix4(matrix42);
  12494. rectAreaLength++;
  12495. } else if (light.isPointLight) {
  12496. const uniforms = state.point[pointLength];
  12497. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12498. uniforms.position.applyMatrix4(viewMatrix);
  12499. pointLength++;
  12500. } else if (light.isHemisphereLight) {
  12501. const uniforms = state.hemi[hemiLength];
  12502. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12503. uniforms.direction.transformDirection(viewMatrix);
  12504. hemiLength++;
  12505. }
  12506. }
  12507. }
  12508. return {
  12509. setup: setup,
  12510. setupView: setupView,
  12511. state: state
  12512. };
  12513. }
  12514. function WebGLRenderState(extensions, capabilities) {
  12515. const lights = new WebGLLights(extensions, capabilities);
  12516. const lightsArray = [];
  12517. const shadowsArray = [];
  12518. function init() {
  12519. lightsArray.length = 0;
  12520. shadowsArray.length = 0;
  12521. }
  12522. function pushLight(light) {
  12523. lightsArray.push(light);
  12524. }
  12525. function pushShadow(shadowLight) {
  12526. shadowsArray.push(shadowLight);
  12527. }
  12528. function setupLights(physicallyCorrectLights) {
  12529. lights.setup(lightsArray, physicallyCorrectLights);
  12530. }
  12531. function setupLightsView(camera) {
  12532. lights.setupView(lightsArray, camera);
  12533. }
  12534. const state = {
  12535. lightsArray: lightsArray,
  12536. shadowsArray: shadowsArray,
  12537. lights: lights
  12538. };
  12539. return {
  12540. init: init,
  12541. state: state,
  12542. setupLights: setupLights,
  12543. setupLightsView: setupLightsView,
  12544. pushLight: pushLight,
  12545. pushShadow: pushShadow
  12546. };
  12547. }
  12548. function WebGLRenderStates(extensions, capabilities) {
  12549. let renderStates = new WeakMap();
  12550. function get(scene, renderCallDepth = 0) {
  12551. const renderStateArray = renderStates.get(scene);
  12552. let renderState;
  12553. if (renderStateArray === undefined) {
  12554. renderState = new WebGLRenderState(extensions, capabilities);
  12555. renderStates.set(scene, [renderState]);
  12556. } else {
  12557. if (renderCallDepth >= renderStateArray.length) {
  12558. renderState = new WebGLRenderState(extensions, capabilities);
  12559. renderStateArray.push(renderState);
  12560. } else {
  12561. renderState = renderStateArray[renderCallDepth];
  12562. }
  12563. }
  12564. return renderState;
  12565. }
  12566. function dispose() {
  12567. renderStates = new WeakMap();
  12568. }
  12569. return {
  12570. get: get,
  12571. dispose: dispose
  12572. };
  12573. }
  12574. class MeshDepthMaterial extends Material {
  12575. constructor(parameters) {
  12576. super();
  12577. this.isMeshDepthMaterial = true;
  12578. this.type = 'MeshDepthMaterial';
  12579. this.depthPacking = BasicDepthPacking;
  12580. this.map = null;
  12581. this.alphaMap = null;
  12582. this.displacementMap = null;
  12583. this.displacementScale = 1;
  12584. this.displacementBias = 0;
  12585. this.wireframe = false;
  12586. this.wireframeLinewidth = 1;
  12587. this.setValues(parameters);
  12588. }
  12589. copy(source) {
  12590. super.copy(source);
  12591. this.depthPacking = source.depthPacking;
  12592. this.map = source.map;
  12593. this.alphaMap = source.alphaMap;
  12594. this.displacementMap = source.displacementMap;
  12595. this.displacementScale = source.displacementScale;
  12596. this.displacementBias = source.displacementBias;
  12597. this.wireframe = source.wireframe;
  12598. this.wireframeLinewidth = source.wireframeLinewidth;
  12599. return this;
  12600. }
  12601. }
  12602. class MeshDistanceMaterial extends Material {
  12603. constructor(parameters) {
  12604. super();
  12605. this.isMeshDistanceMaterial = true;
  12606. this.type = 'MeshDistanceMaterial';
  12607. this.referencePosition = new Vector3();
  12608. this.nearDistance = 1;
  12609. this.farDistance = 1000;
  12610. this.map = null;
  12611. this.alphaMap = null;
  12612. this.displacementMap = null;
  12613. this.displacementScale = 1;
  12614. this.displacementBias = 0;
  12615. this.setValues(parameters);
  12616. }
  12617. copy(source) {
  12618. super.copy(source);
  12619. this.referencePosition.copy(source.referencePosition);
  12620. this.nearDistance = source.nearDistance;
  12621. this.farDistance = source.farDistance;
  12622. this.map = source.map;
  12623. this.alphaMap = source.alphaMap;
  12624. this.displacementMap = source.displacementMap;
  12625. this.displacementScale = source.displacementScale;
  12626. this.displacementBias = source.displacementBias;
  12627. return this;
  12628. }
  12629. }
  12630. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12631. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12632. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12633. let _frustum = new Frustum();
  12634. const _shadowMapSize = new Vector2(),
  12635. _viewportSize = new Vector2(),
  12636. _viewport = new Vector4(),
  12637. _depthMaterial = new MeshDepthMaterial({
  12638. depthPacking: RGBADepthPacking
  12639. }),
  12640. _distanceMaterial = new MeshDistanceMaterial(),
  12641. _materialCache = {},
  12642. _maxTextureSize = _capabilities.maxTextureSize;
  12643. const shadowSide = {
  12644. 0: BackSide,
  12645. 1: FrontSide,
  12646. 2: DoubleSide
  12647. };
  12648. const shadowMaterialVertical = new ShaderMaterial({
  12649. defines: {
  12650. VSM_SAMPLES: 8
  12651. },
  12652. uniforms: {
  12653. shadow_pass: {
  12654. value: null
  12655. },
  12656. resolution: {
  12657. value: new Vector2()
  12658. },
  12659. radius: {
  12660. value: 4.0
  12661. }
  12662. },
  12663. vertexShader: vertex,
  12664. fragmentShader: fragment
  12665. });
  12666. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12667. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12668. const fullScreenTri = new BufferGeometry();
  12669. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12670. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12671. const scope = this;
  12672. this.enabled = false;
  12673. this.autoUpdate = true;
  12674. this.needsUpdate = false;
  12675. this.type = PCFShadowMap;
  12676. this.render = function (lights, scene, camera) {
  12677. if (scope.enabled === false) return;
  12678. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12679. if (lights.length === 0) return;
  12680. const currentRenderTarget = _renderer.getRenderTarget();
  12681. const activeCubeFace = _renderer.getActiveCubeFace();
  12682. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12683. const _state = _renderer.state; // Set GL state for depth map.
  12684. _state.setBlending(NoBlending);
  12685. _state.buffers.color.setClear(1, 1, 1, 1);
  12686. _state.buffers.depth.setTest(true);
  12687. _state.setScissorTest(false); // render depth map
  12688. for (let i = 0, il = lights.length; i < il; i++) {
  12689. const light = lights[i];
  12690. const shadow = light.shadow;
  12691. if (shadow === undefined) {
  12692. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12693. continue;
  12694. }
  12695. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12696. _shadowMapSize.copy(shadow.mapSize);
  12697. const shadowFrameExtents = shadow.getFrameExtents();
  12698. _shadowMapSize.multiply(shadowFrameExtents);
  12699. _viewportSize.copy(shadow.mapSize);
  12700. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12701. if (_shadowMapSize.x > _maxTextureSize) {
  12702. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12703. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12704. shadow.mapSize.x = _viewportSize.x;
  12705. }
  12706. if (_shadowMapSize.y > _maxTextureSize) {
  12707. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12708. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12709. shadow.mapSize.y = _viewportSize.y;
  12710. }
  12711. }
  12712. if (shadow.map === null) {
  12713. const pars = this.type !== VSMShadowMap ? {
  12714. minFilter: NearestFilter,
  12715. magFilter: NearestFilter
  12716. } : {};
  12717. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12718. shadow.map.texture.name = light.name + '.shadowMap';
  12719. shadow.camera.updateProjectionMatrix();
  12720. }
  12721. _renderer.setRenderTarget(shadow.map);
  12722. _renderer.clear();
  12723. const viewportCount = shadow.getViewportCount();
  12724. for (let vp = 0; vp < viewportCount; vp++) {
  12725. const viewport = shadow.getViewport(vp);
  12726. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12727. _state.viewport(_viewport);
  12728. shadow.updateMatrices(light, vp);
  12729. _frustum = shadow.getFrustum();
  12730. renderObject(scene, camera, shadow.camera, light, this.type);
  12731. } // do blur pass for VSM
  12732. if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) {
  12733. VSMPass(shadow, camera);
  12734. }
  12735. shadow.needsUpdate = false;
  12736. }
  12737. scope.needsUpdate = false;
  12738. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12739. };
  12740. function VSMPass(shadow, camera) {
  12741. const geometry = _objects.update(fullScreenMesh);
  12742. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12743. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12744. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12745. shadowMaterialVertical.needsUpdate = true;
  12746. shadowMaterialHorizontal.needsUpdate = true;
  12747. }
  12748. if (shadow.mapPass === null) {
  12749. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  12750. } // vertical pass
  12751. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12752. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12753. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12754. _renderer.setRenderTarget(shadow.mapPass);
  12755. _renderer.clear();
  12756. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12757. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12758. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12759. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12760. _renderer.setRenderTarget(shadow.map);
  12761. _renderer.clear();
  12762. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12763. }
  12764. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12765. let result = null;
  12766. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12767. if (customMaterial !== undefined) {
  12768. result = customMaterial;
  12769. } else {
  12770. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12771. }
  12772. if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12773. // in this case we need a unique material instance reflecting the
  12774. // appropriate state
  12775. const keyA = result.uuid,
  12776. keyB = material.uuid;
  12777. let materialsForVariant = _materialCache[keyA];
  12778. if (materialsForVariant === undefined) {
  12779. materialsForVariant = {};
  12780. _materialCache[keyA] = materialsForVariant;
  12781. }
  12782. let cachedMaterial = materialsForVariant[keyB];
  12783. if (cachedMaterial === undefined) {
  12784. cachedMaterial = result.clone();
  12785. materialsForVariant[keyB] = cachedMaterial;
  12786. }
  12787. result = cachedMaterial;
  12788. }
  12789. result.visible = material.visible;
  12790. result.wireframe = material.wireframe;
  12791. if (type === VSMShadowMap) {
  12792. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12793. } else {
  12794. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12795. }
  12796. result.alphaMap = material.alphaMap;
  12797. result.alphaTest = material.alphaTest;
  12798. result.clipShadows = material.clipShadows;
  12799. result.clippingPlanes = material.clippingPlanes;
  12800. result.clipIntersection = material.clipIntersection;
  12801. result.displacementMap = material.displacementMap;
  12802. result.displacementScale = material.displacementScale;
  12803. result.displacementBias = material.displacementBias;
  12804. result.wireframeLinewidth = material.wireframeLinewidth;
  12805. result.linewidth = material.linewidth;
  12806. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12807. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12808. result.nearDistance = shadowCameraNear;
  12809. result.farDistance = shadowCameraFar;
  12810. }
  12811. return result;
  12812. }
  12813. function renderObject(object, camera, shadowCamera, light, type) {
  12814. if (object.visible === false) return;
  12815. const visible = object.layers.test(camera.layers);
  12816. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12817. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12818. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12819. const geometry = _objects.update(object);
  12820. const material = object.material;
  12821. if (Array.isArray(material)) {
  12822. const groups = geometry.groups;
  12823. for (let k = 0, kl = groups.length; k < kl; k++) {
  12824. const group = groups[k];
  12825. const groupMaterial = material[group.materialIndex];
  12826. if (groupMaterial && groupMaterial.visible) {
  12827. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12828. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12829. }
  12830. }
  12831. } else if (material.visible) {
  12832. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12833. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12834. }
  12835. }
  12836. }
  12837. const children = object.children;
  12838. for (let i = 0, l = children.length; i < l; i++) {
  12839. renderObject(children[i], camera, shadowCamera, light, type);
  12840. }
  12841. }
  12842. }
  12843. function WebGLState(gl, extensions, capabilities) {
  12844. const isWebGL2 = capabilities.isWebGL2;
  12845. function ColorBuffer() {
  12846. let locked = false;
  12847. const color = new Vector4();
  12848. let currentColorMask = null;
  12849. const currentColorClear = new Vector4(0, 0, 0, 0);
  12850. return {
  12851. setMask: function (colorMask) {
  12852. if (currentColorMask !== colorMask && !locked) {
  12853. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12854. currentColorMask = colorMask;
  12855. }
  12856. },
  12857. setLocked: function (lock) {
  12858. locked = lock;
  12859. },
  12860. setClear: function (r, g, b, a, premultipliedAlpha) {
  12861. if (premultipliedAlpha === true) {
  12862. r *= a;
  12863. g *= a;
  12864. b *= a;
  12865. }
  12866. color.set(r, g, b, a);
  12867. if (currentColorClear.equals(color) === false) {
  12868. gl.clearColor(r, g, b, a);
  12869. currentColorClear.copy(color);
  12870. }
  12871. },
  12872. reset: function () {
  12873. locked = false;
  12874. currentColorMask = null;
  12875. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12876. }
  12877. };
  12878. }
  12879. function DepthBuffer() {
  12880. let locked = false;
  12881. let currentDepthMask = null;
  12882. let currentDepthFunc = null;
  12883. let currentDepthClear = null;
  12884. return {
  12885. setTest: function (depthTest) {
  12886. if (depthTest) {
  12887. enable(gl.DEPTH_TEST);
  12888. } else {
  12889. disable(gl.DEPTH_TEST);
  12890. }
  12891. },
  12892. setMask: function (depthMask) {
  12893. if (currentDepthMask !== depthMask && !locked) {
  12894. gl.depthMask(depthMask);
  12895. currentDepthMask = depthMask;
  12896. }
  12897. },
  12898. setFunc: function (depthFunc) {
  12899. if (currentDepthFunc !== depthFunc) {
  12900. if (depthFunc) {
  12901. switch (depthFunc) {
  12902. case NeverDepth:
  12903. gl.depthFunc(gl.NEVER);
  12904. break;
  12905. case AlwaysDepth:
  12906. gl.depthFunc(gl.ALWAYS);
  12907. break;
  12908. case LessDepth:
  12909. gl.depthFunc(gl.LESS);
  12910. break;
  12911. case LessEqualDepth:
  12912. gl.depthFunc(gl.LEQUAL);
  12913. break;
  12914. case EqualDepth:
  12915. gl.depthFunc(gl.EQUAL);
  12916. break;
  12917. case GreaterEqualDepth:
  12918. gl.depthFunc(gl.GEQUAL);
  12919. break;
  12920. case GreaterDepth:
  12921. gl.depthFunc(gl.GREATER);
  12922. break;
  12923. case NotEqualDepth:
  12924. gl.depthFunc(gl.NOTEQUAL);
  12925. break;
  12926. default:
  12927. gl.depthFunc(gl.LEQUAL);
  12928. }
  12929. } else {
  12930. gl.depthFunc(gl.LEQUAL);
  12931. }
  12932. currentDepthFunc = depthFunc;
  12933. }
  12934. },
  12935. setLocked: function (lock) {
  12936. locked = lock;
  12937. },
  12938. setClear: function (depth) {
  12939. if (currentDepthClear !== depth) {
  12940. gl.clearDepth(depth);
  12941. currentDepthClear = depth;
  12942. }
  12943. },
  12944. reset: function () {
  12945. locked = false;
  12946. currentDepthMask = null;
  12947. currentDepthFunc = null;
  12948. currentDepthClear = null;
  12949. }
  12950. };
  12951. }
  12952. function StencilBuffer() {
  12953. let locked = false;
  12954. let currentStencilMask = null;
  12955. let currentStencilFunc = null;
  12956. let currentStencilRef = null;
  12957. let currentStencilFuncMask = null;
  12958. let currentStencilFail = null;
  12959. let currentStencilZFail = null;
  12960. let currentStencilZPass = null;
  12961. let currentStencilClear = null;
  12962. return {
  12963. setTest: function (stencilTest) {
  12964. if (!locked) {
  12965. if (stencilTest) {
  12966. enable(gl.STENCIL_TEST);
  12967. } else {
  12968. disable(gl.STENCIL_TEST);
  12969. }
  12970. }
  12971. },
  12972. setMask: function (stencilMask) {
  12973. if (currentStencilMask !== stencilMask && !locked) {
  12974. gl.stencilMask(stencilMask);
  12975. currentStencilMask = stencilMask;
  12976. }
  12977. },
  12978. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12979. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12980. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12981. currentStencilFunc = stencilFunc;
  12982. currentStencilRef = stencilRef;
  12983. currentStencilFuncMask = stencilMask;
  12984. }
  12985. },
  12986. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12987. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12988. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12989. currentStencilFail = stencilFail;
  12990. currentStencilZFail = stencilZFail;
  12991. currentStencilZPass = stencilZPass;
  12992. }
  12993. },
  12994. setLocked: function (lock) {
  12995. locked = lock;
  12996. },
  12997. setClear: function (stencil) {
  12998. if (currentStencilClear !== stencil) {
  12999. gl.clearStencil(stencil);
  13000. currentStencilClear = stencil;
  13001. }
  13002. },
  13003. reset: function () {
  13004. locked = false;
  13005. currentStencilMask = null;
  13006. currentStencilFunc = null;
  13007. currentStencilRef = null;
  13008. currentStencilFuncMask = null;
  13009. currentStencilFail = null;
  13010. currentStencilZFail = null;
  13011. currentStencilZPass = null;
  13012. currentStencilClear = null;
  13013. }
  13014. };
  13015. } //
  13016. const colorBuffer = new ColorBuffer();
  13017. const depthBuffer = new DepthBuffer();
  13018. const stencilBuffer = new StencilBuffer();
  13019. const uboBindings = new WeakMap();
  13020. const uboProgamMap = new WeakMap();
  13021. let enabledCapabilities = {};
  13022. let currentBoundFramebuffers = {};
  13023. let currentDrawbuffers = new WeakMap();
  13024. let defaultDrawbuffers = [];
  13025. let currentProgram = null;
  13026. let currentBlendingEnabled = false;
  13027. let currentBlending = null;
  13028. let currentBlendEquation = null;
  13029. let currentBlendSrc = null;
  13030. let currentBlendDst = null;
  13031. let currentBlendEquationAlpha = null;
  13032. let currentBlendSrcAlpha = null;
  13033. let currentBlendDstAlpha = null;
  13034. let currentPremultipledAlpha = false;
  13035. let currentFlipSided = null;
  13036. let currentCullFace = null;
  13037. let currentLineWidth = null;
  13038. let currentPolygonOffsetFactor = null;
  13039. let currentPolygonOffsetUnits = null;
  13040. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13041. let lineWidthAvailable = false;
  13042. let version = 0;
  13043. const glVersion = gl.getParameter(gl.VERSION);
  13044. if (glVersion.indexOf('WebGL') !== -1) {
  13045. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13046. lineWidthAvailable = version >= 1.0;
  13047. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13048. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13049. lineWidthAvailable = version >= 2.0;
  13050. }
  13051. let currentTextureSlot = null;
  13052. let currentBoundTextures = {};
  13053. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13054. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13055. const currentScissor = new Vector4().fromArray(scissorParam);
  13056. const currentViewport = new Vector4().fromArray(viewportParam);
  13057. function createTexture(type, target, count) {
  13058. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13059. const texture = gl.createTexture();
  13060. gl.bindTexture(type, texture);
  13061. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13062. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13063. for (let i = 0; i < count; i++) {
  13064. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13065. }
  13066. return texture;
  13067. }
  13068. const emptyTextures = {};
  13069. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13070. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13071. colorBuffer.setClear(0, 0, 0, 1);
  13072. depthBuffer.setClear(1);
  13073. stencilBuffer.setClear(0);
  13074. enable(gl.DEPTH_TEST);
  13075. depthBuffer.setFunc(LessEqualDepth);
  13076. setFlipSided(false);
  13077. setCullFace(CullFaceBack);
  13078. enable(gl.CULL_FACE);
  13079. setBlending(NoBlending); //
  13080. function enable(id) {
  13081. if (enabledCapabilities[id] !== true) {
  13082. gl.enable(id);
  13083. enabledCapabilities[id] = true;
  13084. }
  13085. }
  13086. function disable(id) {
  13087. if (enabledCapabilities[id] !== false) {
  13088. gl.disable(id);
  13089. enabledCapabilities[id] = false;
  13090. }
  13091. }
  13092. function bindFramebuffer(target, framebuffer) {
  13093. if (currentBoundFramebuffers[target] !== framebuffer) {
  13094. gl.bindFramebuffer(target, framebuffer);
  13095. currentBoundFramebuffers[target] = framebuffer;
  13096. if (isWebGL2) {
  13097. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13098. if (target === gl.DRAW_FRAMEBUFFER) {
  13099. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13100. }
  13101. if (target === gl.FRAMEBUFFER) {
  13102. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13103. }
  13104. }
  13105. return true;
  13106. }
  13107. return false;
  13108. }
  13109. function drawBuffers(renderTarget, framebuffer) {
  13110. let drawBuffers = defaultDrawbuffers;
  13111. let needsUpdate = false;
  13112. if (renderTarget) {
  13113. drawBuffers = currentDrawbuffers.get(framebuffer);
  13114. if (drawBuffers === undefined) {
  13115. drawBuffers = [];
  13116. currentDrawbuffers.set(framebuffer, drawBuffers);
  13117. }
  13118. if (renderTarget.isWebGLMultipleRenderTargets) {
  13119. const textures = renderTarget.texture;
  13120. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13121. for (let i = 0, il = textures.length; i < il; i++) {
  13122. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13123. }
  13124. drawBuffers.length = textures.length;
  13125. needsUpdate = true;
  13126. }
  13127. } else {
  13128. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13129. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13130. needsUpdate = true;
  13131. }
  13132. }
  13133. } else {
  13134. if (drawBuffers[0] !== gl.BACK) {
  13135. drawBuffers[0] = gl.BACK;
  13136. needsUpdate = true;
  13137. }
  13138. }
  13139. if (needsUpdate) {
  13140. if (capabilities.isWebGL2) {
  13141. gl.drawBuffers(drawBuffers);
  13142. } else {
  13143. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13144. }
  13145. }
  13146. }
  13147. function useProgram(program) {
  13148. if (currentProgram !== program) {
  13149. gl.useProgram(program);
  13150. currentProgram = program;
  13151. return true;
  13152. }
  13153. return false;
  13154. }
  13155. const equationToGL = {
  13156. [AddEquation]: gl.FUNC_ADD,
  13157. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13158. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13159. };
  13160. if (isWebGL2) {
  13161. equationToGL[MinEquation] = gl.MIN;
  13162. equationToGL[MaxEquation] = gl.MAX;
  13163. } else {
  13164. const extension = extensions.get('EXT_blend_minmax');
  13165. if (extension !== null) {
  13166. equationToGL[MinEquation] = extension.MIN_EXT;
  13167. equationToGL[MaxEquation] = extension.MAX_EXT;
  13168. }
  13169. }
  13170. const factorToGL = {
  13171. [ZeroFactor]: gl.ZERO,
  13172. [OneFactor]: gl.ONE,
  13173. [SrcColorFactor]: gl.SRC_COLOR,
  13174. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13175. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13176. [DstColorFactor]: gl.DST_COLOR,
  13177. [DstAlphaFactor]: gl.DST_ALPHA,
  13178. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13179. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13180. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13181. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13182. };
  13183. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13184. if (blending === NoBlending) {
  13185. if (currentBlendingEnabled === true) {
  13186. disable(gl.BLEND);
  13187. currentBlendingEnabled = false;
  13188. }
  13189. return;
  13190. }
  13191. if (currentBlendingEnabled === false) {
  13192. enable(gl.BLEND);
  13193. currentBlendingEnabled = true;
  13194. }
  13195. if (blending !== CustomBlending) {
  13196. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13197. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13198. gl.blendEquation(gl.FUNC_ADD);
  13199. currentBlendEquation = AddEquation;
  13200. currentBlendEquationAlpha = AddEquation;
  13201. }
  13202. if (premultipliedAlpha) {
  13203. switch (blending) {
  13204. case NormalBlending:
  13205. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13206. break;
  13207. case AdditiveBlending:
  13208. gl.blendFunc(gl.ONE, gl.ONE);
  13209. break;
  13210. case SubtractiveBlending:
  13211. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13212. break;
  13213. case MultiplyBlending:
  13214. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13215. break;
  13216. default:
  13217. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13218. break;
  13219. }
  13220. } else {
  13221. switch (blending) {
  13222. case NormalBlending:
  13223. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13224. break;
  13225. case AdditiveBlending:
  13226. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13227. break;
  13228. case SubtractiveBlending:
  13229. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13230. break;
  13231. case MultiplyBlending:
  13232. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13233. break;
  13234. default:
  13235. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13236. break;
  13237. }
  13238. }
  13239. currentBlendSrc = null;
  13240. currentBlendDst = null;
  13241. currentBlendSrcAlpha = null;
  13242. currentBlendDstAlpha = null;
  13243. currentBlending = blending;
  13244. currentPremultipledAlpha = premultipliedAlpha;
  13245. }
  13246. return;
  13247. } // custom blending
  13248. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13249. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13250. blendDstAlpha = blendDstAlpha || blendDst;
  13251. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13252. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13253. currentBlendEquation = blendEquation;
  13254. currentBlendEquationAlpha = blendEquationAlpha;
  13255. }
  13256. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13257. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13258. currentBlendSrc = blendSrc;
  13259. currentBlendDst = blendDst;
  13260. currentBlendSrcAlpha = blendSrcAlpha;
  13261. currentBlendDstAlpha = blendDstAlpha;
  13262. }
  13263. currentBlending = blending;
  13264. currentPremultipledAlpha = null;
  13265. }
  13266. function setMaterial(material, frontFaceCW) {
  13267. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13268. let flipSided = material.side === BackSide;
  13269. if (frontFaceCW) flipSided = !flipSided;
  13270. setFlipSided(flipSided);
  13271. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  13272. depthBuffer.setFunc(material.depthFunc);
  13273. depthBuffer.setTest(material.depthTest);
  13274. depthBuffer.setMask(material.depthWrite);
  13275. colorBuffer.setMask(material.colorWrite);
  13276. const stencilWrite = material.stencilWrite;
  13277. stencilBuffer.setTest(stencilWrite);
  13278. if (stencilWrite) {
  13279. stencilBuffer.setMask(material.stencilWriteMask);
  13280. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13281. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13282. }
  13283. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13284. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13285. } //
  13286. function setFlipSided(flipSided) {
  13287. if (currentFlipSided !== flipSided) {
  13288. if (flipSided) {
  13289. gl.frontFace(gl.CW);
  13290. } else {
  13291. gl.frontFace(gl.CCW);
  13292. }
  13293. currentFlipSided = flipSided;
  13294. }
  13295. }
  13296. function setCullFace(cullFace) {
  13297. if (cullFace !== CullFaceNone) {
  13298. enable(gl.CULL_FACE);
  13299. if (cullFace !== currentCullFace) {
  13300. if (cullFace === CullFaceBack) {
  13301. gl.cullFace(gl.BACK);
  13302. } else if (cullFace === CullFaceFront) {
  13303. gl.cullFace(gl.FRONT);
  13304. } else {
  13305. gl.cullFace(gl.FRONT_AND_BACK);
  13306. }
  13307. }
  13308. } else {
  13309. disable(gl.CULL_FACE);
  13310. }
  13311. currentCullFace = cullFace;
  13312. }
  13313. function setLineWidth(width) {
  13314. if (width !== currentLineWidth) {
  13315. if (lineWidthAvailable) gl.lineWidth(width);
  13316. currentLineWidth = width;
  13317. }
  13318. }
  13319. function setPolygonOffset(polygonOffset, factor, units) {
  13320. if (polygonOffset) {
  13321. enable(gl.POLYGON_OFFSET_FILL);
  13322. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13323. gl.polygonOffset(factor, units);
  13324. currentPolygonOffsetFactor = factor;
  13325. currentPolygonOffsetUnits = units;
  13326. }
  13327. } else {
  13328. disable(gl.POLYGON_OFFSET_FILL);
  13329. }
  13330. }
  13331. function setScissorTest(scissorTest) {
  13332. if (scissorTest) {
  13333. enable(gl.SCISSOR_TEST);
  13334. } else {
  13335. disable(gl.SCISSOR_TEST);
  13336. }
  13337. } // texture
  13338. function activeTexture(webglSlot) {
  13339. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13340. if (currentTextureSlot !== webglSlot) {
  13341. gl.activeTexture(webglSlot);
  13342. currentTextureSlot = webglSlot;
  13343. }
  13344. }
  13345. function bindTexture(webglType, webglTexture) {
  13346. if (currentTextureSlot === null) {
  13347. activeTexture();
  13348. }
  13349. let boundTexture = currentBoundTextures[currentTextureSlot];
  13350. if (boundTexture === undefined) {
  13351. boundTexture = {
  13352. type: undefined,
  13353. texture: undefined
  13354. };
  13355. currentBoundTextures[currentTextureSlot] = boundTexture;
  13356. }
  13357. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13358. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13359. boundTexture.type = webglType;
  13360. boundTexture.texture = webglTexture;
  13361. }
  13362. }
  13363. function unbindTexture() {
  13364. const boundTexture = currentBoundTextures[currentTextureSlot];
  13365. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13366. gl.bindTexture(boundTexture.type, null);
  13367. boundTexture.type = undefined;
  13368. boundTexture.texture = undefined;
  13369. }
  13370. }
  13371. function compressedTexImage2D() {
  13372. try {
  13373. gl.compressedTexImage2D.apply(gl, arguments);
  13374. } catch (error) {
  13375. console.error('THREE.WebGLState:', error);
  13376. }
  13377. }
  13378. function texSubImage2D() {
  13379. try {
  13380. gl.texSubImage2D.apply(gl, arguments);
  13381. } catch (error) {
  13382. console.error('THREE.WebGLState:', error);
  13383. }
  13384. }
  13385. function texSubImage3D() {
  13386. try {
  13387. gl.texSubImage3D.apply(gl, arguments);
  13388. } catch (error) {
  13389. console.error('THREE.WebGLState:', error);
  13390. }
  13391. }
  13392. function compressedTexSubImage2D() {
  13393. try {
  13394. gl.compressedTexSubImage2D.apply(gl, arguments);
  13395. } catch (error) {
  13396. console.error('THREE.WebGLState:', error);
  13397. }
  13398. }
  13399. function texStorage2D() {
  13400. try {
  13401. gl.texStorage2D.apply(gl, arguments);
  13402. } catch (error) {
  13403. console.error('THREE.WebGLState:', error);
  13404. }
  13405. }
  13406. function texStorage3D() {
  13407. try {
  13408. gl.texStorage3D.apply(gl, arguments);
  13409. } catch (error) {
  13410. console.error('THREE.WebGLState:', error);
  13411. }
  13412. }
  13413. function texImage2D() {
  13414. try {
  13415. gl.texImage2D.apply(gl, arguments);
  13416. } catch (error) {
  13417. console.error('THREE.WebGLState:', error);
  13418. }
  13419. }
  13420. function texImage3D() {
  13421. try {
  13422. gl.texImage3D.apply(gl, arguments);
  13423. } catch (error) {
  13424. console.error('THREE.WebGLState:', error);
  13425. }
  13426. } //
  13427. function scissor(scissor) {
  13428. if (currentScissor.equals(scissor) === false) {
  13429. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13430. currentScissor.copy(scissor);
  13431. }
  13432. }
  13433. function viewport(viewport) {
  13434. if (currentViewport.equals(viewport) === false) {
  13435. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13436. currentViewport.copy(viewport);
  13437. }
  13438. }
  13439. function updateUBOMapping(uniformsGroup, program) {
  13440. let mapping = uboProgamMap.get(program);
  13441. if (mapping === undefined) {
  13442. mapping = new WeakMap();
  13443. uboProgamMap.set(program, mapping);
  13444. }
  13445. let blockIndex = mapping.get(uniformsGroup);
  13446. if (blockIndex === undefined) {
  13447. blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name);
  13448. mapping.set(uniformsGroup, blockIndex);
  13449. }
  13450. }
  13451. function uniformBlockBinding(uniformsGroup, program) {
  13452. const mapping = uboProgamMap.get(program);
  13453. const blockIndex = mapping.get(uniformsGroup);
  13454. if (uboBindings.get(uniformsGroup) !== blockIndex) {
  13455. // bind shader specific block index to global block point
  13456. gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex);
  13457. uboBindings.set(uniformsGroup, blockIndex);
  13458. }
  13459. } //
  13460. function reset() {
  13461. // reset state
  13462. gl.disable(gl.BLEND);
  13463. gl.disable(gl.CULL_FACE);
  13464. gl.disable(gl.DEPTH_TEST);
  13465. gl.disable(gl.POLYGON_OFFSET_FILL);
  13466. gl.disable(gl.SCISSOR_TEST);
  13467. gl.disable(gl.STENCIL_TEST);
  13468. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13469. gl.blendEquation(gl.FUNC_ADD);
  13470. gl.blendFunc(gl.ONE, gl.ZERO);
  13471. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13472. gl.colorMask(true, true, true, true);
  13473. gl.clearColor(0, 0, 0, 0);
  13474. gl.depthMask(true);
  13475. gl.depthFunc(gl.LESS);
  13476. gl.clearDepth(1);
  13477. gl.stencilMask(0xffffffff);
  13478. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13479. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13480. gl.clearStencil(0);
  13481. gl.cullFace(gl.BACK);
  13482. gl.frontFace(gl.CCW);
  13483. gl.polygonOffset(0, 0);
  13484. gl.activeTexture(gl.TEXTURE0);
  13485. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13486. if (isWebGL2 === true) {
  13487. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13488. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13489. }
  13490. gl.useProgram(null);
  13491. gl.lineWidth(1);
  13492. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13493. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13494. enabledCapabilities = {};
  13495. currentTextureSlot = null;
  13496. currentBoundTextures = {};
  13497. currentBoundFramebuffers = {};
  13498. currentDrawbuffers = new WeakMap();
  13499. defaultDrawbuffers = [];
  13500. currentProgram = null;
  13501. currentBlendingEnabled = false;
  13502. currentBlending = null;
  13503. currentBlendEquation = null;
  13504. currentBlendSrc = null;
  13505. currentBlendDst = null;
  13506. currentBlendEquationAlpha = null;
  13507. currentBlendSrcAlpha = null;
  13508. currentBlendDstAlpha = null;
  13509. currentPremultipledAlpha = false;
  13510. currentFlipSided = null;
  13511. currentCullFace = null;
  13512. currentLineWidth = null;
  13513. currentPolygonOffsetFactor = null;
  13514. currentPolygonOffsetUnits = null;
  13515. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13516. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13517. colorBuffer.reset();
  13518. depthBuffer.reset();
  13519. stencilBuffer.reset();
  13520. }
  13521. return {
  13522. buffers: {
  13523. color: colorBuffer,
  13524. depth: depthBuffer,
  13525. stencil: stencilBuffer
  13526. },
  13527. enable: enable,
  13528. disable: disable,
  13529. bindFramebuffer: bindFramebuffer,
  13530. drawBuffers: drawBuffers,
  13531. useProgram: useProgram,
  13532. setBlending: setBlending,
  13533. setMaterial: setMaterial,
  13534. setFlipSided: setFlipSided,
  13535. setCullFace: setCullFace,
  13536. setLineWidth: setLineWidth,
  13537. setPolygonOffset: setPolygonOffset,
  13538. setScissorTest: setScissorTest,
  13539. activeTexture: activeTexture,
  13540. bindTexture: bindTexture,
  13541. unbindTexture: unbindTexture,
  13542. compressedTexImage2D: compressedTexImage2D,
  13543. texImage2D: texImage2D,
  13544. texImage3D: texImage3D,
  13545. updateUBOMapping: updateUBOMapping,
  13546. uniformBlockBinding: uniformBlockBinding,
  13547. texStorage2D: texStorage2D,
  13548. texStorage3D: texStorage3D,
  13549. texSubImage2D: texSubImage2D,
  13550. texSubImage3D: texSubImage3D,
  13551. compressedTexSubImage2D: compressedTexSubImage2D,
  13552. scissor: scissor,
  13553. viewport: viewport,
  13554. reset: reset
  13555. };
  13556. }
  13557. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13558. const isWebGL2 = capabilities.isWebGL2;
  13559. const maxTextures = capabilities.maxTextures;
  13560. const maxCubemapSize = capabilities.maxCubemapSize;
  13561. const maxTextureSize = capabilities.maxTextureSize;
  13562. const maxSamples = capabilities.maxSamples;
  13563. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13564. const supportsInvalidateFramebuffer = /OculusBrowser/g.test(navigator.userAgent);
  13565. const _videoTextures = new WeakMap();
  13566. let _canvas;
  13567. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13568. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13569. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13570. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13571. let useOffscreenCanvas = false;
  13572. try {
  13573. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' // eslint-disable-next-line compat/compat
  13574. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13575. } catch (err) {// Ignore any errors
  13576. }
  13577. function createCanvas(width, height) {
  13578. // Use OffscreenCanvas when available. Specially needed in web workers
  13579. return useOffscreenCanvas ? // eslint-disable-next-line compat/compat
  13580. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13581. }
  13582. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13583. let scale = 1; // handle case if texture exceeds max size
  13584. if (image.width > maxSize || image.height > maxSize) {
  13585. scale = maxSize / Math.max(image.width, image.height);
  13586. } // only perform resize if necessary
  13587. if (scale < 1 || needsPowerOfTwo === true) {
  13588. // only perform resize for certain image types
  13589. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13590. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13591. const width = floor(scale * image.width);
  13592. const height = floor(scale * image.height);
  13593. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13594. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13595. canvas.width = width;
  13596. canvas.height = height;
  13597. const context = canvas.getContext('2d');
  13598. context.drawImage(image, 0, 0, width, height);
  13599. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13600. return canvas;
  13601. } else {
  13602. if ('data' in image) {
  13603. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13604. }
  13605. return image;
  13606. }
  13607. }
  13608. return image;
  13609. }
  13610. function isPowerOfTwo$1(image) {
  13611. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13612. }
  13613. function textureNeedsPowerOfTwo(texture) {
  13614. if (isWebGL2) return false;
  13615. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13616. }
  13617. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13618. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13619. }
  13620. function generateMipmap(target) {
  13621. _gl.generateMipmap(target);
  13622. }
  13623. function getInternalFormat(internalFormatName, glFormat, glType, encoding, isVideoTexture = false) {
  13624. if (isWebGL2 === false) return glFormat;
  13625. if (internalFormatName !== null) {
  13626. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13627. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13628. }
  13629. let internalFormat = glFormat;
  13630. if (glFormat === _gl.RED) {
  13631. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13632. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13633. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13634. }
  13635. if (glFormat === _gl.RG) {
  13636. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13637. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13638. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13639. }
  13640. if (glFormat === _gl.RGBA) {
  13641. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13642. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13643. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && isVideoTexture === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13644. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13645. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13646. }
  13647. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13648. extensions.get('EXT_color_buffer_float');
  13649. }
  13650. return internalFormat;
  13651. }
  13652. function getMipLevels(texture, image, supportsMips) {
  13653. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13654. return Math.log2(Math.max(image.width, image.height)) + 1;
  13655. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13656. // user-defined mipmaps
  13657. return texture.mipmaps.length;
  13658. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13659. return image.mipmaps.length;
  13660. } else {
  13661. // texture without mipmaps (only base level)
  13662. return 1;
  13663. }
  13664. } // Fallback filters for non-power-of-2 textures
  13665. function filterFallback(f) {
  13666. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13667. return _gl.NEAREST;
  13668. }
  13669. return _gl.LINEAR;
  13670. } //
  13671. function onTextureDispose(event) {
  13672. const texture = event.target;
  13673. texture.removeEventListener('dispose', onTextureDispose);
  13674. deallocateTexture(texture);
  13675. if (texture.isVideoTexture) {
  13676. _videoTextures.delete(texture);
  13677. }
  13678. }
  13679. function onRenderTargetDispose(event) {
  13680. const renderTarget = event.target;
  13681. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13682. deallocateRenderTarget(renderTarget);
  13683. } //
  13684. function deallocateTexture(texture) {
  13685. const textureProperties = properties.get(texture);
  13686. if (textureProperties.__webglInit === undefined) return; // check if it's necessary to remove the WebGLTexture object
  13687. const source = texture.source;
  13688. const webglTextures = _sources.get(source);
  13689. if (webglTextures) {
  13690. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13691. webglTexture.usedTimes--; // the WebGLTexture object is not used anymore, remove it
  13692. if (webglTexture.usedTimes === 0) {
  13693. deleteTexture(texture);
  13694. } // remove the weak map entry if no WebGLTexture uses the source anymore
  13695. if (Object.keys(webglTextures).length === 0) {
  13696. _sources.delete(source);
  13697. }
  13698. }
  13699. properties.remove(texture);
  13700. }
  13701. function deleteTexture(texture) {
  13702. const textureProperties = properties.get(texture);
  13703. _gl.deleteTexture(textureProperties.__webglTexture);
  13704. const source = texture.source;
  13705. const webglTextures = _sources.get(source);
  13706. delete webglTextures[textureProperties.__cacheKey];
  13707. info.memory.textures--;
  13708. }
  13709. function deallocateRenderTarget(renderTarget) {
  13710. const texture = renderTarget.texture;
  13711. const renderTargetProperties = properties.get(renderTarget);
  13712. const textureProperties = properties.get(texture);
  13713. if (textureProperties.__webglTexture !== undefined) {
  13714. _gl.deleteTexture(textureProperties.__webglTexture);
  13715. info.memory.textures--;
  13716. }
  13717. if (renderTarget.depthTexture) {
  13718. renderTarget.depthTexture.dispose();
  13719. }
  13720. if (renderTarget.isWebGLCubeRenderTarget) {
  13721. for (let i = 0; i < 6; i++) {
  13722. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13723. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13724. }
  13725. } else {
  13726. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13727. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13728. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13729. if (renderTargetProperties.__webglColorRenderbuffer) {
  13730. for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) {
  13731. if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]);
  13732. }
  13733. }
  13734. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13735. }
  13736. if (renderTarget.isWebGLMultipleRenderTargets) {
  13737. for (let i = 0, il = texture.length; i < il; i++) {
  13738. const attachmentProperties = properties.get(texture[i]);
  13739. if (attachmentProperties.__webglTexture) {
  13740. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13741. info.memory.textures--;
  13742. }
  13743. properties.remove(texture[i]);
  13744. }
  13745. }
  13746. properties.remove(texture);
  13747. properties.remove(renderTarget);
  13748. } //
  13749. let textureUnits = 0;
  13750. function resetTextureUnits() {
  13751. textureUnits = 0;
  13752. }
  13753. function allocateTextureUnit() {
  13754. const textureUnit = textureUnits;
  13755. if (textureUnit >= maxTextures) {
  13756. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13757. }
  13758. textureUnits += 1;
  13759. return textureUnit;
  13760. }
  13761. function getTextureCacheKey(texture) {
  13762. const array = [];
  13763. array.push(texture.wrapS);
  13764. array.push(texture.wrapT);
  13765. array.push(texture.magFilter);
  13766. array.push(texture.minFilter);
  13767. array.push(texture.anisotropy);
  13768. array.push(texture.internalFormat);
  13769. array.push(texture.format);
  13770. array.push(texture.type);
  13771. array.push(texture.generateMipmaps);
  13772. array.push(texture.premultiplyAlpha);
  13773. array.push(texture.flipY);
  13774. array.push(texture.unpackAlignment);
  13775. array.push(texture.encoding);
  13776. return array.join();
  13777. } //
  13778. function setTexture2D(texture, slot) {
  13779. const textureProperties = properties.get(texture);
  13780. if (texture.isVideoTexture) updateVideoTexture(texture);
  13781. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  13782. const image = texture.image;
  13783. if (image === null) {
  13784. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  13785. } else if (image.complete === false) {
  13786. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13787. } else {
  13788. uploadTexture(textureProperties, texture, slot);
  13789. return;
  13790. }
  13791. }
  13792. state.activeTexture(_gl.TEXTURE0 + slot);
  13793. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13794. }
  13795. function setTexture2DArray(texture, slot) {
  13796. const textureProperties = properties.get(texture);
  13797. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13798. uploadTexture(textureProperties, texture, slot);
  13799. return;
  13800. }
  13801. state.activeTexture(_gl.TEXTURE0 + slot);
  13802. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13803. }
  13804. function setTexture3D(texture, slot) {
  13805. const textureProperties = properties.get(texture);
  13806. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13807. uploadTexture(textureProperties, texture, slot);
  13808. return;
  13809. }
  13810. state.activeTexture(_gl.TEXTURE0 + slot);
  13811. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13812. }
  13813. function setTextureCube(texture, slot) {
  13814. const textureProperties = properties.get(texture);
  13815. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13816. uploadCubeTexture(textureProperties, texture, slot);
  13817. return;
  13818. }
  13819. state.activeTexture(_gl.TEXTURE0 + slot);
  13820. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13821. }
  13822. const wrappingToGL = {
  13823. [RepeatWrapping]: _gl.REPEAT,
  13824. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13825. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13826. };
  13827. const filterToGL = {
  13828. [NearestFilter]: _gl.NEAREST,
  13829. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13830. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13831. [LinearFilter]: _gl.LINEAR,
  13832. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13833. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13834. };
  13835. function setTextureParameters(textureType, texture, supportsMips) {
  13836. if (supportsMips) {
  13837. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13838. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13839. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13840. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13841. }
  13842. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13843. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13844. } else {
  13845. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13846. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13847. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13848. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13849. }
  13850. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13851. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13852. }
  13853. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13854. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13855. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13856. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13857. }
  13858. }
  13859. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13860. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13861. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13862. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13863. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13864. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13865. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13866. }
  13867. }
  13868. }
  13869. function initTexture(textureProperties, texture) {
  13870. let forceUpload = false;
  13871. if (textureProperties.__webglInit === undefined) {
  13872. textureProperties.__webglInit = true;
  13873. texture.addEventListener('dispose', onTextureDispose);
  13874. } // create Source <-> WebGLTextures mapping if necessary
  13875. const source = texture.source;
  13876. let webglTextures = _sources.get(source);
  13877. if (webglTextures === undefined) {
  13878. webglTextures = {};
  13879. _sources.set(source, webglTextures);
  13880. } // check if there is already a WebGLTexture object for the given texture parameters
  13881. const textureCacheKey = getTextureCacheKey(texture);
  13882. if (textureCacheKey !== textureProperties.__cacheKey) {
  13883. // if not, create a new instance of WebGLTexture
  13884. if (webglTextures[textureCacheKey] === undefined) {
  13885. // create new entry
  13886. webglTextures[textureCacheKey] = {
  13887. texture: _gl.createTexture(),
  13888. usedTimes: 0
  13889. };
  13890. info.memory.textures++; // when a new instance of WebGLTexture was created, a texture upload is required
  13891. // even if the image contents are identical
  13892. forceUpload = true;
  13893. }
  13894. webglTextures[textureCacheKey].usedTimes++; // every time the texture cache key changes, it's necessary to check if an instance of
  13895. // WebGLTexture can be deleted in order to avoid a memory leak.
  13896. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13897. if (webglTexture !== undefined) {
  13898. webglTextures[textureProperties.__cacheKey].usedTimes--;
  13899. if (webglTexture.usedTimes === 0) {
  13900. deleteTexture(texture);
  13901. }
  13902. } // store references to cache key and WebGLTexture object
  13903. textureProperties.__cacheKey = textureCacheKey;
  13904. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  13905. }
  13906. return forceUpload;
  13907. }
  13908. function uploadTexture(textureProperties, texture, slot) {
  13909. let textureType = _gl.TEXTURE_2D;
  13910. if (texture.isDataArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  13911. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  13912. const forceUpload = initTexture(textureProperties, texture);
  13913. const source = texture.source;
  13914. state.activeTexture(_gl.TEXTURE0 + slot);
  13915. state.bindTexture(textureType, textureProperties.__webglTexture);
  13916. if (source.version !== source.__currentVersion || forceUpload === true) {
  13917. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13918. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13919. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13920. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13921. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13922. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13923. image = verifyColorSpace(texture, image);
  13924. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13925. glFormat = utils.convert(texture.format, texture.encoding);
  13926. let glType = utils.convert(texture.type),
  13927. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  13928. setTextureParameters(textureType, texture, supportsMips);
  13929. let mipmap;
  13930. const mipmaps = texture.mipmaps;
  13931. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13932. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  13933. const levels = getMipLevels(texture, image, supportsMips);
  13934. if (texture.isDepthTexture) {
  13935. // populate depth texture with dummy data
  13936. glInternalFormat = _gl.DEPTH_COMPONENT;
  13937. if (isWebGL2) {
  13938. if (texture.type === FloatType) {
  13939. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13940. } else if (texture.type === UnsignedIntType) {
  13941. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13942. } else if (texture.type === UnsignedInt248Type) {
  13943. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13944. } else {
  13945. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13946. }
  13947. } else {
  13948. if (texture.type === FloatType) {
  13949. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13950. }
  13951. } // validation checks for WebGL 1
  13952. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13953. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13954. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13955. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13956. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13957. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13958. texture.type = UnsignedIntType;
  13959. glType = utils.convert(texture.type);
  13960. }
  13961. }
  13962. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13963. // Depth stencil textures need the DEPTH_STENCIL internal format
  13964. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13965. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13966. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13967. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13968. if (texture.type !== UnsignedInt248Type) {
  13969. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13970. texture.type = UnsignedInt248Type;
  13971. glType = utils.convert(texture.type);
  13972. }
  13973. } //
  13974. if (allocateMemory) {
  13975. if (useTexStorage) {
  13976. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13977. } else {
  13978. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13979. }
  13980. }
  13981. } else if (texture.isDataTexture) {
  13982. // use manually created mipmaps if available
  13983. // if there are no manual mipmaps
  13984. // set 0 level mipmap and then use GL to generate other mipmap levels
  13985. if (mipmaps.length > 0 && supportsMips) {
  13986. if (useTexStorage && allocateMemory) {
  13987. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13988. }
  13989. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13990. mipmap = mipmaps[i];
  13991. if (useTexStorage) {
  13992. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13993. } else {
  13994. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13995. }
  13996. }
  13997. texture.generateMipmaps = false;
  13998. } else {
  13999. if (useTexStorage) {
  14000. if (allocateMemory) {
  14001. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14002. }
  14003. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  14004. } else {
  14005. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14006. }
  14007. }
  14008. } else if (texture.isCompressedTexture) {
  14009. if (useTexStorage && allocateMemory) {
  14010. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14011. }
  14012. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14013. mipmap = mipmaps[i];
  14014. if (texture.format !== RGBAFormat) {
  14015. if (glFormat !== null) {
  14016. if (useTexStorage) {
  14017. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14018. } else {
  14019. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14020. }
  14021. } else {
  14022. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14023. }
  14024. } else {
  14025. if (useTexStorage) {
  14026. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14027. } else {
  14028. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14029. }
  14030. }
  14031. }
  14032. } else if (texture.isDataArrayTexture) {
  14033. if (useTexStorage) {
  14034. if (allocateMemory) {
  14035. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  14036. }
  14037. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14038. } else {
  14039. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14040. }
  14041. } else if (texture.isData3DTexture) {
  14042. if (useTexStorage) {
  14043. if (allocateMemory) {
  14044. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  14045. }
  14046. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14047. } else {
  14048. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14049. }
  14050. } else if (texture.isFramebufferTexture) {
  14051. if (allocateMemory) {
  14052. if (useTexStorage) {
  14053. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14054. } else {
  14055. let width = image.width,
  14056. height = image.height;
  14057. for (let i = 0; i < levels; i++) {
  14058. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14059. width >>= 1;
  14060. height >>= 1;
  14061. }
  14062. }
  14063. }
  14064. } else {
  14065. // regular Texture (image, video, canvas)
  14066. // use manually created mipmaps if available
  14067. // if there are no manual mipmaps
  14068. // set 0 level mipmap and then use GL to generate other mipmap levels
  14069. if (mipmaps.length > 0 && supportsMips) {
  14070. if (useTexStorage && allocateMemory) {
  14071. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14072. }
  14073. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14074. mipmap = mipmaps[i];
  14075. if (useTexStorage) {
  14076. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14077. } else {
  14078. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14079. }
  14080. }
  14081. texture.generateMipmaps = false;
  14082. } else {
  14083. if (useTexStorage) {
  14084. if (allocateMemory) {
  14085. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14086. }
  14087. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14088. } else {
  14089. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14090. }
  14091. }
  14092. }
  14093. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14094. generateMipmap(textureType);
  14095. }
  14096. source.__currentVersion = source.version;
  14097. if (texture.onUpdate) texture.onUpdate(texture);
  14098. }
  14099. textureProperties.__version = texture.version;
  14100. }
  14101. function uploadCubeTexture(textureProperties, texture, slot) {
  14102. if (texture.image.length !== 6) return;
  14103. const forceUpload = initTexture(textureProperties, texture);
  14104. const source = texture.source;
  14105. state.activeTexture(_gl.TEXTURE0 + slot);
  14106. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14107. if (source.version !== source.__currentVersion || forceUpload === true) {
  14108. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14109. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14110. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14111. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14112. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14113. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14114. const cubeImage = [];
  14115. for (let i = 0; i < 6; i++) {
  14116. if (!isCompressed && !isDataTexture) {
  14117. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14118. } else {
  14119. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14120. }
  14121. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14122. }
  14123. const image = cubeImage[0],
  14124. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14125. glFormat = utils.convert(texture.format, texture.encoding),
  14126. glType = utils.convert(texture.type),
  14127. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14128. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14129. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  14130. let levels = getMipLevels(texture, image, supportsMips);
  14131. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14132. let mipmaps;
  14133. if (isCompressed) {
  14134. if (useTexStorage && allocateMemory) {
  14135. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14136. }
  14137. for (let i = 0; i < 6; i++) {
  14138. mipmaps = cubeImage[i].mipmaps;
  14139. for (let j = 0; j < mipmaps.length; j++) {
  14140. const mipmap = mipmaps[j];
  14141. if (texture.format !== RGBAFormat) {
  14142. if (glFormat !== null) {
  14143. if (useTexStorage) {
  14144. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14145. } else {
  14146. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14147. }
  14148. } else {
  14149. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14150. }
  14151. } else {
  14152. if (useTexStorage) {
  14153. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14154. } else {
  14155. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14156. }
  14157. }
  14158. }
  14159. }
  14160. } else {
  14161. mipmaps = texture.mipmaps;
  14162. if (useTexStorage && allocateMemory) {
  14163. // TODO: Uniformly handle mipmap definitions
  14164. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14165. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14166. if (mipmaps.length > 0) levels++;
  14167. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14168. }
  14169. for (let i = 0; i < 6; i++) {
  14170. if (isDataTexture) {
  14171. if (useTexStorage) {
  14172. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14173. } else {
  14174. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14175. }
  14176. for (let j = 0; j < mipmaps.length; j++) {
  14177. const mipmap = mipmaps[j];
  14178. const mipmapImage = mipmap.image[i].image;
  14179. if (useTexStorage) {
  14180. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14181. } else {
  14182. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14183. }
  14184. }
  14185. } else {
  14186. if (useTexStorage) {
  14187. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14188. } else {
  14189. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14190. }
  14191. for (let j = 0; j < mipmaps.length; j++) {
  14192. const mipmap = mipmaps[j];
  14193. if (useTexStorage) {
  14194. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14195. } else {
  14196. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14197. }
  14198. }
  14199. }
  14200. }
  14201. }
  14202. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14203. // We assume images for cube map have the same size.
  14204. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14205. }
  14206. source.__currentVersion = source.version;
  14207. if (texture.onUpdate) texture.onUpdate(texture);
  14208. }
  14209. textureProperties.__version = texture.version;
  14210. } // Render targets
  14211. // Setup storage for target texture and bind it to correct framebuffer
  14212. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14213. const glFormat = utils.convert(texture.format, texture.encoding);
  14214. const glType = utils.convert(texture.type);
  14215. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14216. const renderTargetProperties = properties.get(renderTarget);
  14217. if (!renderTargetProperties.__hasExternalTextures) {
  14218. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14219. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14220. } else {
  14221. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14222. }
  14223. }
  14224. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14225. if (useMultisampledRTT(renderTarget)) {
  14226. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14227. } else {
  14228. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14229. }
  14230. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14231. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14232. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14233. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14234. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14235. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14236. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14237. const depthTexture = renderTarget.depthTexture;
  14238. if (depthTexture && depthTexture.isDepthTexture) {
  14239. if (depthTexture.type === FloatType) {
  14240. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14241. } else if (depthTexture.type === UnsignedIntType) {
  14242. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14243. }
  14244. }
  14245. const samples = getRenderTargetSamples(renderTarget);
  14246. if (useMultisampledRTT(renderTarget)) {
  14247. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14248. } else {
  14249. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14250. }
  14251. } else {
  14252. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14253. }
  14254. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14255. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14256. const samples = getRenderTargetSamples(renderTarget);
  14257. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14258. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14259. } else if (useMultisampledRTT(renderTarget)) {
  14260. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14261. } else {
  14262. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14263. }
  14264. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14265. } else {
  14266. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14267. for (let i = 0; i < textures.length; i++) {
  14268. const texture = textures[i];
  14269. const glFormat = utils.convert(texture.format, texture.encoding);
  14270. const glType = utils.convert(texture.type);
  14271. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14272. const samples = getRenderTargetSamples(renderTarget);
  14273. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14274. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14275. } else if (useMultisampledRTT(renderTarget)) {
  14276. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14277. } else {
  14278. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14279. }
  14280. }
  14281. }
  14282. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14283. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14284. function setupDepthTexture(framebuffer, renderTarget) {
  14285. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14286. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14287. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14288. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14289. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14290. } // upload an empty depth texture with framebuffer size
  14291. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14292. renderTarget.depthTexture.image.width = renderTarget.width;
  14293. renderTarget.depthTexture.image.height = renderTarget.height;
  14294. renderTarget.depthTexture.needsUpdate = true;
  14295. }
  14296. setTexture2D(renderTarget.depthTexture, 0);
  14297. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14298. const samples = getRenderTargetSamples(renderTarget);
  14299. if (renderTarget.depthTexture.format === DepthFormat) {
  14300. if (useMultisampledRTT(renderTarget)) {
  14301. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14302. } else {
  14303. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14304. }
  14305. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14306. if (useMultisampledRTT(renderTarget)) {
  14307. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14308. } else {
  14309. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14310. }
  14311. } else {
  14312. throw new Error('Unknown depthTexture format');
  14313. }
  14314. } // Setup GL resources for a non-texture depth buffer
  14315. function setupDepthRenderbuffer(renderTarget) {
  14316. const renderTargetProperties = properties.get(renderTarget);
  14317. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14318. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14319. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14320. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14321. } else {
  14322. if (isCube) {
  14323. renderTargetProperties.__webglDepthbuffer = [];
  14324. for (let i = 0; i < 6; i++) {
  14325. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14326. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14327. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14328. }
  14329. } else {
  14330. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14331. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14332. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14333. }
  14334. }
  14335. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14336. } // rebind framebuffer with external textures
  14337. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14338. const renderTargetProperties = properties.get(renderTarget);
  14339. if (colorTexture !== undefined) {
  14340. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14341. }
  14342. if (depthTexture !== undefined) {
  14343. setupDepthRenderbuffer(renderTarget);
  14344. }
  14345. } // Set up GL resources for the render target
  14346. function setupRenderTarget(renderTarget) {
  14347. const texture = renderTarget.texture;
  14348. const renderTargetProperties = properties.get(renderTarget);
  14349. const textureProperties = properties.get(texture);
  14350. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14351. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14352. if (textureProperties.__webglTexture === undefined) {
  14353. textureProperties.__webglTexture = _gl.createTexture();
  14354. }
  14355. textureProperties.__version = texture.version;
  14356. info.memory.textures++;
  14357. }
  14358. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14359. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14360. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
  14361. if (isCube) {
  14362. renderTargetProperties.__webglFramebuffer = [];
  14363. for (let i = 0; i < 6; i++) {
  14364. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14365. }
  14366. } else {
  14367. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14368. if (isMultipleRenderTargets) {
  14369. if (capabilities.drawBuffers) {
  14370. const textures = renderTarget.texture;
  14371. for (let i = 0, il = textures.length; i < il; i++) {
  14372. const attachmentProperties = properties.get(textures[i]);
  14373. if (attachmentProperties.__webglTexture === undefined) {
  14374. attachmentProperties.__webglTexture = _gl.createTexture();
  14375. info.memory.textures++;
  14376. }
  14377. }
  14378. } else {
  14379. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14380. }
  14381. }
  14382. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14383. const textures = isMultipleRenderTargets ? texture : [texture];
  14384. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14385. renderTargetProperties.__webglColorRenderbuffer = [];
  14386. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14387. for (let i = 0; i < textures.length; i++) {
  14388. const texture = textures[i];
  14389. renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer();
  14390. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14391. const glFormat = utils.convert(texture.format, texture.encoding);
  14392. const glType = utils.convert(texture.type);
  14393. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14394. const samples = getRenderTargetSamples(renderTarget);
  14395. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14396. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14397. }
  14398. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14399. if (renderTarget.depthBuffer) {
  14400. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14401. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14402. }
  14403. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14404. }
  14405. } // Setup color buffer
  14406. if (isCube) {
  14407. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14408. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14409. for (let i = 0; i < 6; i++) {
  14410. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14411. }
  14412. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14413. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14414. }
  14415. state.unbindTexture();
  14416. } else if (isMultipleRenderTargets) {
  14417. const textures = renderTarget.texture;
  14418. for (let i = 0, il = textures.length; i < il; i++) {
  14419. const attachment = textures[i];
  14420. const attachmentProperties = properties.get(attachment);
  14421. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14422. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14423. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14424. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14425. generateMipmap(_gl.TEXTURE_2D);
  14426. }
  14427. }
  14428. state.unbindTexture();
  14429. } else {
  14430. let glTextureType = _gl.TEXTURE_2D;
  14431. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14432. if (isWebGL2) {
  14433. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14434. } else {
  14435. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14436. }
  14437. }
  14438. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14439. setTextureParameters(glTextureType, texture, supportsMips);
  14440. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14441. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14442. generateMipmap(glTextureType);
  14443. }
  14444. state.unbindTexture();
  14445. } // Setup depth and stencil buffers
  14446. if (renderTarget.depthBuffer) {
  14447. setupDepthRenderbuffer(renderTarget);
  14448. }
  14449. }
  14450. function updateRenderTargetMipmap(renderTarget) {
  14451. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14452. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14453. for (let i = 0, il = textures.length; i < il; i++) {
  14454. const texture = textures[i];
  14455. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14456. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14457. const webglTexture = properties.get(texture).__webglTexture;
  14458. state.bindTexture(target, webglTexture);
  14459. generateMipmap(target);
  14460. state.unbindTexture();
  14461. }
  14462. }
  14463. }
  14464. function updateMultisampleRenderTarget(renderTarget) {
  14465. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14466. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture];
  14467. const width = renderTarget.width;
  14468. const height = renderTarget.height;
  14469. let mask = _gl.COLOR_BUFFER_BIT;
  14470. const invalidationArray = [];
  14471. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14472. const renderTargetProperties = properties.get(renderTarget);
  14473. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; // If MRT we need to remove FBO attachments
  14474. if (isMultipleRenderTargets) {
  14475. for (let i = 0; i < textures.length; i++) {
  14476. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14477. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null);
  14478. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14479. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0);
  14480. }
  14481. }
  14482. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14483. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14484. for (let i = 0; i < textures.length; i++) {
  14485. invalidationArray.push(_gl.COLOR_ATTACHMENT0 + i);
  14486. if (renderTarget.depthBuffer) {
  14487. invalidationArray.push(depthStyle);
  14488. }
  14489. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14490. if (ignoreDepthValues === false) {
  14491. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14492. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14493. }
  14494. if (isMultipleRenderTargets) {
  14495. _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14496. }
  14497. if (ignoreDepthValues === true) {
  14498. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14499. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14500. }
  14501. if (isMultipleRenderTargets) {
  14502. const webglTexture = properties.get(textures[i]).__webglTexture;
  14503. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0);
  14504. }
  14505. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14506. if (supportsInvalidateFramebuffer) {
  14507. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14508. }
  14509. }
  14510. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14511. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14512. if (isMultipleRenderTargets) {
  14513. for (let i = 0; i < textures.length; i++) {
  14514. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14515. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]);
  14516. const webglTexture = properties.get(textures[i]).__webglTexture;
  14517. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14518. _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0);
  14519. }
  14520. }
  14521. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14522. }
  14523. }
  14524. function getRenderTargetSamples(renderTarget) {
  14525. return Math.min(maxSamples, renderTarget.samples);
  14526. }
  14527. function useMultisampledRTT(renderTarget) {
  14528. const renderTargetProperties = properties.get(renderTarget);
  14529. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14530. }
  14531. function updateVideoTexture(texture) {
  14532. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14533. if (_videoTextures.get(texture) !== frame) {
  14534. _videoTextures.set(texture, frame);
  14535. texture.update();
  14536. }
  14537. }
  14538. function verifyColorSpace(texture, image) {
  14539. const encoding = texture.encoding;
  14540. const format = texture.format;
  14541. const type = texture.type;
  14542. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14543. if (encoding !== LinearEncoding) {
  14544. // sRGB
  14545. if (encoding === sRGBEncoding) {
  14546. if (isWebGL2 === false) {
  14547. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14548. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14549. texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
  14550. texture.minFilter = LinearFilter;
  14551. texture.generateMipmaps = false;
  14552. } else {
  14553. // slow fallback (CPU decode)
  14554. image = ImageUtils.sRGBToLinear(image);
  14555. }
  14556. } else {
  14557. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14558. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14559. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14560. }
  14561. }
  14562. } else {
  14563. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14564. }
  14565. }
  14566. return image;
  14567. } //
  14568. this.allocateTextureUnit = allocateTextureUnit;
  14569. this.resetTextureUnits = resetTextureUnits;
  14570. this.setTexture2D = setTexture2D;
  14571. this.setTexture2DArray = setTexture2DArray;
  14572. this.setTexture3D = setTexture3D;
  14573. this.setTextureCube = setTextureCube;
  14574. this.rebindTextures = rebindTextures;
  14575. this.setupRenderTarget = setupRenderTarget;
  14576. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14577. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14578. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14579. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14580. this.useMultisampledRTT = useMultisampledRTT;
  14581. }
  14582. function WebGLUtils(gl, extensions, capabilities) {
  14583. const isWebGL2 = capabilities.isWebGL2;
  14584. function convert(p, encoding = null) {
  14585. let extension;
  14586. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14587. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14588. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14589. if (p === ByteType) return gl.BYTE;
  14590. if (p === ShortType) return gl.SHORT;
  14591. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14592. if (p === IntType) return gl.INT;
  14593. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14594. if (p === FloatType) return gl.FLOAT;
  14595. if (p === HalfFloatType) {
  14596. if (isWebGL2) return gl.HALF_FLOAT;
  14597. extension = extensions.get('OES_texture_half_float');
  14598. if (extension !== null) {
  14599. return extension.HALF_FLOAT_OES;
  14600. } else {
  14601. return null;
  14602. }
  14603. }
  14604. if (p === AlphaFormat) return gl.ALPHA;
  14605. if (p === RGBAFormat) return gl.RGBA;
  14606. if (p === LuminanceFormat) return gl.LUMINANCE;
  14607. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14608. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14609. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14610. if (p === RedFormat) return gl.RED; // @deprecated since r137
  14611. if (p === RGBFormat) {
  14612. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14613. return gl.RGBA;
  14614. } // WebGL 1 sRGB fallback
  14615. if (p === _SRGBAFormat) {
  14616. extension = extensions.get('EXT_sRGB');
  14617. if (extension !== null) {
  14618. return extension.SRGB_ALPHA_EXT;
  14619. } else {
  14620. return null;
  14621. }
  14622. } // WebGL2 formats.
  14623. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14624. if (p === RGFormat) return gl.RG;
  14625. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14626. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; // S3TC
  14627. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14628. if (encoding === sRGBEncoding) {
  14629. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14630. if (extension !== null) {
  14631. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14632. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14633. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14634. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14635. } else {
  14636. return null;
  14637. }
  14638. } else {
  14639. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14640. if (extension !== null) {
  14641. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14642. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14643. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14644. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14645. } else {
  14646. return null;
  14647. }
  14648. }
  14649. } // PVRTC
  14650. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14651. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14652. if (extension !== null) {
  14653. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14654. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14655. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14656. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14657. } else {
  14658. return null;
  14659. }
  14660. } // ETC1
  14661. if (p === RGB_ETC1_Format) {
  14662. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14663. if (extension !== null) {
  14664. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14665. } else {
  14666. return null;
  14667. }
  14668. } // ETC2
  14669. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14670. extension = extensions.get('WEBGL_compressed_texture_etc');
  14671. if (extension !== null) {
  14672. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14673. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14674. } else {
  14675. return null;
  14676. }
  14677. } // ASTC
  14678. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) {
  14679. extension = extensions.get('WEBGL_compressed_texture_astc');
  14680. if (extension !== null) {
  14681. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14682. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14683. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14684. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14685. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14686. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14687. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14688. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14689. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14690. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14691. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14692. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14693. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14694. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14695. } else {
  14696. return null;
  14697. }
  14698. } // BPTC
  14699. if (p === RGBA_BPTC_Format) {
  14700. extension = extensions.get('EXT_texture_compression_bptc');
  14701. if (extension !== null) {
  14702. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14703. } else {
  14704. return null;
  14705. }
  14706. } //
  14707. if (p === UnsignedInt248Type) {
  14708. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14709. extension = extensions.get('WEBGL_depth_texture');
  14710. if (extension !== null) {
  14711. return extension.UNSIGNED_INT_24_8_WEBGL;
  14712. } else {
  14713. return null;
  14714. }
  14715. } // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14716. return gl[p] !== undefined ? gl[p] : null;
  14717. }
  14718. return {
  14719. convert: convert
  14720. };
  14721. }
  14722. class ArrayCamera extends PerspectiveCamera {
  14723. constructor(array = []) {
  14724. super();
  14725. this.isArrayCamera = true;
  14726. this.cameras = array;
  14727. }
  14728. }
  14729. class Group extends Object3D {
  14730. constructor() {
  14731. super();
  14732. this.isGroup = true;
  14733. this.type = 'Group';
  14734. }
  14735. }
  14736. const _moveEvent = {
  14737. type: 'move'
  14738. };
  14739. class WebXRController {
  14740. constructor() {
  14741. this._targetRay = null;
  14742. this._grip = null;
  14743. this._hand = null;
  14744. }
  14745. getHandSpace() {
  14746. if (this._hand === null) {
  14747. this._hand = new Group();
  14748. this._hand.matrixAutoUpdate = false;
  14749. this._hand.visible = false;
  14750. this._hand.joints = {};
  14751. this._hand.inputState = {
  14752. pinching: false
  14753. };
  14754. }
  14755. return this._hand;
  14756. }
  14757. getTargetRaySpace() {
  14758. if (this._targetRay === null) {
  14759. this._targetRay = new Group();
  14760. this._targetRay.matrixAutoUpdate = false;
  14761. this._targetRay.visible = false;
  14762. this._targetRay.hasLinearVelocity = false;
  14763. this._targetRay.linearVelocity = new Vector3();
  14764. this._targetRay.hasAngularVelocity = false;
  14765. this._targetRay.angularVelocity = new Vector3();
  14766. }
  14767. return this._targetRay;
  14768. }
  14769. getGripSpace() {
  14770. if (this._grip === null) {
  14771. this._grip = new Group();
  14772. this._grip.matrixAutoUpdate = false;
  14773. this._grip.visible = false;
  14774. this._grip.hasLinearVelocity = false;
  14775. this._grip.linearVelocity = new Vector3();
  14776. this._grip.hasAngularVelocity = false;
  14777. this._grip.angularVelocity = new Vector3();
  14778. }
  14779. return this._grip;
  14780. }
  14781. dispatchEvent(event) {
  14782. if (this._targetRay !== null) {
  14783. this._targetRay.dispatchEvent(event);
  14784. }
  14785. if (this._grip !== null) {
  14786. this._grip.dispatchEvent(event);
  14787. }
  14788. if (this._hand !== null) {
  14789. this._hand.dispatchEvent(event);
  14790. }
  14791. return this;
  14792. }
  14793. disconnect(inputSource) {
  14794. this.dispatchEvent({
  14795. type: 'disconnected',
  14796. data: inputSource
  14797. });
  14798. if (this._targetRay !== null) {
  14799. this._targetRay.visible = false;
  14800. }
  14801. if (this._grip !== null) {
  14802. this._grip.visible = false;
  14803. }
  14804. if (this._hand !== null) {
  14805. this._hand.visible = false;
  14806. }
  14807. return this;
  14808. }
  14809. update(inputSource, frame, referenceSpace) {
  14810. let inputPose = null;
  14811. let gripPose = null;
  14812. let handPose = null;
  14813. const targetRay = this._targetRay;
  14814. const grip = this._grip;
  14815. const hand = this._hand;
  14816. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14817. if (hand && inputSource.hand) {
  14818. handPose = true;
  14819. for (const inputjoint of inputSource.hand.values()) {
  14820. // Update the joints groups with the XRJoint poses
  14821. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14822. if (hand.joints[inputjoint.jointName] === undefined) {
  14823. // The transform of this joint will be updated with the joint pose on each frame
  14824. const joint = new Group();
  14825. joint.matrixAutoUpdate = false;
  14826. joint.visible = false;
  14827. hand.joints[inputjoint.jointName] = joint; // ??
  14828. hand.add(joint);
  14829. }
  14830. const joint = hand.joints[inputjoint.jointName];
  14831. if (jointPose !== null) {
  14832. joint.matrix.fromArray(jointPose.transform.matrix);
  14833. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14834. joint.jointRadius = jointPose.radius;
  14835. }
  14836. joint.visible = jointPose !== null;
  14837. } // Custom events
  14838. // Check pinchz
  14839. const indexTip = hand.joints['index-finger-tip'];
  14840. const thumbTip = hand.joints['thumb-tip'];
  14841. const distance = indexTip.position.distanceTo(thumbTip.position);
  14842. const distanceToPinch = 0.02;
  14843. const threshold = 0.005;
  14844. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14845. hand.inputState.pinching = false;
  14846. this.dispatchEvent({
  14847. type: 'pinchend',
  14848. handedness: inputSource.handedness,
  14849. target: this
  14850. });
  14851. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14852. hand.inputState.pinching = true;
  14853. this.dispatchEvent({
  14854. type: 'pinchstart',
  14855. handedness: inputSource.handedness,
  14856. target: this
  14857. });
  14858. }
  14859. } else {
  14860. if (grip !== null && inputSource.gripSpace) {
  14861. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14862. if (gripPose !== null) {
  14863. grip.matrix.fromArray(gripPose.transform.matrix);
  14864. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14865. if (gripPose.linearVelocity) {
  14866. grip.hasLinearVelocity = true;
  14867. grip.linearVelocity.copy(gripPose.linearVelocity);
  14868. } else {
  14869. grip.hasLinearVelocity = false;
  14870. }
  14871. if (gripPose.angularVelocity) {
  14872. grip.hasAngularVelocity = true;
  14873. grip.angularVelocity.copy(gripPose.angularVelocity);
  14874. } else {
  14875. grip.hasAngularVelocity = false;
  14876. }
  14877. }
  14878. }
  14879. }
  14880. if (targetRay !== null) {
  14881. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14882. if (inputPose === null && gripPose !== null) {
  14883. inputPose = gripPose;
  14884. }
  14885. if (inputPose !== null) {
  14886. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14887. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14888. if (inputPose.linearVelocity) {
  14889. targetRay.hasLinearVelocity = true;
  14890. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14891. } else {
  14892. targetRay.hasLinearVelocity = false;
  14893. }
  14894. if (inputPose.angularVelocity) {
  14895. targetRay.hasAngularVelocity = true;
  14896. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14897. } else {
  14898. targetRay.hasAngularVelocity = false;
  14899. }
  14900. this.dispatchEvent(_moveEvent);
  14901. }
  14902. }
  14903. }
  14904. if (targetRay !== null) {
  14905. targetRay.visible = inputPose !== null;
  14906. }
  14907. if (grip !== null) {
  14908. grip.visible = gripPose !== null;
  14909. }
  14910. if (hand !== null) {
  14911. hand.visible = handPose !== null;
  14912. }
  14913. return this;
  14914. }
  14915. }
  14916. class DepthTexture extends Texture {
  14917. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14918. format = format !== undefined ? format : DepthFormat;
  14919. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14920. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14921. }
  14922. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  14923. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14924. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14925. this.isDepthTexture = true;
  14926. this.image = {
  14927. width: width,
  14928. height: height
  14929. };
  14930. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14931. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14932. this.flipY = false;
  14933. this.generateMipmaps = false;
  14934. }
  14935. }
  14936. class WebXRManager extends EventDispatcher {
  14937. constructor(renderer, gl) {
  14938. super();
  14939. const scope = this;
  14940. let session = null;
  14941. let framebufferScaleFactor = 1.0;
  14942. let referenceSpace = null;
  14943. let referenceSpaceType = 'local-floor';
  14944. let customReferenceSpace = null;
  14945. let pose = null;
  14946. let glBinding = null;
  14947. let glProjLayer = null;
  14948. let glBaseLayer = null;
  14949. let xrFrame = null;
  14950. const attributes = gl.getContextAttributes();
  14951. let initialRenderTarget = null;
  14952. let newRenderTarget = null;
  14953. const controllers = [];
  14954. const controllerInputSources = []; //
  14955. const cameraL = new PerspectiveCamera();
  14956. cameraL.layers.enable(1);
  14957. cameraL.viewport = new Vector4();
  14958. const cameraR = new PerspectiveCamera();
  14959. cameraR.layers.enable(2);
  14960. cameraR.viewport = new Vector4();
  14961. const cameras = [cameraL, cameraR];
  14962. const cameraVR = new ArrayCamera();
  14963. cameraVR.layers.enable(1);
  14964. cameraVR.layers.enable(2);
  14965. let _currentDepthNear = null;
  14966. let _currentDepthFar = null; //
  14967. this.cameraAutoUpdate = true;
  14968. this.enabled = false;
  14969. this.isPresenting = false;
  14970. this.getController = function (index) {
  14971. let controller = controllers[index];
  14972. if (controller === undefined) {
  14973. controller = new WebXRController();
  14974. controllers[index] = controller;
  14975. }
  14976. return controller.getTargetRaySpace();
  14977. };
  14978. this.getControllerGrip = function (index) {
  14979. let controller = controllers[index];
  14980. if (controller === undefined) {
  14981. controller = new WebXRController();
  14982. controllers[index] = controller;
  14983. }
  14984. return controller.getGripSpace();
  14985. };
  14986. this.getHand = function (index) {
  14987. let controller = controllers[index];
  14988. if (controller === undefined) {
  14989. controller = new WebXRController();
  14990. controllers[index] = controller;
  14991. }
  14992. return controller.getHandSpace();
  14993. }; //
  14994. function onSessionEvent(event) {
  14995. const controllerIndex = controllerInputSources.indexOf(event.inputSource);
  14996. if (controllerIndex === -1) {
  14997. return;
  14998. }
  14999. const controller = controllers[controllerIndex];
  15000. if (controller !== undefined) {
  15001. controller.dispatchEvent({
  15002. type: event.type,
  15003. data: event.inputSource
  15004. });
  15005. }
  15006. }
  15007. function onSessionEnd() {
  15008. session.removeEventListener('select', onSessionEvent);
  15009. session.removeEventListener('selectstart', onSessionEvent);
  15010. session.removeEventListener('selectend', onSessionEvent);
  15011. session.removeEventListener('squeeze', onSessionEvent);
  15012. session.removeEventListener('squeezestart', onSessionEvent);
  15013. session.removeEventListener('squeezeend', onSessionEvent);
  15014. session.removeEventListener('end', onSessionEnd);
  15015. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  15016. for (let i = 0; i < controllers.length; i++) {
  15017. const inputSource = controllerInputSources[i];
  15018. if (inputSource === null) continue;
  15019. controllerInputSources[i] = null;
  15020. controllers[i].disconnect(inputSource);
  15021. }
  15022. _currentDepthNear = null;
  15023. _currentDepthFar = null; // restore framebuffer/rendering state
  15024. renderer.setRenderTarget(initialRenderTarget);
  15025. glBaseLayer = null;
  15026. glProjLayer = null;
  15027. glBinding = null;
  15028. session = null;
  15029. newRenderTarget = null; //
  15030. animation.stop();
  15031. scope.isPresenting = false;
  15032. scope.dispatchEvent({
  15033. type: 'sessionend'
  15034. });
  15035. }
  15036. this.setFramebufferScaleFactor = function (value) {
  15037. framebufferScaleFactor = value;
  15038. if (scope.isPresenting === true) {
  15039. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  15040. }
  15041. };
  15042. this.setReferenceSpaceType = function (value) {
  15043. referenceSpaceType = value;
  15044. if (scope.isPresenting === true) {
  15045. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  15046. }
  15047. };
  15048. this.getReferenceSpace = function () {
  15049. return customReferenceSpace || referenceSpace;
  15050. };
  15051. this.setReferenceSpace = function (space) {
  15052. customReferenceSpace = space;
  15053. };
  15054. this.getBaseLayer = function () {
  15055. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15056. };
  15057. this.getBinding = function () {
  15058. return glBinding;
  15059. };
  15060. this.getFrame = function () {
  15061. return xrFrame;
  15062. };
  15063. this.getSession = function () {
  15064. return session;
  15065. };
  15066. this.setSession = async function (value) {
  15067. session = value;
  15068. if (session !== null) {
  15069. initialRenderTarget = renderer.getRenderTarget();
  15070. session.addEventListener('select', onSessionEvent);
  15071. session.addEventListener('selectstart', onSessionEvent);
  15072. session.addEventListener('selectend', onSessionEvent);
  15073. session.addEventListener('squeeze', onSessionEvent);
  15074. session.addEventListener('squeezestart', onSessionEvent);
  15075. session.addEventListener('squeezeend', onSessionEvent);
  15076. session.addEventListener('end', onSessionEnd);
  15077. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15078. if (attributes.xrCompatible !== true) {
  15079. await gl.makeXRCompatible();
  15080. }
  15081. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15082. const layerInit = {
  15083. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15084. alpha: attributes.alpha,
  15085. depth: attributes.depth,
  15086. stencil: attributes.stencil,
  15087. framebufferScaleFactor: framebufferScaleFactor
  15088. };
  15089. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15090. session.updateRenderState({
  15091. baseLayer: glBaseLayer
  15092. });
  15093. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15094. format: RGBAFormat,
  15095. type: UnsignedByteType,
  15096. encoding: renderer.outputEncoding,
  15097. stencilBuffer: attributes.stencil
  15098. });
  15099. } else {
  15100. let depthFormat = null;
  15101. let depthType = null;
  15102. let glDepthFormat = null;
  15103. if (attributes.depth) {
  15104. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15105. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15106. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15107. }
  15108. const projectionlayerInit = {
  15109. colorFormat: gl.RGBA8,
  15110. depthFormat: glDepthFormat,
  15111. scaleFactor: framebufferScaleFactor
  15112. };
  15113. glBinding = new XRWebGLBinding(session, gl);
  15114. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15115. session.updateRenderState({
  15116. layers: [glProjLayer]
  15117. });
  15118. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15119. format: RGBAFormat,
  15120. type: UnsignedByteType,
  15121. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15122. stencilBuffer: attributes.stencil,
  15123. encoding: renderer.outputEncoding,
  15124. samples: attributes.antialias ? 4 : 0
  15125. });
  15126. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15127. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15128. }
  15129. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15130. // Set foveation to maximum.
  15131. this.setFoveation(1.0);
  15132. customReferenceSpace = null;
  15133. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15134. animation.setContext(session);
  15135. animation.start();
  15136. scope.isPresenting = true;
  15137. scope.dispatchEvent({
  15138. type: 'sessionstart'
  15139. });
  15140. }
  15141. };
  15142. function onInputSourcesChange(event) {
  15143. // Notify disconnected
  15144. for (let i = 0; i < event.removed.length; i++) {
  15145. const inputSource = event.removed[i];
  15146. const index = controllerInputSources.indexOf(inputSource);
  15147. if (index >= 0) {
  15148. controllerInputSources[index] = null;
  15149. controllers[index].dispatchEvent({
  15150. type: 'disconnected',
  15151. data: inputSource
  15152. });
  15153. }
  15154. } // Notify connected
  15155. for (let i = 0; i < event.added.length; i++) {
  15156. const inputSource = event.added[i];
  15157. let controllerIndex = controllerInputSources.indexOf(inputSource);
  15158. if (controllerIndex === -1) {
  15159. // Assign input source a controller that currently has no input source
  15160. for (let i = 0; i < controllers.length; i++) {
  15161. if (i >= controllerInputSources.length) {
  15162. controllerInputSources.push(inputSource);
  15163. controllerIndex = i;
  15164. break;
  15165. } else if (controllerInputSources[i] === null) {
  15166. controllerInputSources[i] = inputSource;
  15167. controllerIndex = i;
  15168. break;
  15169. }
  15170. } // If all controllers do currently receive input we ignore new ones
  15171. if (controllerIndex === -1) break;
  15172. }
  15173. const controller = controllers[controllerIndex];
  15174. if (controller) {
  15175. controller.dispatchEvent({
  15176. type: 'connected',
  15177. data: inputSource
  15178. });
  15179. }
  15180. }
  15181. } //
  15182. const cameraLPos = new Vector3();
  15183. const cameraRPos = new Vector3();
  15184. /**
  15185. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15186. * the cameras' projection and world matrices have already been set.
  15187. * And that near and far planes are identical for both cameras.
  15188. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15189. */
  15190. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15191. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15192. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15193. const ipd = cameraLPos.distanceTo(cameraRPos);
  15194. const projL = cameraL.projectionMatrix.elements;
  15195. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15196. // most likely identical top and bottom frustum extents.
  15197. // Use the left camera for these values.
  15198. const near = projL[14] / (projL[10] - 1);
  15199. const far = projL[14] / (projL[10] + 1);
  15200. const topFov = (projL[9] + 1) / projL[5];
  15201. const bottomFov = (projL[9] - 1) / projL[5];
  15202. const leftFov = (projL[8] - 1) / projL[0];
  15203. const rightFov = (projR[8] + 1) / projR[0];
  15204. const left = near * leftFov;
  15205. const right = near * rightFov; // Calculate the new camera's position offset from the
  15206. // left camera. xOffset should be roughly half `ipd`.
  15207. const zOffset = ipd / (-leftFov + rightFov);
  15208. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15209. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15210. camera.translateX(xOffset);
  15211. camera.translateZ(zOffset);
  15212. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15213. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  15214. // the values so that the near plane's position does not change in world space,
  15215. // although must now be relative to the new union camera.
  15216. const near2 = near + zOffset;
  15217. const far2 = far + zOffset;
  15218. const left2 = left - xOffset;
  15219. const right2 = right + (ipd - xOffset);
  15220. const top2 = topFov * far / far2 * near2;
  15221. const bottom2 = bottomFov * far / far2 * near2;
  15222. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15223. }
  15224. function updateCamera(camera, parent) {
  15225. if (parent === null) {
  15226. camera.matrixWorld.copy(camera.matrix);
  15227. } else {
  15228. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15229. }
  15230. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15231. }
  15232. this.updateCamera = function (camera) {
  15233. if (session === null) return;
  15234. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15235. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15236. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15237. // Note that the new renderState won't apply until the next frame. See #18320
  15238. session.updateRenderState({
  15239. depthNear: cameraVR.near,
  15240. depthFar: cameraVR.far
  15241. });
  15242. _currentDepthNear = cameraVR.near;
  15243. _currentDepthFar = cameraVR.far;
  15244. }
  15245. const parent = camera.parent;
  15246. const cameras = cameraVR.cameras;
  15247. updateCamera(cameraVR, parent);
  15248. for (let i = 0; i < cameras.length; i++) {
  15249. updateCamera(cameras[i], parent);
  15250. }
  15251. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  15252. camera.matrix.copy(cameraVR.matrix);
  15253. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  15254. const children = camera.children;
  15255. for (let i = 0, l = children.length; i < l; i++) {
  15256. children[i].updateMatrixWorld(true);
  15257. } // update projection matrix for proper view frustum culling
  15258. if (cameras.length === 2) {
  15259. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15260. } else {
  15261. // assume single camera setup (AR)
  15262. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  15263. }
  15264. };
  15265. this.getCamera = function () {
  15266. return cameraVR;
  15267. };
  15268. this.getFoveation = function () {
  15269. if (glProjLayer !== null) {
  15270. return glProjLayer.fixedFoveation;
  15271. }
  15272. if (glBaseLayer !== null) {
  15273. return glBaseLayer.fixedFoveation;
  15274. }
  15275. return undefined;
  15276. };
  15277. this.setFoveation = function (foveation) {
  15278. // 0 = no foveation = full resolution
  15279. // 1 = maximum foveation = the edges render at lower resolution
  15280. if (glProjLayer !== null) {
  15281. glProjLayer.fixedFoveation = foveation;
  15282. }
  15283. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15284. glBaseLayer.fixedFoveation = foveation;
  15285. }
  15286. }; // Animation Loop
  15287. let onAnimationFrameCallback = null;
  15288. function onAnimationFrame(time, frame) {
  15289. pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
  15290. xrFrame = frame;
  15291. if (pose !== null) {
  15292. const views = pose.views;
  15293. if (glBaseLayer !== null) {
  15294. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15295. renderer.setRenderTarget(newRenderTarget);
  15296. }
  15297. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  15298. if (views.length !== cameraVR.cameras.length) {
  15299. cameraVR.cameras.length = 0;
  15300. cameraVRNeedsUpdate = true;
  15301. }
  15302. for (let i = 0; i < views.length; i++) {
  15303. const view = views[i];
  15304. let viewport = null;
  15305. if (glBaseLayer !== null) {
  15306. viewport = glBaseLayer.getViewport(view);
  15307. } else {
  15308. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15309. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  15310. if (i === 0) {
  15311. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15312. renderer.setRenderTarget(newRenderTarget);
  15313. }
  15314. }
  15315. let camera = cameras[i];
  15316. if (camera === undefined) {
  15317. camera = new PerspectiveCamera();
  15318. camera.layers.enable(i);
  15319. camera.viewport = new Vector4();
  15320. cameras[i] = camera;
  15321. }
  15322. camera.matrix.fromArray(view.transform.matrix);
  15323. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15324. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15325. if (i === 0) {
  15326. cameraVR.matrix.copy(camera.matrix);
  15327. }
  15328. if (cameraVRNeedsUpdate === true) {
  15329. cameraVR.cameras.push(camera);
  15330. }
  15331. }
  15332. } //
  15333. for (let i = 0; i < controllers.length; i++) {
  15334. const inputSource = controllerInputSources[i];
  15335. const controller = controllers[i];
  15336. if (inputSource !== null && controller !== undefined) {
  15337. controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
  15338. }
  15339. }
  15340. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15341. xrFrame = null;
  15342. }
  15343. const animation = new WebGLAnimation();
  15344. animation.setAnimationLoop(onAnimationFrame);
  15345. this.setAnimationLoop = function (callback) {
  15346. onAnimationFrameCallback = callback;
  15347. };
  15348. this.dispose = function () {};
  15349. }
  15350. }
  15351. function WebGLMaterials(renderer, properties) {
  15352. function refreshFogUniforms(uniforms, fog) {
  15353. uniforms.fogColor.value.copy(fog.color);
  15354. if (fog.isFog) {
  15355. uniforms.fogNear.value = fog.near;
  15356. uniforms.fogFar.value = fog.far;
  15357. } else if (fog.isFogExp2) {
  15358. uniforms.fogDensity.value = fog.density;
  15359. }
  15360. }
  15361. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15362. if (material.isMeshBasicMaterial) {
  15363. refreshUniformsCommon(uniforms, material);
  15364. } else if (material.isMeshLambertMaterial) {
  15365. refreshUniformsCommon(uniforms, material);
  15366. } else if (material.isMeshToonMaterial) {
  15367. refreshUniformsCommon(uniforms, material);
  15368. refreshUniformsToon(uniforms, material);
  15369. } else if (material.isMeshPhongMaterial) {
  15370. refreshUniformsCommon(uniforms, material);
  15371. refreshUniformsPhong(uniforms, material);
  15372. } else if (material.isMeshStandardMaterial) {
  15373. refreshUniformsCommon(uniforms, material);
  15374. refreshUniformsStandard(uniforms, material);
  15375. if (material.isMeshPhysicalMaterial) {
  15376. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15377. }
  15378. } else if (material.isMeshMatcapMaterial) {
  15379. refreshUniformsCommon(uniforms, material);
  15380. refreshUniformsMatcap(uniforms, material);
  15381. } else if (material.isMeshDepthMaterial) {
  15382. refreshUniformsCommon(uniforms, material);
  15383. } else if (material.isMeshDistanceMaterial) {
  15384. refreshUniformsCommon(uniforms, material);
  15385. refreshUniformsDistance(uniforms, material);
  15386. } else if (material.isMeshNormalMaterial) {
  15387. refreshUniformsCommon(uniforms, material);
  15388. } else if (material.isLineBasicMaterial) {
  15389. refreshUniformsLine(uniforms, material);
  15390. if (material.isLineDashedMaterial) {
  15391. refreshUniformsDash(uniforms, material);
  15392. }
  15393. } else if (material.isPointsMaterial) {
  15394. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15395. } else if (material.isSpriteMaterial) {
  15396. refreshUniformsSprites(uniforms, material);
  15397. } else if (material.isShadowMaterial) {
  15398. uniforms.color.value.copy(material.color);
  15399. uniforms.opacity.value = material.opacity;
  15400. } else if (material.isShaderMaterial) {
  15401. material.uniformsNeedUpdate = false; // #15581
  15402. }
  15403. }
  15404. function refreshUniformsCommon(uniforms, material) {
  15405. uniforms.opacity.value = material.opacity;
  15406. if (material.color) {
  15407. uniforms.diffuse.value.copy(material.color);
  15408. }
  15409. if (material.emissive) {
  15410. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15411. }
  15412. if (material.map) {
  15413. uniforms.map.value = material.map;
  15414. }
  15415. if (material.alphaMap) {
  15416. uniforms.alphaMap.value = material.alphaMap;
  15417. }
  15418. if (material.bumpMap) {
  15419. uniforms.bumpMap.value = material.bumpMap;
  15420. uniforms.bumpScale.value = material.bumpScale;
  15421. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15422. }
  15423. if (material.displacementMap) {
  15424. uniforms.displacementMap.value = material.displacementMap;
  15425. uniforms.displacementScale.value = material.displacementScale;
  15426. uniforms.displacementBias.value = material.displacementBias;
  15427. }
  15428. if (material.emissiveMap) {
  15429. uniforms.emissiveMap.value = material.emissiveMap;
  15430. }
  15431. if (material.normalMap) {
  15432. uniforms.normalMap.value = material.normalMap;
  15433. uniforms.normalScale.value.copy(material.normalScale);
  15434. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15435. }
  15436. if (material.specularMap) {
  15437. uniforms.specularMap.value = material.specularMap;
  15438. }
  15439. if (material.alphaTest > 0) {
  15440. uniforms.alphaTest.value = material.alphaTest;
  15441. }
  15442. const envMap = properties.get(material).envMap;
  15443. if (envMap) {
  15444. uniforms.envMap.value = envMap;
  15445. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15446. uniforms.reflectivity.value = material.reflectivity;
  15447. uniforms.ior.value = material.ior;
  15448. uniforms.refractionRatio.value = material.refractionRatio;
  15449. }
  15450. if (material.lightMap) {
  15451. uniforms.lightMap.value = material.lightMap; // artist-friendly light intensity scaling factor
  15452. const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1;
  15453. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15454. }
  15455. if (material.aoMap) {
  15456. uniforms.aoMap.value = material.aoMap;
  15457. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15458. } // uv repeat and offset setting priorities
  15459. // 1. color map
  15460. // 2. specular map
  15461. // 3. displacementMap map
  15462. // 4. normal map
  15463. // 5. bump map
  15464. // 6. roughnessMap map
  15465. // 7. metalnessMap map
  15466. // 8. alphaMap map
  15467. // 9. emissiveMap map
  15468. // 10. clearcoat map
  15469. // 11. clearcoat normal map
  15470. // 12. clearcoat roughnessMap map
  15471. // 13. iridescence map
  15472. // 14. iridescence thickness map
  15473. // 15. specular intensity map
  15474. // 16. specular tint map
  15475. // 17. transmission map
  15476. // 18. thickness map
  15477. let uvScaleMap;
  15478. if (material.map) {
  15479. uvScaleMap = material.map;
  15480. } else if (material.specularMap) {
  15481. uvScaleMap = material.specularMap;
  15482. } else if (material.displacementMap) {
  15483. uvScaleMap = material.displacementMap;
  15484. } else if (material.normalMap) {
  15485. uvScaleMap = material.normalMap;
  15486. } else if (material.bumpMap) {
  15487. uvScaleMap = material.bumpMap;
  15488. } else if (material.roughnessMap) {
  15489. uvScaleMap = material.roughnessMap;
  15490. } else if (material.metalnessMap) {
  15491. uvScaleMap = material.metalnessMap;
  15492. } else if (material.alphaMap) {
  15493. uvScaleMap = material.alphaMap;
  15494. } else if (material.emissiveMap) {
  15495. uvScaleMap = material.emissiveMap;
  15496. } else if (material.clearcoatMap) {
  15497. uvScaleMap = material.clearcoatMap;
  15498. } else if (material.clearcoatNormalMap) {
  15499. uvScaleMap = material.clearcoatNormalMap;
  15500. } else if (material.clearcoatRoughnessMap) {
  15501. uvScaleMap = material.clearcoatRoughnessMap;
  15502. } else if (material.iridescenceMap) {
  15503. uvScaleMap = material.iridescenceMap;
  15504. } else if (material.iridescenceThicknessMap) {
  15505. uvScaleMap = material.iridescenceThicknessMap;
  15506. } else if (material.specularIntensityMap) {
  15507. uvScaleMap = material.specularIntensityMap;
  15508. } else if (material.specularColorMap) {
  15509. uvScaleMap = material.specularColorMap;
  15510. } else if (material.transmissionMap) {
  15511. uvScaleMap = material.transmissionMap;
  15512. } else if (material.thicknessMap) {
  15513. uvScaleMap = material.thicknessMap;
  15514. } else if (material.sheenColorMap) {
  15515. uvScaleMap = material.sheenColorMap;
  15516. } else if (material.sheenRoughnessMap) {
  15517. uvScaleMap = material.sheenRoughnessMap;
  15518. }
  15519. if (uvScaleMap !== undefined) {
  15520. // backwards compatibility
  15521. if (uvScaleMap.isWebGLRenderTarget) {
  15522. uvScaleMap = uvScaleMap.texture;
  15523. }
  15524. if (uvScaleMap.matrixAutoUpdate === true) {
  15525. uvScaleMap.updateMatrix();
  15526. }
  15527. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15528. } // uv repeat and offset setting priorities for uv2
  15529. // 1. ao map
  15530. // 2. light map
  15531. let uv2ScaleMap;
  15532. if (material.aoMap) {
  15533. uv2ScaleMap = material.aoMap;
  15534. } else if (material.lightMap) {
  15535. uv2ScaleMap = material.lightMap;
  15536. }
  15537. if (uv2ScaleMap !== undefined) {
  15538. // backwards compatibility
  15539. if (uv2ScaleMap.isWebGLRenderTarget) {
  15540. uv2ScaleMap = uv2ScaleMap.texture;
  15541. }
  15542. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15543. uv2ScaleMap.updateMatrix();
  15544. }
  15545. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15546. }
  15547. }
  15548. function refreshUniformsLine(uniforms, material) {
  15549. uniforms.diffuse.value.copy(material.color);
  15550. uniforms.opacity.value = material.opacity;
  15551. }
  15552. function refreshUniformsDash(uniforms, material) {
  15553. uniforms.dashSize.value = material.dashSize;
  15554. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15555. uniforms.scale.value = material.scale;
  15556. }
  15557. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15558. uniforms.diffuse.value.copy(material.color);
  15559. uniforms.opacity.value = material.opacity;
  15560. uniforms.size.value = material.size * pixelRatio;
  15561. uniforms.scale.value = height * 0.5;
  15562. if (material.map) {
  15563. uniforms.map.value = material.map;
  15564. }
  15565. if (material.alphaMap) {
  15566. uniforms.alphaMap.value = material.alphaMap;
  15567. }
  15568. if (material.alphaTest > 0) {
  15569. uniforms.alphaTest.value = material.alphaTest;
  15570. } // uv repeat and offset setting priorities
  15571. // 1. color map
  15572. // 2. alpha map
  15573. let uvScaleMap;
  15574. if (material.map) {
  15575. uvScaleMap = material.map;
  15576. } else if (material.alphaMap) {
  15577. uvScaleMap = material.alphaMap;
  15578. }
  15579. if (uvScaleMap !== undefined) {
  15580. if (uvScaleMap.matrixAutoUpdate === true) {
  15581. uvScaleMap.updateMatrix();
  15582. }
  15583. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15584. }
  15585. }
  15586. function refreshUniformsSprites(uniforms, material) {
  15587. uniforms.diffuse.value.copy(material.color);
  15588. uniforms.opacity.value = material.opacity;
  15589. uniforms.rotation.value = material.rotation;
  15590. if (material.map) {
  15591. uniforms.map.value = material.map;
  15592. }
  15593. if (material.alphaMap) {
  15594. uniforms.alphaMap.value = material.alphaMap;
  15595. }
  15596. if (material.alphaTest > 0) {
  15597. uniforms.alphaTest.value = material.alphaTest;
  15598. } // uv repeat and offset setting priorities
  15599. // 1. color map
  15600. // 2. alpha map
  15601. let uvScaleMap;
  15602. if (material.map) {
  15603. uvScaleMap = material.map;
  15604. } else if (material.alphaMap) {
  15605. uvScaleMap = material.alphaMap;
  15606. }
  15607. if (uvScaleMap !== undefined) {
  15608. if (uvScaleMap.matrixAutoUpdate === true) {
  15609. uvScaleMap.updateMatrix();
  15610. }
  15611. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15612. }
  15613. }
  15614. function refreshUniformsPhong(uniforms, material) {
  15615. uniforms.specular.value.copy(material.specular);
  15616. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15617. }
  15618. function refreshUniformsToon(uniforms, material) {
  15619. if (material.gradientMap) {
  15620. uniforms.gradientMap.value = material.gradientMap;
  15621. }
  15622. }
  15623. function refreshUniformsStandard(uniforms, material) {
  15624. uniforms.roughness.value = material.roughness;
  15625. uniforms.metalness.value = material.metalness;
  15626. if (material.roughnessMap) {
  15627. uniforms.roughnessMap.value = material.roughnessMap;
  15628. }
  15629. if (material.metalnessMap) {
  15630. uniforms.metalnessMap.value = material.metalnessMap;
  15631. }
  15632. const envMap = properties.get(material).envMap;
  15633. if (envMap) {
  15634. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15635. uniforms.envMapIntensity.value = material.envMapIntensity;
  15636. }
  15637. }
  15638. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15639. uniforms.ior.value = material.ior; // also part of uniforms common
  15640. if (material.sheen > 0) {
  15641. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15642. uniforms.sheenRoughness.value = material.sheenRoughness;
  15643. if (material.sheenColorMap) {
  15644. uniforms.sheenColorMap.value = material.sheenColorMap;
  15645. }
  15646. if (material.sheenRoughnessMap) {
  15647. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15648. }
  15649. }
  15650. if (material.clearcoat > 0) {
  15651. uniforms.clearcoat.value = material.clearcoat;
  15652. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15653. if (material.clearcoatMap) {
  15654. uniforms.clearcoatMap.value = material.clearcoatMap;
  15655. }
  15656. if (material.clearcoatRoughnessMap) {
  15657. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15658. }
  15659. if (material.clearcoatNormalMap) {
  15660. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15661. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15662. if (material.side === BackSide) {
  15663. uniforms.clearcoatNormalScale.value.negate();
  15664. }
  15665. }
  15666. }
  15667. if (material.iridescence > 0) {
  15668. uniforms.iridescence.value = material.iridescence;
  15669. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15670. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0];
  15671. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1];
  15672. if (material.iridescenceMap) {
  15673. uniforms.iridescenceMap.value = material.iridescenceMap;
  15674. }
  15675. if (material.iridescenceThicknessMap) {
  15676. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15677. }
  15678. }
  15679. if (material.transmission > 0) {
  15680. uniforms.transmission.value = material.transmission;
  15681. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15682. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15683. if (material.transmissionMap) {
  15684. uniforms.transmissionMap.value = material.transmissionMap;
  15685. }
  15686. uniforms.thickness.value = material.thickness;
  15687. if (material.thicknessMap) {
  15688. uniforms.thicknessMap.value = material.thicknessMap;
  15689. }
  15690. uniforms.attenuationDistance.value = material.attenuationDistance;
  15691. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15692. }
  15693. uniforms.specularIntensity.value = material.specularIntensity;
  15694. uniforms.specularColor.value.copy(material.specularColor);
  15695. if (material.specularIntensityMap) {
  15696. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15697. }
  15698. if (material.specularColorMap) {
  15699. uniforms.specularColorMap.value = material.specularColorMap;
  15700. }
  15701. }
  15702. function refreshUniformsMatcap(uniforms, material) {
  15703. if (material.matcap) {
  15704. uniforms.matcap.value = material.matcap;
  15705. }
  15706. }
  15707. function refreshUniformsDistance(uniforms, material) {
  15708. uniforms.referencePosition.value.copy(material.referencePosition);
  15709. uniforms.nearDistance.value = material.nearDistance;
  15710. uniforms.farDistance.value = material.farDistance;
  15711. }
  15712. return {
  15713. refreshFogUniforms: refreshFogUniforms,
  15714. refreshMaterialUniforms: refreshMaterialUniforms
  15715. };
  15716. }
  15717. function WebGLUniformsGroups(gl, info, capabilities, state) {
  15718. let buffers = {};
  15719. let updateList = {};
  15720. let allocatedBindingPoints = [];
  15721. const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS) : 0; // binding points are global whereas block indices are per shader program
  15722. function bind(uniformsGroup, program) {
  15723. const webglProgram = program.program;
  15724. state.uniformBlockBinding(uniformsGroup, webglProgram);
  15725. }
  15726. function update(uniformsGroup, program) {
  15727. let buffer = buffers[uniformsGroup.id];
  15728. if (buffer === undefined) {
  15729. prepareUniformsGroup(uniformsGroup);
  15730. buffer = createBuffer(uniformsGroup);
  15731. buffers[uniformsGroup.id] = buffer;
  15732. uniformsGroup.addEventListener('dispose', onUniformsGroupsDispose);
  15733. } // ensure to update the binding points/block indices mapping for this program
  15734. const webglProgram = program.program;
  15735. state.updateUBOMapping(uniformsGroup, webglProgram); // update UBO once per frame
  15736. const frame = info.render.frame;
  15737. if (updateList[uniformsGroup.id] !== frame) {
  15738. updateBufferData(uniformsGroup);
  15739. updateList[uniformsGroup.id] = frame;
  15740. }
  15741. }
  15742. function createBuffer(uniformsGroup) {
  15743. // the setup of an UBO is independent of a particular shader program but global
  15744. const bindingPointIndex = allocateBindingPointIndex();
  15745. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15746. const buffer = gl.createBuffer();
  15747. const size = uniformsGroup.__size;
  15748. const usage = uniformsGroup.usage;
  15749. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  15750. gl.bufferData(gl.UNIFORM_BUFFER, size, usage);
  15751. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  15752. gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer);
  15753. return buffer;
  15754. }
  15755. function allocateBindingPointIndex() {
  15756. for (let i = 0; i < maxBindingPoints; i++) {
  15757. if (allocatedBindingPoints.indexOf(i) === -1) {
  15758. allocatedBindingPoints.push(i);
  15759. return i;
  15760. }
  15761. }
  15762. console.error('THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.');
  15763. return 0;
  15764. }
  15765. function updateBufferData(uniformsGroup) {
  15766. const buffer = buffers[uniformsGroup.id];
  15767. const uniforms = uniformsGroup.uniforms;
  15768. const cache = uniformsGroup.__cache;
  15769. gl.bindBuffer(gl.UNIFORM_BUFFER, buffer);
  15770. for (let i = 0, il = uniforms.length; i < il; i++) {
  15771. const uniform = uniforms[i]; // partly update the buffer if necessary
  15772. if (hasUniformChanged(uniform, i, cache) === true) {
  15773. const value = uniform.value;
  15774. const offset = uniform.__offset;
  15775. if (typeof value === 'number') {
  15776. uniform.__data[0] = value;
  15777. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  15778. } else {
  15779. if (uniform.value.isMatrix3) {
  15780. // manually converting 3x3 to 3x4
  15781. uniform.__data[0] = uniform.value.elements[0];
  15782. uniform.__data[1] = uniform.value.elements[1];
  15783. uniform.__data[2] = uniform.value.elements[2];
  15784. uniform.__data[3] = uniform.value.elements[0];
  15785. uniform.__data[4] = uniform.value.elements[3];
  15786. uniform.__data[5] = uniform.value.elements[4];
  15787. uniform.__data[6] = uniform.value.elements[5];
  15788. uniform.__data[7] = uniform.value.elements[0];
  15789. uniform.__data[8] = uniform.value.elements[6];
  15790. uniform.__data[9] = uniform.value.elements[7];
  15791. uniform.__data[10] = uniform.value.elements[8];
  15792. uniform.__data[11] = uniform.value.elements[0];
  15793. } else {
  15794. value.toArray(uniform.__data);
  15795. }
  15796. gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data);
  15797. }
  15798. }
  15799. }
  15800. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  15801. }
  15802. function hasUniformChanged(uniform, index, cache) {
  15803. const value = uniform.value;
  15804. if (cache[index] === undefined) {
  15805. // cache entry does not exist so far
  15806. if (typeof value === 'number') {
  15807. cache[index] = value;
  15808. } else {
  15809. cache[index] = value.clone();
  15810. }
  15811. return true;
  15812. } else {
  15813. // compare current value with cached entry
  15814. if (typeof value === 'number') {
  15815. if (cache[index] !== value) {
  15816. cache[index] = value;
  15817. return true;
  15818. }
  15819. } else {
  15820. const cachedObject = cache[index];
  15821. if (cachedObject.equals(value) === false) {
  15822. cachedObject.copy(value);
  15823. return true;
  15824. }
  15825. }
  15826. }
  15827. return false;
  15828. }
  15829. function prepareUniformsGroup(uniformsGroup) {
  15830. // determine total buffer size according to the STD140 layout
  15831. // Hint: STD140 is the only supported layout in WebGL 2
  15832. const uniforms = uniformsGroup.uniforms;
  15833. let offset = 0; // global buffer offset in bytes
  15834. const chunkSize = 16; // size of a chunk in bytes
  15835. let chunkOffset = 0; // offset within a single chunk in bytes
  15836. for (let i = 0, l = uniforms.length; i < l; i++) {
  15837. const uniform = uniforms[i];
  15838. const info = getUniformSize(uniform); // the following two properties will be used for partial buffer updates
  15839. uniform.__data = new Float32Array(info.storage / Float32Array.BYTES_PER_ELEMENT);
  15840. uniform.__offset = offset; //
  15841. if (i > 0) {
  15842. chunkOffset = offset % chunkSize;
  15843. const remainingSizeInChunk = chunkSize - chunkOffset; // check for chunk overflow
  15844. if (chunkOffset !== 0 && remainingSizeInChunk - info.boundary < 0) {
  15845. // add padding and adjust offset
  15846. offset += chunkSize - chunkOffset;
  15847. uniform.__offset = offset;
  15848. }
  15849. }
  15850. offset += info.storage;
  15851. } // ensure correct final padding
  15852. chunkOffset = offset % chunkSize;
  15853. if (chunkOffset > 0) offset += chunkSize - chunkOffset; //
  15854. uniformsGroup.__size = offset;
  15855. uniformsGroup.__cache = {};
  15856. return this;
  15857. }
  15858. function getUniformSize(uniform) {
  15859. const value = uniform.value;
  15860. const info = {
  15861. boundary: 0,
  15862. // bytes
  15863. storage: 0 // bytes
  15864. }; // determine sizes according to STD140
  15865. if (typeof value === 'number') {
  15866. // float/int
  15867. info.boundary = 4;
  15868. info.storage = 4;
  15869. } else if (value.isVector2) {
  15870. // vec2
  15871. info.boundary = 8;
  15872. info.storage = 8;
  15873. } else if (value.isVector3 || value.isColor) {
  15874. // vec3
  15875. info.boundary = 16;
  15876. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  15877. } else if (value.isVector4) {
  15878. // vec4
  15879. info.boundary = 16;
  15880. info.storage = 16;
  15881. } else if (value.isMatrix3) {
  15882. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  15883. info.boundary = 48;
  15884. info.storage = 48;
  15885. } else if (value.isMatrix4) {
  15886. // mat4
  15887. info.boundary = 64;
  15888. info.storage = 64;
  15889. } else if (value.isTexture) {
  15890. console.warn('THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.');
  15891. } else {
  15892. console.warn('THREE.WebGLRenderer: Unsupported uniform value type.', value);
  15893. }
  15894. return info;
  15895. }
  15896. function onUniformsGroupsDispose(event) {
  15897. const uniformsGroup = event.target;
  15898. uniformsGroup.removeEventListener('dispose', onUniformsGroupsDispose);
  15899. const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex);
  15900. allocatedBindingPoints.splice(index, 1);
  15901. gl.deleteBuffer(buffers[uniformsGroup.id]);
  15902. delete buffers[uniformsGroup.id];
  15903. delete updateList[uniformsGroup.id];
  15904. }
  15905. function dispose() {
  15906. for (const id in buffers) {
  15907. gl.deleteBuffer(buffers[id]);
  15908. }
  15909. allocatedBindingPoints = [];
  15910. buffers = {};
  15911. updateList = {};
  15912. }
  15913. return {
  15914. bind: bind,
  15915. update: update,
  15916. dispose: dispose
  15917. };
  15918. }
  15919. function createCanvasElement() {
  15920. const canvas = createElementNS('canvas');
  15921. canvas.style.display = 'block';
  15922. return canvas;
  15923. }
  15924. function WebGLRenderer(parameters = {}) {
  15925. this.isWebGLRenderer = true;
  15926. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15927. _context = parameters.context !== undefined ? parameters.context : null,
  15928. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15929. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15930. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15931. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15932. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15933. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15934. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15935. let _alpha;
  15936. if (_context !== null) {
  15937. _alpha = _context.getContextAttributes().alpha;
  15938. } else {
  15939. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15940. }
  15941. let currentRenderList = null;
  15942. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15943. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15944. const renderListStack = [];
  15945. const renderStateStack = []; // public properties
  15946. this.domElement = _canvas; // Debug configuration container
  15947. this.debug = {
  15948. /**
  15949. * Enables error checking and reporting when shader programs are being compiled
  15950. * @type {boolean}
  15951. */
  15952. checkShaderErrors: true
  15953. }; // clearing
  15954. this.autoClear = true;
  15955. this.autoClearColor = true;
  15956. this.autoClearDepth = true;
  15957. this.autoClearStencil = true; // scene graph
  15958. this.sortObjects = true; // user-defined clipping
  15959. this.clippingPlanes = [];
  15960. this.localClippingEnabled = false; // physically based shading
  15961. this.outputEncoding = LinearEncoding; // physical lights
  15962. this.physicallyCorrectLights = false; // tone mapping
  15963. this.toneMapping = NoToneMapping;
  15964. this.toneMappingExposure = 1.0; //
  15965. Object.defineProperties(this, {
  15966. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  15967. gammaFactor: {
  15968. get: function () {
  15969. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15970. return 2;
  15971. },
  15972. set: function () {
  15973. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15974. }
  15975. }
  15976. }); // internal properties
  15977. const _this = this;
  15978. let _isContextLost = false; // internal state cache
  15979. let _currentActiveCubeFace = 0;
  15980. let _currentActiveMipmapLevel = 0;
  15981. let _currentRenderTarget = null;
  15982. let _currentMaterialId = -1;
  15983. let _currentCamera = null;
  15984. const _currentViewport = new Vector4();
  15985. const _currentScissor = new Vector4();
  15986. let _currentScissorTest = null; //
  15987. let _width = _canvas.width;
  15988. let _height = _canvas.height;
  15989. let _pixelRatio = 1;
  15990. let _opaqueSort = null;
  15991. let _transparentSort = null;
  15992. const _viewport = new Vector4(0, 0, _width, _height);
  15993. const _scissor = new Vector4(0, 0, _width, _height);
  15994. let _scissorTest = false; // frustum
  15995. const _frustum = new Frustum(); // clipping
  15996. let _clippingEnabled = false;
  15997. let _localClippingEnabled = false; // transmission
  15998. let _transmissionRenderTarget = null; // camera matrices cache
  15999. const _projScreenMatrix = new Matrix4();
  16000. const _vector2 = new Vector2();
  16001. const _vector3 = new Vector3();
  16002. const _emptyScene = {
  16003. background: null,
  16004. fog: null,
  16005. environment: null,
  16006. overrideMaterial: null,
  16007. isScene: true
  16008. };
  16009. function getTargetPixelRatio() {
  16010. return _currentRenderTarget === null ? _pixelRatio : 1;
  16011. } // initialize
  16012. let _gl = _context;
  16013. function getContext(contextNames, contextAttributes) {
  16014. for (let i = 0; i < contextNames.length; i++) {
  16015. const contextName = contextNames[i];
  16016. const context = _canvas.getContext(contextName, contextAttributes);
  16017. if (context !== null) return context;
  16018. }
  16019. return null;
  16020. }
  16021. try {
  16022. const contextAttributes = {
  16023. alpha: true,
  16024. depth: _depth,
  16025. stencil: _stencil,
  16026. antialias: _antialias,
  16027. premultipliedAlpha: _premultipliedAlpha,
  16028. preserveDrawingBuffer: _preserveDrawingBuffer,
  16029. powerPreference: _powerPreference,
  16030. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16031. }; // OffscreenCanvas does not have setAttribute, see #22811
  16032. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  16033. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  16034. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  16035. _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  16036. if (_gl === null) {
  16037. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  16038. if (_this.isWebGL1Renderer === true) {
  16039. contextNames.shift();
  16040. }
  16041. _gl = getContext(contextNames, contextAttributes);
  16042. if (_gl === null) {
  16043. if (getContext(contextNames)) {
  16044. throw new Error('Error creating WebGL context with your selected attributes.');
  16045. } else {
  16046. throw new Error('Error creating WebGL context.');
  16047. }
  16048. }
  16049. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16050. if (_gl.getShaderPrecisionFormat === undefined) {
  16051. _gl.getShaderPrecisionFormat = function () {
  16052. return {
  16053. 'rangeMin': 1,
  16054. 'rangeMax': 1,
  16055. 'precision': 1
  16056. };
  16057. };
  16058. }
  16059. } catch (error) {
  16060. console.error('THREE.WebGLRenderer: ' + error.message);
  16061. throw error;
  16062. }
  16063. let extensions, capabilities, state, info;
  16064. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16065. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16066. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16067. let utils, bindingStates, uniformsGroups;
  16068. function initGLContext() {
  16069. extensions = new WebGLExtensions(_gl);
  16070. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  16071. extensions.init(capabilities);
  16072. utils = new WebGLUtils(_gl, extensions, capabilities);
  16073. state = new WebGLState(_gl, extensions, capabilities);
  16074. info = new WebGLInfo(_gl);
  16075. properties = new WebGLProperties();
  16076. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  16077. cubemaps = new WebGLCubeMaps(_this);
  16078. cubeuvmaps = new WebGLCubeUVMaps(_this);
  16079. attributes = new WebGLAttributes(_gl, capabilities);
  16080. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  16081. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  16082. objects = new WebGLObjects(_gl, geometries, attributes, info);
  16083. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  16084. clipping = new WebGLClipping(properties);
  16085. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  16086. materials = new WebGLMaterials(_this, properties);
  16087. renderLists = new WebGLRenderLists();
  16088. renderStates = new WebGLRenderStates(extensions, capabilities);
  16089. background = new WebGLBackground(_this, cubemaps, state, objects, _alpha, _premultipliedAlpha);
  16090. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  16091. uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state);
  16092. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  16093. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  16094. info.programs = programCache.programs;
  16095. _this.capabilities = capabilities;
  16096. _this.extensions = extensions;
  16097. _this.properties = properties;
  16098. _this.renderLists = renderLists;
  16099. _this.shadowMap = shadowMap;
  16100. _this.state = state;
  16101. _this.info = info;
  16102. }
  16103. initGLContext(); // xr
  16104. const xr = new WebXRManager(_this, _gl);
  16105. this.xr = xr; // API
  16106. this.getContext = function () {
  16107. return _gl;
  16108. };
  16109. this.getContextAttributes = function () {
  16110. return _gl.getContextAttributes();
  16111. };
  16112. this.forceContextLoss = function () {
  16113. const extension = extensions.get('WEBGL_lose_context');
  16114. if (extension) extension.loseContext();
  16115. };
  16116. this.forceContextRestore = function () {
  16117. const extension = extensions.get('WEBGL_lose_context');
  16118. if (extension) extension.restoreContext();
  16119. };
  16120. this.getPixelRatio = function () {
  16121. return _pixelRatio;
  16122. };
  16123. this.setPixelRatio = function (value) {
  16124. if (value === undefined) return;
  16125. _pixelRatio = value;
  16126. this.setSize(_width, _height, false);
  16127. };
  16128. this.getSize = function (target) {
  16129. return target.set(_width, _height);
  16130. };
  16131. this.setSize = function (width, height, updateStyle) {
  16132. if (xr.isPresenting) {
  16133. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  16134. return;
  16135. }
  16136. _width = width;
  16137. _height = height;
  16138. _canvas.width = Math.floor(width * _pixelRatio);
  16139. _canvas.height = Math.floor(height * _pixelRatio);
  16140. if (updateStyle !== false) {
  16141. _canvas.style.width = width + 'px';
  16142. _canvas.style.height = height + 'px';
  16143. }
  16144. this.setViewport(0, 0, width, height);
  16145. };
  16146. this.getDrawingBufferSize = function (target) {
  16147. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  16148. };
  16149. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  16150. _width = width;
  16151. _height = height;
  16152. _pixelRatio = pixelRatio;
  16153. _canvas.width = Math.floor(width * pixelRatio);
  16154. _canvas.height = Math.floor(height * pixelRatio);
  16155. this.setViewport(0, 0, width, height);
  16156. };
  16157. this.getCurrentViewport = function (target) {
  16158. return target.copy(_currentViewport);
  16159. };
  16160. this.getViewport = function (target) {
  16161. return target.copy(_viewport);
  16162. };
  16163. this.setViewport = function (x, y, width, height) {
  16164. if (x.isVector4) {
  16165. _viewport.set(x.x, x.y, x.z, x.w);
  16166. } else {
  16167. _viewport.set(x, y, width, height);
  16168. }
  16169. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  16170. };
  16171. this.getScissor = function (target) {
  16172. return target.copy(_scissor);
  16173. };
  16174. this.setScissor = function (x, y, width, height) {
  16175. if (x.isVector4) {
  16176. _scissor.set(x.x, x.y, x.z, x.w);
  16177. } else {
  16178. _scissor.set(x, y, width, height);
  16179. }
  16180. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  16181. };
  16182. this.getScissorTest = function () {
  16183. return _scissorTest;
  16184. };
  16185. this.setScissorTest = function (boolean) {
  16186. state.setScissorTest(_scissorTest = boolean);
  16187. };
  16188. this.setOpaqueSort = function (method) {
  16189. _opaqueSort = method;
  16190. };
  16191. this.setTransparentSort = function (method) {
  16192. _transparentSort = method;
  16193. }; // Clearing
  16194. this.getClearColor = function (target) {
  16195. return target.copy(background.getClearColor());
  16196. };
  16197. this.setClearColor = function () {
  16198. background.setClearColor.apply(background, arguments);
  16199. };
  16200. this.getClearAlpha = function () {
  16201. return background.getClearAlpha();
  16202. };
  16203. this.setClearAlpha = function () {
  16204. background.setClearAlpha.apply(background, arguments);
  16205. };
  16206. this.clear = function (color = true, depth = true, stencil = true) {
  16207. let bits = 0;
  16208. if (color) bits |= _gl.COLOR_BUFFER_BIT;
  16209. if (depth) bits |= _gl.DEPTH_BUFFER_BIT;
  16210. if (stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  16211. _gl.clear(bits);
  16212. };
  16213. this.clearColor = function () {
  16214. this.clear(true, false, false);
  16215. };
  16216. this.clearDepth = function () {
  16217. this.clear(false, true, false);
  16218. };
  16219. this.clearStencil = function () {
  16220. this.clear(false, false, true);
  16221. }; //
  16222. this.dispose = function () {
  16223. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  16224. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  16225. _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  16226. renderLists.dispose();
  16227. renderStates.dispose();
  16228. properties.dispose();
  16229. cubemaps.dispose();
  16230. cubeuvmaps.dispose();
  16231. objects.dispose();
  16232. bindingStates.dispose();
  16233. uniformsGroups.dispose();
  16234. programCache.dispose();
  16235. xr.dispose();
  16236. xr.removeEventListener('sessionstart', onXRSessionStart);
  16237. xr.removeEventListener('sessionend', onXRSessionEnd);
  16238. if (_transmissionRenderTarget) {
  16239. _transmissionRenderTarget.dispose();
  16240. _transmissionRenderTarget = null;
  16241. }
  16242. animation.stop();
  16243. }; // Events
  16244. function onContextLost(event) {
  16245. event.preventDefault();
  16246. console.log('THREE.WebGLRenderer: Context Lost.');
  16247. _isContextLost = true;
  16248. }
  16249. function
  16250. /* event */
  16251. onContextRestore() {
  16252. console.log('THREE.WebGLRenderer: Context Restored.');
  16253. _isContextLost = false;
  16254. const infoAutoReset = info.autoReset;
  16255. const shadowMapEnabled = shadowMap.enabled;
  16256. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16257. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16258. const shadowMapType = shadowMap.type;
  16259. initGLContext();
  16260. info.autoReset = infoAutoReset;
  16261. shadowMap.enabled = shadowMapEnabled;
  16262. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16263. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16264. shadowMap.type = shadowMapType;
  16265. }
  16266. function onContextCreationError(event) {
  16267. console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage);
  16268. }
  16269. function onMaterialDispose(event) {
  16270. const material = event.target;
  16271. material.removeEventListener('dispose', onMaterialDispose);
  16272. deallocateMaterial(material);
  16273. } // Buffer deallocation
  16274. function deallocateMaterial(material) {
  16275. releaseMaterialProgramReferences(material);
  16276. properties.remove(material);
  16277. }
  16278. function releaseMaterialProgramReferences(material) {
  16279. const programs = properties.get(material).programs;
  16280. if (programs !== undefined) {
  16281. programs.forEach(function (program) {
  16282. programCache.releaseProgram(program);
  16283. });
  16284. if (material.isShaderMaterial) {
  16285. programCache.releaseShaderCache(material);
  16286. }
  16287. }
  16288. } // Buffer rendering
  16289. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  16290. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16291. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  16292. const program = setProgram(camera, scene, geometry, material, object);
  16293. state.setMaterial(material, frontFaceCW); //
  16294. let index = geometry.index;
  16295. const position = geometry.attributes.position; //
  16296. if (index === null) {
  16297. if (position === undefined || position.count === 0) return;
  16298. } else if (index.count === 0) {
  16299. return;
  16300. } //
  16301. let rangeFactor = 1;
  16302. if (material.wireframe === true) {
  16303. index = geometries.getWireframeAttribute(geometry);
  16304. rangeFactor = 2;
  16305. }
  16306. bindingStates.setup(object, material, program, geometry, index);
  16307. let attribute;
  16308. let renderer = bufferRenderer;
  16309. if (index !== null) {
  16310. attribute = attributes.get(index);
  16311. renderer = indexedBufferRenderer;
  16312. renderer.setIndex(attribute);
  16313. } //
  16314. const dataCount = index !== null ? index.count : position.count;
  16315. const rangeStart = geometry.drawRange.start * rangeFactor;
  16316. const rangeCount = geometry.drawRange.count * rangeFactor;
  16317. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16318. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16319. const drawStart = Math.max(rangeStart, groupStart);
  16320. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  16321. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  16322. if (drawCount === 0) return; //
  16323. if (object.isMesh) {
  16324. if (material.wireframe === true) {
  16325. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16326. renderer.setMode(_gl.LINES);
  16327. } else {
  16328. renderer.setMode(_gl.TRIANGLES);
  16329. }
  16330. } else if (object.isLine) {
  16331. let lineWidth = material.linewidth;
  16332. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16333. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16334. if (object.isLineSegments) {
  16335. renderer.setMode(_gl.LINES);
  16336. } else if (object.isLineLoop) {
  16337. renderer.setMode(_gl.LINE_LOOP);
  16338. } else {
  16339. renderer.setMode(_gl.LINE_STRIP);
  16340. }
  16341. } else if (object.isPoints) {
  16342. renderer.setMode(_gl.POINTS);
  16343. } else if (object.isSprite) {
  16344. renderer.setMode(_gl.TRIANGLES);
  16345. }
  16346. if (object.isInstancedMesh) {
  16347. renderer.renderInstances(drawStart, drawCount, object.count);
  16348. } else if (geometry.isInstancedBufferGeometry) {
  16349. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  16350. renderer.renderInstances(drawStart, drawCount, instanceCount);
  16351. } else {
  16352. renderer.render(drawStart, drawCount);
  16353. }
  16354. }; // Compile
  16355. this.compile = function (scene, camera) {
  16356. function prepare(material, scene, object) {
  16357. if (material.transparent === true && material.side === DoubleSide) {
  16358. material.side = BackSide;
  16359. material.needsUpdate = true;
  16360. getProgram(material, scene, object);
  16361. material.side = FrontSide;
  16362. material.needsUpdate = true;
  16363. getProgram(material, scene, object);
  16364. material.side = DoubleSide;
  16365. } else {
  16366. getProgram(material, scene, object);
  16367. }
  16368. }
  16369. currentRenderState = renderStates.get(scene);
  16370. currentRenderState.init();
  16371. renderStateStack.push(currentRenderState);
  16372. scene.traverseVisible(function (object) {
  16373. if (object.isLight && object.layers.test(camera.layers)) {
  16374. currentRenderState.pushLight(object);
  16375. if (object.castShadow) {
  16376. currentRenderState.pushShadow(object);
  16377. }
  16378. }
  16379. });
  16380. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16381. scene.traverse(function (object) {
  16382. const material = object.material;
  16383. if (material) {
  16384. if (Array.isArray(material)) {
  16385. for (let i = 0; i < material.length; i++) {
  16386. const material2 = material[i];
  16387. prepare(material2, scene, object);
  16388. }
  16389. } else {
  16390. prepare(material, scene, object);
  16391. }
  16392. }
  16393. });
  16394. renderStateStack.pop();
  16395. currentRenderState = null;
  16396. }; // Animation Loop
  16397. let onAnimationFrameCallback = null;
  16398. function onAnimationFrame(time) {
  16399. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16400. }
  16401. function onXRSessionStart() {
  16402. animation.stop();
  16403. }
  16404. function onXRSessionEnd() {
  16405. animation.start();
  16406. }
  16407. const animation = new WebGLAnimation();
  16408. animation.setAnimationLoop(onAnimationFrame);
  16409. if (typeof self !== 'undefined') animation.setContext(self);
  16410. this.setAnimationLoop = function (callback) {
  16411. onAnimationFrameCallback = callback;
  16412. xr.setAnimationLoop(callback);
  16413. callback === null ? animation.stop() : animation.start();
  16414. };
  16415. xr.addEventListener('sessionstart', onXRSessionStart);
  16416. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  16417. this.render = function (scene, camera) {
  16418. if (camera !== undefined && camera.isCamera !== true) {
  16419. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16420. return;
  16421. }
  16422. if (_isContextLost === true) return; // update scene graph
  16423. if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16424. if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
  16425. if (xr.enabled === true && xr.isPresenting === true) {
  16426. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  16427. camera = xr.getCamera(); // use XR camera for rendering
  16428. } //
  16429. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  16430. currentRenderState = renderStates.get(scene, renderStateStack.length);
  16431. currentRenderState.init();
  16432. renderStateStack.push(currentRenderState);
  16433. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16434. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  16435. _localClippingEnabled = this.localClippingEnabled;
  16436. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16437. currentRenderList = renderLists.get(scene, renderListStack.length);
  16438. currentRenderList.init();
  16439. renderListStack.push(currentRenderList);
  16440. projectObject(scene, camera, 0, _this.sortObjects);
  16441. currentRenderList.finish();
  16442. if (_this.sortObjects === true) {
  16443. currentRenderList.sort(_opaqueSort, _transparentSort);
  16444. } //
  16445. if (_clippingEnabled === true) clipping.beginShadows();
  16446. const shadowsArray = currentRenderState.state.shadowsArray;
  16447. shadowMap.render(shadowsArray, scene, camera);
  16448. if (_clippingEnabled === true) clipping.endShadows(); //
  16449. if (this.info.autoReset === true) this.info.reset(); //
  16450. background.render(currentRenderList, scene); // render scene
  16451. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16452. if (camera.isArrayCamera) {
  16453. const cameras = camera.cameras;
  16454. for (let i = 0, l = cameras.length; i < l; i++) {
  16455. const camera2 = cameras[i];
  16456. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16457. }
  16458. } else {
  16459. renderScene(currentRenderList, scene, camera);
  16460. } //
  16461. if (_currentRenderTarget !== null) {
  16462. // resolve multisample renderbuffers to a single-sample texture if necessary
  16463. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  16464. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16465. } //
  16466. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // _gl.finish();
  16467. bindingStates.resetDefaultState();
  16468. _currentMaterialId = -1;
  16469. _currentCamera = null;
  16470. renderStateStack.pop();
  16471. if (renderStateStack.length > 0) {
  16472. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16473. } else {
  16474. currentRenderState = null;
  16475. }
  16476. renderListStack.pop();
  16477. if (renderListStack.length > 0) {
  16478. currentRenderList = renderListStack[renderListStack.length - 1];
  16479. } else {
  16480. currentRenderList = null;
  16481. }
  16482. };
  16483. function projectObject(object, camera, groupOrder, sortObjects) {
  16484. if (object.visible === false) return;
  16485. const visible = object.layers.test(camera.layers);
  16486. if (visible) {
  16487. if (object.isGroup) {
  16488. groupOrder = object.renderOrder;
  16489. } else if (object.isLOD) {
  16490. if (object.autoUpdate === true) object.update(camera);
  16491. } else if (object.isLight) {
  16492. currentRenderState.pushLight(object);
  16493. if (object.castShadow) {
  16494. currentRenderState.pushShadow(object);
  16495. }
  16496. } else if (object.isSprite) {
  16497. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16498. if (sortObjects) {
  16499. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16500. }
  16501. const geometry = objects.update(object);
  16502. const material = object.material;
  16503. if (material.visible) {
  16504. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16505. }
  16506. }
  16507. } else if (object.isMesh || object.isLine || object.isPoints) {
  16508. if (object.isSkinnedMesh) {
  16509. // update skeleton only once in a frame
  16510. if (object.skeleton.frame !== info.render.frame) {
  16511. object.skeleton.update();
  16512. object.skeleton.frame = info.render.frame;
  16513. }
  16514. }
  16515. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16516. if (sortObjects) {
  16517. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16518. }
  16519. const geometry = objects.update(object);
  16520. const material = object.material;
  16521. if (Array.isArray(material)) {
  16522. const groups = geometry.groups;
  16523. for (let i = 0, l = groups.length; i < l; i++) {
  16524. const group = groups[i];
  16525. const groupMaterial = material[group.materialIndex];
  16526. if (groupMaterial && groupMaterial.visible) {
  16527. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16528. }
  16529. }
  16530. } else if (material.visible) {
  16531. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16532. }
  16533. }
  16534. }
  16535. }
  16536. const children = object.children;
  16537. for (let i = 0, l = children.length; i < l; i++) {
  16538. projectObject(children[i], camera, groupOrder, sortObjects);
  16539. }
  16540. }
  16541. function renderScene(currentRenderList, scene, camera, viewport) {
  16542. const opaqueObjects = currentRenderList.opaque;
  16543. const transmissiveObjects = currentRenderList.transmissive;
  16544. const transparentObjects = currentRenderList.transparent;
  16545. currentRenderState.setupLightsView(camera);
  16546. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16547. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16548. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16549. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16550. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  16551. state.buffers.depth.setTest(true);
  16552. state.buffers.depth.setMask(true);
  16553. state.buffers.color.setMask(true);
  16554. state.setPolygonOffset(false);
  16555. }
  16556. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16557. const isWebGL2 = capabilities.isWebGL2;
  16558. if (_transmissionRenderTarget === null) {
  16559. _transmissionRenderTarget = new WebGLRenderTarget(1, 1, {
  16560. generateMipmaps: true,
  16561. type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType,
  16562. minFilter: LinearMipmapLinearFilter,
  16563. samples: isWebGL2 && _antialias === true ? 4 : 0
  16564. });
  16565. }
  16566. _this.getDrawingBufferSize(_vector2);
  16567. if (isWebGL2) {
  16568. _transmissionRenderTarget.setSize(_vector2.x, _vector2.y);
  16569. } else {
  16570. _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y));
  16571. } //
  16572. const currentRenderTarget = _this.getRenderTarget();
  16573. _this.setRenderTarget(_transmissionRenderTarget);
  16574. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16575. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16576. const currentToneMapping = _this.toneMapping;
  16577. _this.toneMapping = NoToneMapping;
  16578. renderObjects(opaqueObjects, scene, camera);
  16579. _this.toneMapping = currentToneMapping;
  16580. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16581. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16582. _this.setRenderTarget(currentRenderTarget);
  16583. }
  16584. function renderObjects(renderList, scene, camera) {
  16585. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16586. for (let i = 0, l = renderList.length; i < l; i++) {
  16587. const renderItem = renderList[i];
  16588. const object = renderItem.object;
  16589. const geometry = renderItem.geometry;
  16590. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16591. const group = renderItem.group;
  16592. if (object.layers.test(camera.layers)) {
  16593. renderObject(object, scene, camera, geometry, material, group);
  16594. }
  16595. }
  16596. }
  16597. function renderObject(object, scene, camera, geometry, material, group) {
  16598. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16599. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16600. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16601. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16602. if (material.transparent === true && material.side === DoubleSide) {
  16603. material.side = BackSide;
  16604. material.needsUpdate = true;
  16605. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16606. material.side = FrontSide;
  16607. material.needsUpdate = true;
  16608. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16609. material.side = DoubleSide;
  16610. } else {
  16611. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16612. }
  16613. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16614. }
  16615. function getProgram(material, scene, object) {
  16616. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16617. const materialProperties = properties.get(material);
  16618. const lights = currentRenderState.state.lights;
  16619. const shadowsArray = currentRenderState.state.shadowsArray;
  16620. const lightsStateVersion = lights.state.version;
  16621. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16622. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16623. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16624. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16625. materialProperties.fog = scene.fog;
  16626. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16627. if (programs === undefined) {
  16628. // new material
  16629. material.addEventListener('dispose', onMaterialDispose);
  16630. programs = new Map();
  16631. materialProperties.programs = programs;
  16632. }
  16633. let program = programs.get(programCacheKey);
  16634. if (program !== undefined) {
  16635. // early out if program and light state is identical
  16636. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16637. updateCommonMaterialProperties(material, parameters);
  16638. return program;
  16639. }
  16640. } else {
  16641. parameters.uniforms = programCache.getUniforms(material);
  16642. material.onBuild(object, parameters, _this);
  16643. material.onBeforeCompile(parameters, _this);
  16644. program = programCache.acquireProgram(parameters, programCacheKey);
  16645. programs.set(programCacheKey, program);
  16646. materialProperties.uniforms = parameters.uniforms;
  16647. }
  16648. const uniforms = materialProperties.uniforms;
  16649. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16650. uniforms.clippingPlanes = clipping.uniform;
  16651. }
  16652. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16653. materialProperties.needsLights = materialNeedsLights(material);
  16654. materialProperties.lightsStateVersion = lightsStateVersion;
  16655. if (materialProperties.needsLights) {
  16656. // wire up the material to this renderer's lighting state
  16657. uniforms.ambientLightColor.value = lights.state.ambient;
  16658. uniforms.lightProbe.value = lights.state.probe;
  16659. uniforms.directionalLights.value = lights.state.directional;
  16660. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16661. uniforms.spotLights.value = lights.state.spot;
  16662. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16663. uniforms.rectAreaLights.value = lights.state.rectArea;
  16664. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16665. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16666. uniforms.pointLights.value = lights.state.point;
  16667. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16668. uniforms.hemisphereLights.value = lights.state.hemi;
  16669. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16670. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16671. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16672. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16673. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16674. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16675. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16676. }
  16677. const progUniforms = program.getUniforms();
  16678. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16679. materialProperties.currentProgram = program;
  16680. materialProperties.uniformsList = uniformsList;
  16681. return program;
  16682. }
  16683. function updateCommonMaterialProperties(material, parameters) {
  16684. const materialProperties = properties.get(material);
  16685. materialProperties.outputEncoding = parameters.outputEncoding;
  16686. materialProperties.instancing = parameters.instancing;
  16687. materialProperties.skinning = parameters.skinning;
  16688. materialProperties.morphTargets = parameters.morphTargets;
  16689. materialProperties.morphNormals = parameters.morphNormals;
  16690. materialProperties.morphColors = parameters.morphColors;
  16691. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16692. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16693. materialProperties.numIntersection = parameters.numClipIntersection;
  16694. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16695. materialProperties.vertexTangents = parameters.vertexTangents;
  16696. materialProperties.toneMapping = parameters.toneMapping;
  16697. }
  16698. function setProgram(camera, scene, geometry, material, object) {
  16699. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16700. textures.resetTextureUnits();
  16701. const fog = scene.fog;
  16702. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16703. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
  16704. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16705. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16706. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16707. const morphTargets = !!geometry.morphAttributes.position;
  16708. const morphNormals = !!geometry.morphAttributes.normal;
  16709. const morphColors = !!geometry.morphAttributes.color;
  16710. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16711. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16712. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  16713. const materialProperties = properties.get(material);
  16714. const lights = currentRenderState.state.lights;
  16715. if (_clippingEnabled === true) {
  16716. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16717. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16718. // object instead of the material, once it becomes feasible
  16719. // (#8465, #8379)
  16720. clipping.setState(material, camera, useCache);
  16721. }
  16722. } //
  16723. let needsProgramChange = false;
  16724. if (material.version === materialProperties.__version) {
  16725. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16726. needsProgramChange = true;
  16727. } else if (materialProperties.outputEncoding !== encoding) {
  16728. needsProgramChange = true;
  16729. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16730. needsProgramChange = true;
  16731. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16732. needsProgramChange = true;
  16733. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16734. needsProgramChange = true;
  16735. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16736. needsProgramChange = true;
  16737. } else if (materialProperties.envMap !== envMap) {
  16738. needsProgramChange = true;
  16739. } else if (material.fog === true && materialProperties.fog !== fog) {
  16740. needsProgramChange = true;
  16741. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16742. needsProgramChange = true;
  16743. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16744. needsProgramChange = true;
  16745. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16746. needsProgramChange = true;
  16747. } else if (materialProperties.morphTargets !== morphTargets) {
  16748. needsProgramChange = true;
  16749. } else if (materialProperties.morphNormals !== morphNormals) {
  16750. needsProgramChange = true;
  16751. } else if (materialProperties.morphColors !== morphColors) {
  16752. needsProgramChange = true;
  16753. } else if (materialProperties.toneMapping !== toneMapping) {
  16754. needsProgramChange = true;
  16755. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16756. needsProgramChange = true;
  16757. }
  16758. } else {
  16759. needsProgramChange = true;
  16760. materialProperties.__version = material.version;
  16761. } //
  16762. let program = materialProperties.currentProgram;
  16763. if (needsProgramChange === true) {
  16764. program = getProgram(material, scene, object);
  16765. }
  16766. let refreshProgram = false;
  16767. let refreshMaterial = false;
  16768. let refreshLights = false;
  16769. const p_uniforms = program.getUniforms(),
  16770. m_uniforms = materialProperties.uniforms;
  16771. if (state.useProgram(program.program)) {
  16772. refreshProgram = true;
  16773. refreshMaterial = true;
  16774. refreshLights = true;
  16775. }
  16776. if (material.id !== _currentMaterialId) {
  16777. _currentMaterialId = material.id;
  16778. refreshMaterial = true;
  16779. }
  16780. if (refreshProgram || _currentCamera !== camera) {
  16781. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16782. if (capabilities.logarithmicDepthBuffer) {
  16783. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16784. }
  16785. if (_currentCamera !== camera) {
  16786. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16787. // now, in case this material supports lights - or later, when
  16788. // the next material that does gets activated:
  16789. refreshMaterial = true; // set to true on material change
  16790. refreshLights = true; // remains set until update done
  16791. } // load material specific uniforms
  16792. // (shader material also gets them for the sake of genericity)
  16793. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16794. const uCamPos = p_uniforms.map.cameraPosition;
  16795. if (uCamPos !== undefined) {
  16796. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16797. }
  16798. }
  16799. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16800. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16801. }
  16802. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16803. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16804. }
  16805. } // skinning and morph target uniforms must be set even if material didn't change
  16806. // auto-setting of texture unit for bone and morph texture must go before other textures
  16807. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16808. if (object.isSkinnedMesh) {
  16809. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16810. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16811. const skeleton = object.skeleton;
  16812. if (skeleton) {
  16813. if (capabilities.floatVertexTextures) {
  16814. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16815. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16816. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16817. } else {
  16818. console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.');
  16819. }
  16820. }
  16821. }
  16822. const morphAttributes = geometry.morphAttributes;
  16823. if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) {
  16824. morphtargets.update(object, geometry, material, program);
  16825. }
  16826. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16827. materialProperties.receiveShadow = object.receiveShadow;
  16828. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16829. } // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  16830. if (material.isMeshGouraudMaterial && material.envMap !== null) {
  16831. m_uniforms.envMap.value = envMap;
  16832. m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  16833. }
  16834. if (refreshMaterial) {
  16835. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16836. if (materialProperties.needsLights) {
  16837. // the current material requires lighting info
  16838. // note: all lighting uniforms are always set correctly
  16839. // they simply reference the renderer's state for their
  16840. // values
  16841. //
  16842. // use the current material's .needsUpdate flags to set
  16843. // the GL state when required
  16844. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16845. } // refresh uniforms common to several materials
  16846. if (fog && material.fog === true) {
  16847. materials.refreshFogUniforms(m_uniforms, fog);
  16848. }
  16849. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16850. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16851. }
  16852. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16853. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16854. material.uniformsNeedUpdate = false;
  16855. }
  16856. if (material.isSpriteMaterial) {
  16857. p_uniforms.setValue(_gl, 'center', object.center);
  16858. } // common matrices
  16859. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16860. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16861. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld); // UBOs
  16862. if (material.isShaderMaterial || material.isRawShaderMaterial) {
  16863. const groups = material.uniformsGroups;
  16864. for (let i = 0, l = groups.length; i < l; i++) {
  16865. if (capabilities.isWebGL2) {
  16866. const group = groups[i];
  16867. uniformsGroups.update(group, program);
  16868. uniformsGroups.bind(group, program);
  16869. } else {
  16870. console.warn('THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.');
  16871. }
  16872. }
  16873. }
  16874. return program;
  16875. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16876. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16877. uniforms.ambientLightColor.needsUpdate = value;
  16878. uniforms.lightProbe.needsUpdate = value;
  16879. uniforms.directionalLights.needsUpdate = value;
  16880. uniforms.directionalLightShadows.needsUpdate = value;
  16881. uniforms.pointLights.needsUpdate = value;
  16882. uniforms.pointLightShadows.needsUpdate = value;
  16883. uniforms.spotLights.needsUpdate = value;
  16884. uniforms.spotLightShadows.needsUpdate = value;
  16885. uniforms.rectAreaLights.needsUpdate = value;
  16886. uniforms.hemisphereLights.needsUpdate = value;
  16887. }
  16888. function materialNeedsLights(material) {
  16889. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16890. }
  16891. this.getActiveCubeFace = function () {
  16892. return _currentActiveCubeFace;
  16893. };
  16894. this.getActiveMipmapLevel = function () {
  16895. return _currentActiveMipmapLevel;
  16896. };
  16897. this.getRenderTarget = function () {
  16898. return _currentRenderTarget;
  16899. };
  16900. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16901. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16902. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16903. const renderTargetProperties = properties.get(renderTarget);
  16904. renderTargetProperties.__hasExternalTextures = true;
  16905. if (renderTargetProperties.__hasExternalTextures) {
  16906. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16907. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16908. // The multisample_render_to_texture extension doesn't work properly if there
  16909. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16910. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  16911. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  16912. renderTargetProperties.__useRenderToTexture = false;
  16913. }
  16914. }
  16915. }
  16916. };
  16917. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16918. const renderTargetProperties = properties.get(renderTarget);
  16919. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16920. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16921. };
  16922. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16923. _currentRenderTarget = renderTarget;
  16924. _currentActiveCubeFace = activeCubeFace;
  16925. _currentActiveMipmapLevel = activeMipmapLevel;
  16926. let useDefaultFramebuffer = true;
  16927. if (renderTarget) {
  16928. const renderTargetProperties = properties.get(renderTarget);
  16929. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16930. // We need to make sure to rebind the framebuffer.
  16931. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16932. useDefaultFramebuffer = false;
  16933. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16934. textures.setupRenderTarget(renderTarget);
  16935. } else if (renderTargetProperties.__hasExternalTextures) {
  16936. // Color and depth texture must be rebound in order for the swapchain to update.
  16937. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16938. }
  16939. }
  16940. let framebuffer = null;
  16941. let isCube = false;
  16942. let isRenderTarget3D = false;
  16943. if (renderTarget) {
  16944. const texture = renderTarget.texture;
  16945. if (texture.isData3DTexture || texture.isDataArrayTexture) {
  16946. isRenderTarget3D = true;
  16947. }
  16948. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16949. if (renderTarget.isWebGLCubeRenderTarget) {
  16950. framebuffer = __webglFramebuffer[activeCubeFace];
  16951. isCube = true;
  16952. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  16953. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16954. } else {
  16955. framebuffer = __webglFramebuffer;
  16956. }
  16957. _currentViewport.copy(renderTarget.viewport);
  16958. _currentScissor.copy(renderTarget.scissor);
  16959. _currentScissorTest = renderTarget.scissorTest;
  16960. } else {
  16961. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16962. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16963. _currentScissorTest = _scissorTest;
  16964. }
  16965. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16966. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16967. state.drawBuffers(renderTarget, framebuffer);
  16968. }
  16969. state.viewport(_currentViewport);
  16970. state.scissor(_currentScissor);
  16971. state.setScissorTest(_currentScissorTest);
  16972. if (isCube) {
  16973. const textureProperties = properties.get(renderTarget.texture);
  16974. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16975. } else if (isRenderTarget3D) {
  16976. const textureProperties = properties.get(renderTarget.texture);
  16977. const layer = activeCubeFace || 0;
  16978. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16979. }
  16980. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16981. };
  16982. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16983. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16984. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16985. return;
  16986. }
  16987. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16988. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16989. framebuffer = framebuffer[activeCubeFaceIndex];
  16990. }
  16991. if (framebuffer) {
  16992. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16993. try {
  16994. const texture = renderTarget.texture;
  16995. const textureFormat = texture.format;
  16996. const textureType = texture.type;
  16997. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16998. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16999. return;
  17000. }
  17001. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  17002. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  17003. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  17004. !halfFloatSupportedByExt) {
  17005. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  17006. return;
  17007. } // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17008. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  17009. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  17010. }
  17011. } finally {
  17012. // restore framebuffer of current render target if necessary
  17013. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  17014. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  17015. }
  17016. }
  17017. };
  17018. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  17019. const levelScale = Math.pow(2, -level);
  17020. const width = Math.floor(texture.image.width * levelScale);
  17021. const height = Math.floor(texture.image.height * levelScale);
  17022. textures.setTexture2D(texture, 0);
  17023. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  17024. state.unbindTexture();
  17025. };
  17026. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  17027. const width = srcTexture.image.width;
  17028. const height = srcTexture.image.height;
  17029. const glFormat = utils.convert(dstTexture.format);
  17030. const glType = utils.convert(dstTexture.type);
  17031. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  17032. // parameters, make sure they are correct for the dstTexture
  17033. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17034. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17035. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17036. if (srcTexture.isDataTexture) {
  17037. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  17038. } else {
  17039. if (srcTexture.isCompressedTexture) {
  17040. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  17041. } else {
  17042. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  17043. }
  17044. } // Generate mipmaps only when copying level 0
  17045. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  17046. state.unbindTexture();
  17047. };
  17048. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  17049. if (_this.isWebGL1Renderer) {
  17050. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  17051. return;
  17052. }
  17053. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17054. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17055. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17056. const glFormat = utils.convert(dstTexture.format);
  17057. const glType = utils.convert(dstTexture.type);
  17058. let glTarget;
  17059. if (dstTexture.isData3DTexture) {
  17060. textures.setTexture3D(dstTexture, 0);
  17061. glTarget = _gl.TEXTURE_3D;
  17062. } else if (dstTexture.isDataArrayTexture) {
  17063. textures.setTexture2DArray(dstTexture, 0);
  17064. glTarget = _gl.TEXTURE_2D_ARRAY;
  17065. } else {
  17066. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  17067. return;
  17068. }
  17069. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  17070. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  17071. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  17072. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  17073. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  17074. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  17075. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  17076. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  17077. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  17078. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  17079. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  17080. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  17081. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  17082. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  17083. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  17084. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  17085. } else {
  17086. if (srcTexture.isCompressedTexture) {
  17087. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  17088. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  17089. } else {
  17090. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  17091. }
  17092. }
  17093. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  17094. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  17095. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  17096. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  17097. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  17098. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  17099. state.unbindTexture();
  17100. };
  17101. this.initTexture = function (texture) {
  17102. if (texture.isCubeTexture) {
  17103. textures.setTextureCube(texture, 0);
  17104. } else if (texture.isData3DTexture) {
  17105. textures.setTexture3D(texture, 0);
  17106. } else if (texture.isDataArrayTexture) {
  17107. textures.setTexture2DArray(texture, 0);
  17108. } else {
  17109. textures.setTexture2D(texture, 0);
  17110. }
  17111. state.unbindTexture();
  17112. };
  17113. this.resetState = function () {
  17114. _currentActiveCubeFace = 0;
  17115. _currentActiveMipmapLevel = 0;
  17116. _currentRenderTarget = null;
  17117. state.reset();
  17118. bindingStates.reset();
  17119. };
  17120. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17121. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17122. detail: this
  17123. }));
  17124. }
  17125. }
  17126. class WebGL1Renderer extends WebGLRenderer {}
  17127. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17128. class FogExp2 {
  17129. constructor(color, density = 0.00025) {
  17130. this.isFogExp2 = true;
  17131. this.name = '';
  17132. this.color = new Color(color);
  17133. this.density = density;
  17134. }
  17135. clone() {
  17136. return new FogExp2(this.color, this.density);
  17137. }
  17138. toJSON() {
  17139. return {
  17140. type: 'FogExp2',
  17141. color: this.color.getHex(),
  17142. density: this.density
  17143. };
  17144. }
  17145. }
  17146. class Fog {
  17147. constructor(color, near = 1, far = 1000) {
  17148. this.isFog = true;
  17149. this.name = '';
  17150. this.color = new Color(color);
  17151. this.near = near;
  17152. this.far = far;
  17153. }
  17154. clone() {
  17155. return new Fog(this.color, this.near, this.far);
  17156. }
  17157. toJSON() {
  17158. return {
  17159. type: 'Fog',
  17160. color: this.color.getHex(),
  17161. near: this.near,
  17162. far: this.far
  17163. };
  17164. }
  17165. }
  17166. class Scene extends Object3D {
  17167. constructor() {
  17168. super();
  17169. this.isScene = true;
  17170. this.type = 'Scene';
  17171. this.background = null;
  17172. this.environment = null;
  17173. this.fog = null;
  17174. this.overrideMaterial = null;
  17175. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  17176. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  17177. detail: this
  17178. }));
  17179. }
  17180. }
  17181. copy(source, recursive) {
  17182. super.copy(source, recursive);
  17183. if (source.background !== null) this.background = source.background.clone();
  17184. if (source.environment !== null) this.environment = source.environment.clone();
  17185. if (source.fog !== null) this.fog = source.fog.clone();
  17186. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  17187. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17188. return this;
  17189. }
  17190. toJSON(meta) {
  17191. const data = super.toJSON(meta);
  17192. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  17193. return data;
  17194. } // Deprecated
  17195. get autoUpdate() {
  17196. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17197. return this.matrixWorldAutoUpdate;
  17198. }
  17199. set autoUpdate(value) {
  17200. console.warn('THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.');
  17201. this.matrixWorldAutoUpdate = value;
  17202. }
  17203. }
  17204. class InterleavedBuffer {
  17205. constructor(array, stride) {
  17206. this.isInterleavedBuffer = true;
  17207. this.array = array;
  17208. this.stride = stride;
  17209. this.count = array !== undefined ? array.length / stride : 0;
  17210. this.usage = StaticDrawUsage;
  17211. this.updateRange = {
  17212. offset: 0,
  17213. count: -1
  17214. };
  17215. this.version = 0;
  17216. this.uuid = generateUUID();
  17217. }
  17218. onUploadCallback() {}
  17219. set needsUpdate(value) {
  17220. if (value === true) this.version++;
  17221. }
  17222. setUsage(value) {
  17223. this.usage = value;
  17224. return this;
  17225. }
  17226. copy(source) {
  17227. this.array = new source.array.constructor(source.array);
  17228. this.count = source.count;
  17229. this.stride = source.stride;
  17230. this.usage = source.usage;
  17231. return this;
  17232. }
  17233. copyAt(index1, attribute, index2) {
  17234. index1 *= this.stride;
  17235. index2 *= attribute.stride;
  17236. for (let i = 0, l = this.stride; i < l; i++) {
  17237. this.array[index1 + i] = attribute.array[index2 + i];
  17238. }
  17239. return this;
  17240. }
  17241. set(value, offset = 0) {
  17242. this.array.set(value, offset);
  17243. return this;
  17244. }
  17245. clone(data) {
  17246. if (data.arrayBuffers === undefined) {
  17247. data.arrayBuffers = {};
  17248. }
  17249. if (this.array.buffer._uuid === undefined) {
  17250. this.array.buffer._uuid = generateUUID();
  17251. }
  17252. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17253. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  17254. }
  17255. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  17256. const ib = new this.constructor(array, this.stride);
  17257. ib.setUsage(this.usage);
  17258. return ib;
  17259. }
  17260. onUpload(callback) {
  17261. this.onUploadCallback = callback;
  17262. return this;
  17263. }
  17264. toJSON(data) {
  17265. if (data.arrayBuffers === undefined) {
  17266. data.arrayBuffers = {};
  17267. } // generate UUID for array buffer if necessary
  17268. if (this.array.buffer._uuid === undefined) {
  17269. this.array.buffer._uuid = generateUUID();
  17270. }
  17271. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  17272. data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer));
  17273. } //
  17274. return {
  17275. uuid: this.uuid,
  17276. buffer: this.array.buffer._uuid,
  17277. type: this.array.constructor.name,
  17278. stride: this.stride
  17279. };
  17280. }
  17281. }
  17282. const _vector$6 = /*@__PURE__*/new Vector3();
  17283. class InterleavedBufferAttribute {
  17284. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  17285. this.isInterleavedBufferAttribute = true;
  17286. this.name = '';
  17287. this.data = interleavedBuffer;
  17288. this.itemSize = itemSize;
  17289. this.offset = offset;
  17290. this.normalized = normalized === true;
  17291. }
  17292. get count() {
  17293. return this.data.count;
  17294. }
  17295. get array() {
  17296. return this.data.array;
  17297. }
  17298. set needsUpdate(value) {
  17299. this.data.needsUpdate = value;
  17300. }
  17301. applyMatrix4(m) {
  17302. for (let i = 0, l = this.data.count; i < l; i++) {
  17303. _vector$6.fromBufferAttribute(this, i);
  17304. _vector$6.applyMatrix4(m);
  17305. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17306. }
  17307. return this;
  17308. }
  17309. applyNormalMatrix(m) {
  17310. for (let i = 0, l = this.count; i < l; i++) {
  17311. _vector$6.fromBufferAttribute(this, i);
  17312. _vector$6.applyNormalMatrix(m);
  17313. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17314. }
  17315. return this;
  17316. }
  17317. transformDirection(m) {
  17318. for (let i = 0, l = this.count; i < l; i++) {
  17319. _vector$6.fromBufferAttribute(this, i);
  17320. _vector$6.transformDirection(m);
  17321. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  17322. }
  17323. return this;
  17324. }
  17325. setX(index, x) {
  17326. if (this.normalized) x = normalize(x, this.array);
  17327. this.data.array[index * this.data.stride + this.offset] = x;
  17328. return this;
  17329. }
  17330. setY(index, y) {
  17331. if (this.normalized) y = normalize(y, this.array);
  17332. this.data.array[index * this.data.stride + this.offset + 1] = y;
  17333. return this;
  17334. }
  17335. setZ(index, z) {
  17336. if (this.normalized) z = normalize(z, this.array);
  17337. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17338. return this;
  17339. }
  17340. setW(index, w) {
  17341. if (this.normalized) w = normalize(w, this.array);
  17342. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17343. return this;
  17344. }
  17345. getX(index) {
  17346. let x = this.data.array[index * this.data.stride + this.offset];
  17347. if (this.normalized) x = denormalize(x, this.array);
  17348. return x;
  17349. }
  17350. getY(index) {
  17351. let y = this.data.array[index * this.data.stride + this.offset + 1];
  17352. if (this.normalized) y = denormalize(y, this.array);
  17353. return y;
  17354. }
  17355. getZ(index) {
  17356. let z = this.data.array[index * this.data.stride + this.offset + 2];
  17357. if (this.normalized) z = denormalize(z, this.array);
  17358. return z;
  17359. }
  17360. getW(index) {
  17361. let w = this.data.array[index * this.data.stride + this.offset + 3];
  17362. if (this.normalized) w = denormalize(w, this.array);
  17363. return w;
  17364. }
  17365. setXY(index, x, y) {
  17366. index = index * this.data.stride + this.offset;
  17367. if (this.normalized) {
  17368. x = normalize(x, this.array);
  17369. y = normalize(y, this.array);
  17370. }
  17371. this.data.array[index + 0] = x;
  17372. this.data.array[index + 1] = y;
  17373. return this;
  17374. }
  17375. setXYZ(index, x, y, z) {
  17376. index = index * this.data.stride + this.offset;
  17377. if (this.normalized) {
  17378. x = normalize(x, this.array);
  17379. y = normalize(y, this.array);
  17380. z = normalize(z, this.array);
  17381. }
  17382. this.data.array[index + 0] = x;
  17383. this.data.array[index + 1] = y;
  17384. this.data.array[index + 2] = z;
  17385. return this;
  17386. }
  17387. setXYZW(index, x, y, z, w) {
  17388. index = index * this.data.stride + this.offset;
  17389. if (this.normalized) {
  17390. x = normalize(x, this.array);
  17391. y = normalize(y, this.array);
  17392. z = normalize(z, this.array);
  17393. w = normalize(w, this.array);
  17394. }
  17395. this.data.array[index + 0] = x;
  17396. this.data.array[index + 1] = y;
  17397. this.data.array[index + 2] = z;
  17398. this.data.array[index + 3] = w;
  17399. return this;
  17400. }
  17401. clone(data) {
  17402. if (data === undefined) {
  17403. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.');
  17404. const array = [];
  17405. for (let i = 0; i < this.count; i++) {
  17406. const index = i * this.data.stride + this.offset;
  17407. for (let j = 0; j < this.itemSize; j++) {
  17408. array.push(this.data.array[index + j]);
  17409. }
  17410. }
  17411. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17412. } else {
  17413. if (data.interleavedBuffers === undefined) {
  17414. data.interleavedBuffers = {};
  17415. }
  17416. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17417. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17418. }
  17419. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17420. }
  17421. }
  17422. toJSON(data) {
  17423. if (data === undefined) {
  17424. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.');
  17425. const array = [];
  17426. for (let i = 0; i < this.count; i++) {
  17427. const index = i * this.data.stride + this.offset;
  17428. for (let j = 0; j < this.itemSize; j++) {
  17429. array.push(this.data.array[index + j]);
  17430. }
  17431. } // deinterleave data and save it as an ordinary buffer attribute for now
  17432. return {
  17433. itemSize: this.itemSize,
  17434. type: this.array.constructor.name,
  17435. array: array,
  17436. normalized: this.normalized
  17437. };
  17438. } else {
  17439. // save as true interleaved attribtue
  17440. if (data.interleavedBuffers === undefined) {
  17441. data.interleavedBuffers = {};
  17442. }
  17443. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17444. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  17445. }
  17446. return {
  17447. isInterleavedBufferAttribute: true,
  17448. itemSize: this.itemSize,
  17449. data: this.data.uuid,
  17450. offset: this.offset,
  17451. normalized: this.normalized
  17452. };
  17453. }
  17454. }
  17455. }
  17456. class SpriteMaterial extends Material {
  17457. constructor(parameters) {
  17458. super();
  17459. this.isSpriteMaterial = true;
  17460. this.type = 'SpriteMaterial';
  17461. this.color = new Color(0xffffff);
  17462. this.map = null;
  17463. this.alphaMap = null;
  17464. this.rotation = 0;
  17465. this.sizeAttenuation = true;
  17466. this.transparent = true;
  17467. this.fog = true;
  17468. this.setValues(parameters);
  17469. }
  17470. copy(source) {
  17471. super.copy(source);
  17472. this.color.copy(source.color);
  17473. this.map = source.map;
  17474. this.alphaMap = source.alphaMap;
  17475. this.rotation = source.rotation;
  17476. this.sizeAttenuation = source.sizeAttenuation;
  17477. this.fog = source.fog;
  17478. return this;
  17479. }
  17480. }
  17481. let _geometry;
  17482. const _intersectPoint = /*@__PURE__*/new Vector3();
  17483. const _worldScale = /*@__PURE__*/new Vector3();
  17484. const _mvPosition = /*@__PURE__*/new Vector3();
  17485. const _alignedPosition = /*@__PURE__*/new Vector2();
  17486. const _rotatedPosition = /*@__PURE__*/new Vector2();
  17487. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17488. const _vA = /*@__PURE__*/new Vector3();
  17489. const _vB = /*@__PURE__*/new Vector3();
  17490. const _vC = /*@__PURE__*/new Vector3();
  17491. const _uvA = /*@__PURE__*/new Vector2();
  17492. const _uvB = /*@__PURE__*/new Vector2();
  17493. const _uvC = /*@__PURE__*/new Vector2();
  17494. class Sprite extends Object3D {
  17495. constructor(material) {
  17496. super();
  17497. this.isSprite = true;
  17498. this.type = 'Sprite';
  17499. if (_geometry === undefined) {
  17500. _geometry = new BufferGeometry();
  17501. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  17502. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17503. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17504. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17505. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17506. }
  17507. this.geometry = _geometry;
  17508. this.material = material !== undefined ? material : new SpriteMaterial();
  17509. this.center = new Vector2(0.5, 0.5);
  17510. }
  17511. raycast(raycaster, intersects) {
  17512. if (raycaster.camera === null) {
  17513. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17514. }
  17515. _worldScale.setFromMatrixScale(this.matrixWorld);
  17516. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17517. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17518. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17519. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17520. _worldScale.multiplyScalar(-_mvPosition.z);
  17521. }
  17522. const rotation = this.material.rotation;
  17523. let sin, cos;
  17524. if (rotation !== 0) {
  17525. cos = Math.cos(rotation);
  17526. sin = Math.sin(rotation);
  17527. }
  17528. const center = this.center;
  17529. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17530. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17531. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17532. _uvA.set(0, 0);
  17533. _uvB.set(1, 0);
  17534. _uvC.set(1, 1); // check first triangle
  17535. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17536. if (intersect === null) {
  17537. // check second triangle
  17538. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17539. _uvB.set(0, 1);
  17540. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17541. if (intersect === null) {
  17542. return;
  17543. }
  17544. }
  17545. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17546. if (distance < raycaster.near || distance > raycaster.far) return;
  17547. intersects.push({
  17548. distance: distance,
  17549. point: _intersectPoint.clone(),
  17550. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17551. face: null,
  17552. object: this
  17553. });
  17554. }
  17555. copy(source, recursive) {
  17556. super.copy(source, recursive);
  17557. if (source.center !== undefined) this.center.copy(source.center);
  17558. this.material = source.material;
  17559. return this;
  17560. }
  17561. }
  17562. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17563. // compute position in camera space
  17564. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17565. if (sin !== undefined) {
  17566. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17567. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17568. } else {
  17569. _rotatedPosition.copy(_alignedPosition);
  17570. }
  17571. vertexPosition.copy(mvPosition);
  17572. vertexPosition.x += _rotatedPosition.x;
  17573. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17574. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17575. }
  17576. const _v1$2 = /*@__PURE__*/new Vector3();
  17577. const _v2$1 = /*@__PURE__*/new Vector3();
  17578. class LOD extends Object3D {
  17579. constructor() {
  17580. super();
  17581. this._currentLevel = 0;
  17582. this.type = 'LOD';
  17583. Object.defineProperties(this, {
  17584. levels: {
  17585. enumerable: true,
  17586. value: []
  17587. },
  17588. isLOD: {
  17589. value: true
  17590. }
  17591. });
  17592. this.autoUpdate = true;
  17593. }
  17594. copy(source) {
  17595. super.copy(source, false);
  17596. const levels = source.levels;
  17597. for (let i = 0, l = levels.length; i < l; i++) {
  17598. const level = levels[i];
  17599. this.addLevel(level.object.clone(), level.distance);
  17600. }
  17601. this.autoUpdate = source.autoUpdate;
  17602. return this;
  17603. }
  17604. addLevel(object, distance = 0) {
  17605. distance = Math.abs(distance);
  17606. const levels = this.levels;
  17607. let l;
  17608. for (l = 0; l < levels.length; l++) {
  17609. if (distance < levels[l].distance) {
  17610. break;
  17611. }
  17612. }
  17613. levels.splice(l, 0, {
  17614. distance: distance,
  17615. object: object
  17616. });
  17617. this.add(object);
  17618. return this;
  17619. }
  17620. getCurrentLevel() {
  17621. return this._currentLevel;
  17622. }
  17623. getObjectForDistance(distance) {
  17624. const levels = this.levels;
  17625. if (levels.length > 0) {
  17626. let i, l;
  17627. for (i = 1, l = levels.length; i < l; i++) {
  17628. if (distance < levels[i].distance) {
  17629. break;
  17630. }
  17631. }
  17632. return levels[i - 1].object;
  17633. }
  17634. return null;
  17635. }
  17636. raycast(raycaster, intersects) {
  17637. const levels = this.levels;
  17638. if (levels.length > 0) {
  17639. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17640. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17641. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17642. }
  17643. }
  17644. update(camera) {
  17645. const levels = this.levels;
  17646. if (levels.length > 1) {
  17647. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17648. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17649. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17650. levels[0].object.visible = true;
  17651. let i, l;
  17652. for (i = 1, l = levels.length; i < l; i++) {
  17653. if (distance >= levels[i].distance) {
  17654. levels[i - 1].object.visible = false;
  17655. levels[i].object.visible = true;
  17656. } else {
  17657. break;
  17658. }
  17659. }
  17660. this._currentLevel = i - 1;
  17661. for (; i < l; i++) {
  17662. levels[i].object.visible = false;
  17663. }
  17664. }
  17665. }
  17666. toJSON(meta) {
  17667. const data = super.toJSON(meta);
  17668. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17669. data.object.levels = [];
  17670. const levels = this.levels;
  17671. for (let i = 0, l = levels.length; i < l; i++) {
  17672. const level = levels[i];
  17673. data.object.levels.push({
  17674. object: level.object.uuid,
  17675. distance: level.distance
  17676. });
  17677. }
  17678. return data;
  17679. }
  17680. }
  17681. const _basePosition = /*@__PURE__*/new Vector3();
  17682. const _skinIndex = /*@__PURE__*/new Vector4();
  17683. const _skinWeight = /*@__PURE__*/new Vector4();
  17684. const _vector$5 = /*@__PURE__*/new Vector3();
  17685. const _matrix = /*@__PURE__*/new Matrix4();
  17686. class SkinnedMesh extends Mesh {
  17687. constructor(geometry, material) {
  17688. super(geometry, material);
  17689. this.isSkinnedMesh = true;
  17690. this.type = 'SkinnedMesh';
  17691. this.bindMode = 'attached';
  17692. this.bindMatrix = new Matrix4();
  17693. this.bindMatrixInverse = new Matrix4();
  17694. }
  17695. copy(source, recursive) {
  17696. super.copy(source, recursive);
  17697. this.bindMode = source.bindMode;
  17698. this.bindMatrix.copy(source.bindMatrix);
  17699. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17700. this.skeleton = source.skeleton;
  17701. return this;
  17702. }
  17703. bind(skeleton, bindMatrix) {
  17704. this.skeleton = skeleton;
  17705. if (bindMatrix === undefined) {
  17706. this.updateMatrixWorld(true);
  17707. this.skeleton.calculateInverses();
  17708. bindMatrix = this.matrixWorld;
  17709. }
  17710. this.bindMatrix.copy(bindMatrix);
  17711. this.bindMatrixInverse.copy(bindMatrix).invert();
  17712. }
  17713. pose() {
  17714. this.skeleton.pose();
  17715. }
  17716. normalizeSkinWeights() {
  17717. const vector = new Vector4();
  17718. const skinWeight = this.geometry.attributes.skinWeight;
  17719. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17720. vector.fromBufferAttribute(skinWeight, i);
  17721. const scale = 1.0 / vector.manhattanLength();
  17722. if (scale !== Infinity) {
  17723. vector.multiplyScalar(scale);
  17724. } else {
  17725. vector.set(1, 0, 0, 0); // do something reasonable
  17726. }
  17727. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17728. }
  17729. }
  17730. updateMatrixWorld(force) {
  17731. super.updateMatrixWorld(force);
  17732. if (this.bindMode === 'attached') {
  17733. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17734. } else if (this.bindMode === 'detached') {
  17735. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17736. } else {
  17737. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17738. }
  17739. }
  17740. boneTransform(index, target) {
  17741. const skeleton = this.skeleton;
  17742. const geometry = this.geometry;
  17743. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17744. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17745. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17746. target.set(0, 0, 0);
  17747. for (let i = 0; i < 4; i++) {
  17748. const weight = _skinWeight.getComponent(i);
  17749. if (weight !== 0) {
  17750. const boneIndex = _skinIndex.getComponent(i);
  17751. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17752. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17753. }
  17754. }
  17755. return target.applyMatrix4(this.bindMatrixInverse);
  17756. }
  17757. }
  17758. class Bone extends Object3D {
  17759. constructor() {
  17760. super();
  17761. this.isBone = true;
  17762. this.type = 'Bone';
  17763. }
  17764. }
  17765. class DataTexture extends Texture {
  17766. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17767. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17768. this.isDataTexture = true;
  17769. this.image = {
  17770. data: data,
  17771. width: width,
  17772. height: height
  17773. };
  17774. this.generateMipmaps = false;
  17775. this.flipY = false;
  17776. this.unpackAlignment = 1;
  17777. }
  17778. }
  17779. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17780. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17781. class Skeleton {
  17782. constructor(bones = [], boneInverses = []) {
  17783. this.uuid = generateUUID();
  17784. this.bones = bones.slice(0);
  17785. this.boneInverses = boneInverses;
  17786. this.boneMatrices = null;
  17787. this.boneTexture = null;
  17788. this.boneTextureSize = 0;
  17789. this.frame = -1;
  17790. this.init();
  17791. }
  17792. init() {
  17793. const bones = this.bones;
  17794. const boneInverses = this.boneInverses;
  17795. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17796. if (boneInverses.length === 0) {
  17797. this.calculateInverses();
  17798. } else {
  17799. // handle special case
  17800. if (bones.length !== boneInverses.length) {
  17801. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17802. this.boneInverses = [];
  17803. for (let i = 0, il = this.bones.length; i < il; i++) {
  17804. this.boneInverses.push(new Matrix4());
  17805. }
  17806. }
  17807. }
  17808. }
  17809. calculateInverses() {
  17810. this.boneInverses.length = 0;
  17811. for (let i = 0, il = this.bones.length; i < il; i++) {
  17812. const inverse = new Matrix4();
  17813. if (this.bones[i]) {
  17814. inverse.copy(this.bones[i].matrixWorld).invert();
  17815. }
  17816. this.boneInverses.push(inverse);
  17817. }
  17818. }
  17819. pose() {
  17820. // recover the bind-time world matrices
  17821. for (let i = 0, il = this.bones.length; i < il; i++) {
  17822. const bone = this.bones[i];
  17823. if (bone) {
  17824. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17825. }
  17826. } // compute the local matrices, positions, rotations and scales
  17827. for (let i = 0, il = this.bones.length; i < il; i++) {
  17828. const bone = this.bones[i];
  17829. if (bone) {
  17830. if (bone.parent && bone.parent.isBone) {
  17831. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17832. bone.matrix.multiply(bone.matrixWorld);
  17833. } else {
  17834. bone.matrix.copy(bone.matrixWorld);
  17835. }
  17836. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17837. }
  17838. }
  17839. }
  17840. update() {
  17841. const bones = this.bones;
  17842. const boneInverses = this.boneInverses;
  17843. const boneMatrices = this.boneMatrices;
  17844. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17845. for (let i = 0, il = bones.length; i < il; i++) {
  17846. // compute the offset between the current and the original transform
  17847. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17848. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17849. _offsetMatrix.toArray(boneMatrices, i * 16);
  17850. }
  17851. if (boneTexture !== null) {
  17852. boneTexture.needsUpdate = true;
  17853. }
  17854. }
  17855. clone() {
  17856. return new Skeleton(this.bones, this.boneInverses);
  17857. }
  17858. computeBoneTexture() {
  17859. // layout (1 matrix = 4 pixels)
  17860. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17861. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17862. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17863. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17864. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17865. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17866. size = ceilPowerOfTwo(size);
  17867. size = Math.max(size, 4);
  17868. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17869. boneMatrices.set(this.boneMatrices); // copy current values
  17870. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17871. boneTexture.needsUpdate = true;
  17872. this.boneMatrices = boneMatrices;
  17873. this.boneTexture = boneTexture;
  17874. this.boneTextureSize = size;
  17875. return this;
  17876. }
  17877. getBoneByName(name) {
  17878. for (let i = 0, il = this.bones.length; i < il; i++) {
  17879. const bone = this.bones[i];
  17880. if (bone.name === name) {
  17881. return bone;
  17882. }
  17883. }
  17884. return undefined;
  17885. }
  17886. dispose() {
  17887. if (this.boneTexture !== null) {
  17888. this.boneTexture.dispose();
  17889. this.boneTexture = null;
  17890. }
  17891. }
  17892. fromJSON(json, bones) {
  17893. this.uuid = json.uuid;
  17894. for (let i = 0, l = json.bones.length; i < l; i++) {
  17895. const uuid = json.bones[i];
  17896. let bone = bones[uuid];
  17897. if (bone === undefined) {
  17898. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17899. bone = new Bone();
  17900. }
  17901. this.bones.push(bone);
  17902. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17903. }
  17904. this.init();
  17905. return this;
  17906. }
  17907. toJSON() {
  17908. const data = {
  17909. metadata: {
  17910. version: 4.5,
  17911. type: 'Skeleton',
  17912. generator: 'Skeleton.toJSON'
  17913. },
  17914. bones: [],
  17915. boneInverses: []
  17916. };
  17917. data.uuid = this.uuid;
  17918. const bones = this.bones;
  17919. const boneInverses = this.boneInverses;
  17920. for (let i = 0, l = bones.length; i < l; i++) {
  17921. const bone = bones[i];
  17922. data.bones.push(bone.uuid);
  17923. const boneInverse = boneInverses[i];
  17924. data.boneInverses.push(boneInverse.toArray());
  17925. }
  17926. return data;
  17927. }
  17928. }
  17929. class InstancedBufferAttribute extends BufferAttribute {
  17930. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17931. super(array, itemSize, normalized);
  17932. this.isInstancedBufferAttribute = true;
  17933. this.meshPerAttribute = meshPerAttribute;
  17934. }
  17935. copy(source) {
  17936. super.copy(source);
  17937. this.meshPerAttribute = source.meshPerAttribute;
  17938. return this;
  17939. }
  17940. toJSON() {
  17941. const data = super.toJSON();
  17942. data.meshPerAttribute = this.meshPerAttribute;
  17943. data.isInstancedBufferAttribute = true;
  17944. return data;
  17945. }
  17946. }
  17947. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17948. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17949. const _instanceIntersects = [];
  17950. const _mesh = /*@__PURE__*/new Mesh();
  17951. class InstancedMesh extends Mesh {
  17952. constructor(geometry, material, count) {
  17953. super(geometry, material);
  17954. this.isInstancedMesh = true;
  17955. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17956. this.instanceColor = null;
  17957. this.count = count;
  17958. this.frustumCulled = false;
  17959. }
  17960. copy(source, recursive) {
  17961. super.copy(source, recursive);
  17962. this.instanceMatrix.copy(source.instanceMatrix);
  17963. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17964. this.count = source.count;
  17965. return this;
  17966. }
  17967. getColorAt(index, color) {
  17968. color.fromArray(this.instanceColor.array, index * 3);
  17969. }
  17970. getMatrixAt(index, matrix) {
  17971. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17972. }
  17973. raycast(raycaster, intersects) {
  17974. const matrixWorld = this.matrixWorld;
  17975. const raycastTimes = this.count;
  17976. _mesh.geometry = this.geometry;
  17977. _mesh.material = this.material;
  17978. if (_mesh.material === undefined) return;
  17979. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17980. // calculate the world matrix for each instance
  17981. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17982. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17983. _mesh.matrixWorld = _instanceWorldMatrix;
  17984. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17985. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17986. const intersect = _instanceIntersects[i];
  17987. intersect.instanceId = instanceId;
  17988. intersect.object = this;
  17989. intersects.push(intersect);
  17990. }
  17991. _instanceIntersects.length = 0;
  17992. }
  17993. }
  17994. setColorAt(index, color) {
  17995. if (this.instanceColor === null) {
  17996. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17997. }
  17998. color.toArray(this.instanceColor.array, index * 3);
  17999. }
  18000. setMatrixAt(index, matrix) {
  18001. matrix.toArray(this.instanceMatrix.array, index * 16);
  18002. }
  18003. updateMorphTargets() {}
  18004. dispose() {
  18005. this.dispatchEvent({
  18006. type: 'dispose'
  18007. });
  18008. }
  18009. }
  18010. class LineBasicMaterial extends Material {
  18011. constructor(parameters) {
  18012. super();
  18013. this.isLineBasicMaterial = true;
  18014. this.type = 'LineBasicMaterial';
  18015. this.color = new Color(0xffffff);
  18016. this.linewidth = 1;
  18017. this.linecap = 'round';
  18018. this.linejoin = 'round';
  18019. this.fog = true;
  18020. this.setValues(parameters);
  18021. }
  18022. copy(source) {
  18023. super.copy(source);
  18024. this.color.copy(source.color);
  18025. this.linewidth = source.linewidth;
  18026. this.linecap = source.linecap;
  18027. this.linejoin = source.linejoin;
  18028. this.fog = source.fog;
  18029. return this;
  18030. }
  18031. }
  18032. const _start$1 = /*@__PURE__*/new Vector3();
  18033. const _end$1 = /*@__PURE__*/new Vector3();
  18034. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  18035. const _ray$1 = /*@__PURE__*/new Ray();
  18036. const _sphere$1 = /*@__PURE__*/new Sphere();
  18037. class Line extends Object3D {
  18038. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  18039. super();
  18040. this.isLine = true;
  18041. this.type = 'Line';
  18042. this.geometry = geometry;
  18043. this.material = material;
  18044. this.updateMorphTargets();
  18045. }
  18046. copy(source, recursive) {
  18047. super.copy(source, recursive);
  18048. this.material = source.material;
  18049. this.geometry = source.geometry;
  18050. return this;
  18051. }
  18052. computeLineDistances() {
  18053. const geometry = this.geometry; // we assume non-indexed geometry
  18054. if (geometry.index === null) {
  18055. const positionAttribute = geometry.attributes.position;
  18056. const lineDistances = [0];
  18057. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  18058. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  18059. _end$1.fromBufferAttribute(positionAttribute, i);
  18060. lineDistances[i] = lineDistances[i - 1];
  18061. lineDistances[i] += _start$1.distanceTo(_end$1);
  18062. }
  18063. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18064. } else {
  18065. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18066. }
  18067. return this;
  18068. }
  18069. raycast(raycaster, intersects) {
  18070. const geometry = this.geometry;
  18071. const matrixWorld = this.matrixWorld;
  18072. const threshold = raycaster.params.Line.threshold;
  18073. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18074. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18075. _sphere$1.copy(geometry.boundingSphere);
  18076. _sphere$1.applyMatrix4(matrixWorld);
  18077. _sphere$1.radius += threshold;
  18078. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  18079. _inverseMatrix$1.copy(matrixWorld).invert();
  18080. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  18081. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18082. const localThresholdSq = localThreshold * localThreshold;
  18083. const vStart = new Vector3();
  18084. const vEnd = new Vector3();
  18085. const interSegment = new Vector3();
  18086. const interRay = new Vector3();
  18087. const step = this.isLineSegments ? 2 : 1;
  18088. const index = geometry.index;
  18089. const attributes = geometry.attributes;
  18090. const positionAttribute = attributes.position;
  18091. if (index !== null) {
  18092. const start = Math.max(0, drawRange.start);
  18093. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18094. for (let i = start, l = end - 1; i < l; i += step) {
  18095. const a = index.getX(i);
  18096. const b = index.getX(i + 1);
  18097. vStart.fromBufferAttribute(positionAttribute, a);
  18098. vEnd.fromBufferAttribute(positionAttribute, b);
  18099. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18100. if (distSq > localThresholdSq) continue;
  18101. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18102. const distance = raycaster.ray.origin.distanceTo(interRay);
  18103. if (distance < raycaster.near || distance > raycaster.far) continue;
  18104. intersects.push({
  18105. distance: distance,
  18106. // What do we want? intersection point on the ray or on the segment??
  18107. // point: raycaster.ray.at( distance ),
  18108. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18109. index: i,
  18110. face: null,
  18111. faceIndex: null,
  18112. object: this
  18113. });
  18114. }
  18115. } else {
  18116. const start = Math.max(0, drawRange.start);
  18117. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18118. for (let i = start, l = end - 1; i < l; i += step) {
  18119. vStart.fromBufferAttribute(positionAttribute, i);
  18120. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  18121. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  18122. if (distSq > localThresholdSq) continue;
  18123. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  18124. const distance = raycaster.ray.origin.distanceTo(interRay);
  18125. if (distance < raycaster.near || distance > raycaster.far) continue;
  18126. intersects.push({
  18127. distance: distance,
  18128. // What do we want? intersection point on the ray or on the segment??
  18129. // point: raycaster.ray.at( distance ),
  18130. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  18131. index: i,
  18132. face: null,
  18133. faceIndex: null,
  18134. object: this
  18135. });
  18136. }
  18137. }
  18138. }
  18139. updateMorphTargets() {
  18140. const geometry = this.geometry;
  18141. const morphAttributes = geometry.morphAttributes;
  18142. const keys = Object.keys(morphAttributes);
  18143. if (keys.length > 0) {
  18144. const morphAttribute = morphAttributes[keys[0]];
  18145. if (morphAttribute !== undefined) {
  18146. this.morphTargetInfluences = [];
  18147. this.morphTargetDictionary = {};
  18148. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18149. const name = morphAttribute[m].name || String(m);
  18150. this.morphTargetInfluences.push(0);
  18151. this.morphTargetDictionary[name] = m;
  18152. }
  18153. }
  18154. }
  18155. }
  18156. }
  18157. const _start = /*@__PURE__*/new Vector3();
  18158. const _end = /*@__PURE__*/new Vector3();
  18159. class LineSegments extends Line {
  18160. constructor(geometry, material) {
  18161. super(geometry, material);
  18162. this.isLineSegments = true;
  18163. this.type = 'LineSegments';
  18164. }
  18165. computeLineDistances() {
  18166. const geometry = this.geometry; // we assume non-indexed geometry
  18167. if (geometry.index === null) {
  18168. const positionAttribute = geometry.attributes.position;
  18169. const lineDistances = [];
  18170. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  18171. _start.fromBufferAttribute(positionAttribute, i);
  18172. _end.fromBufferAttribute(positionAttribute, i + 1);
  18173. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  18174. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  18175. }
  18176. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  18177. } else {
  18178. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  18179. }
  18180. return this;
  18181. }
  18182. }
  18183. class LineLoop extends Line {
  18184. constructor(geometry, material) {
  18185. super(geometry, material);
  18186. this.isLineLoop = true;
  18187. this.type = 'LineLoop';
  18188. }
  18189. }
  18190. class PointsMaterial extends Material {
  18191. constructor(parameters) {
  18192. super();
  18193. this.isPointsMaterial = true;
  18194. this.type = 'PointsMaterial';
  18195. this.color = new Color(0xffffff);
  18196. this.map = null;
  18197. this.alphaMap = null;
  18198. this.size = 1;
  18199. this.sizeAttenuation = true;
  18200. this.fog = true;
  18201. this.setValues(parameters);
  18202. }
  18203. copy(source) {
  18204. super.copy(source);
  18205. this.color.copy(source.color);
  18206. this.map = source.map;
  18207. this.alphaMap = source.alphaMap;
  18208. this.size = source.size;
  18209. this.sizeAttenuation = source.sizeAttenuation;
  18210. this.fog = source.fog;
  18211. return this;
  18212. }
  18213. }
  18214. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  18215. const _ray = /*@__PURE__*/new Ray();
  18216. const _sphere = /*@__PURE__*/new Sphere();
  18217. const _position$2 = /*@__PURE__*/new Vector3();
  18218. class Points extends Object3D {
  18219. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  18220. super();
  18221. this.isPoints = true;
  18222. this.type = 'Points';
  18223. this.geometry = geometry;
  18224. this.material = material;
  18225. this.updateMorphTargets();
  18226. }
  18227. copy(source, recursive) {
  18228. super.copy(source, recursive);
  18229. this.material = source.material;
  18230. this.geometry = source.geometry;
  18231. return this;
  18232. }
  18233. raycast(raycaster, intersects) {
  18234. const geometry = this.geometry;
  18235. const matrixWorld = this.matrixWorld;
  18236. const threshold = raycaster.params.Points.threshold;
  18237. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  18238. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  18239. _sphere.copy(geometry.boundingSphere);
  18240. _sphere.applyMatrix4(matrixWorld);
  18241. _sphere.radius += threshold;
  18242. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  18243. _inverseMatrix.copy(matrixWorld).invert();
  18244. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  18245. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  18246. const localThresholdSq = localThreshold * localThreshold;
  18247. const index = geometry.index;
  18248. const attributes = geometry.attributes;
  18249. const positionAttribute = attributes.position;
  18250. if (index !== null) {
  18251. const start = Math.max(0, drawRange.start);
  18252. const end = Math.min(index.count, drawRange.start + drawRange.count);
  18253. for (let i = start, il = end; i < il; i++) {
  18254. const a = index.getX(i);
  18255. _position$2.fromBufferAttribute(positionAttribute, a);
  18256. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18257. }
  18258. } else {
  18259. const start = Math.max(0, drawRange.start);
  18260. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  18261. for (let i = start, l = end; i < l; i++) {
  18262. _position$2.fromBufferAttribute(positionAttribute, i);
  18263. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  18264. }
  18265. }
  18266. }
  18267. updateMorphTargets() {
  18268. const geometry = this.geometry;
  18269. const morphAttributes = geometry.morphAttributes;
  18270. const keys = Object.keys(morphAttributes);
  18271. if (keys.length > 0) {
  18272. const morphAttribute = morphAttributes[keys[0]];
  18273. if (morphAttribute !== undefined) {
  18274. this.morphTargetInfluences = [];
  18275. this.morphTargetDictionary = {};
  18276. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  18277. const name = morphAttribute[m].name || String(m);
  18278. this.morphTargetInfluences.push(0);
  18279. this.morphTargetDictionary[name] = m;
  18280. }
  18281. }
  18282. }
  18283. }
  18284. }
  18285. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  18286. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  18287. if (rayPointDistanceSq < localThresholdSq) {
  18288. const intersectPoint = new Vector3();
  18289. _ray.closestPointToPoint(point, intersectPoint);
  18290. intersectPoint.applyMatrix4(matrixWorld);
  18291. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  18292. if (distance < raycaster.near || distance > raycaster.far) return;
  18293. intersects.push({
  18294. distance: distance,
  18295. distanceToRay: Math.sqrt(rayPointDistanceSq),
  18296. point: intersectPoint,
  18297. index: index,
  18298. face: null,
  18299. object: object
  18300. });
  18301. }
  18302. }
  18303. class VideoTexture extends Texture {
  18304. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18305. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18306. this.isVideoTexture = true;
  18307. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18308. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18309. this.generateMipmaps = false;
  18310. const scope = this;
  18311. function updateVideo() {
  18312. scope.needsUpdate = true;
  18313. video.requestVideoFrameCallback(updateVideo);
  18314. }
  18315. if ('requestVideoFrameCallback' in video) {
  18316. video.requestVideoFrameCallback(updateVideo);
  18317. }
  18318. }
  18319. clone() {
  18320. return new this.constructor(this.image).copy(this);
  18321. }
  18322. update() {
  18323. const video = this.image;
  18324. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18325. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18326. this.needsUpdate = true;
  18327. }
  18328. }
  18329. }
  18330. class FramebufferTexture extends Texture {
  18331. constructor(width, height, format) {
  18332. super({
  18333. width,
  18334. height
  18335. });
  18336. this.isFramebufferTexture = true;
  18337. this.format = format;
  18338. this.magFilter = NearestFilter;
  18339. this.minFilter = NearestFilter;
  18340. this.generateMipmaps = false;
  18341. this.needsUpdate = true;
  18342. }
  18343. }
  18344. class CompressedTexture extends Texture {
  18345. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18346. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18347. this.isCompressedTexture = true;
  18348. this.image = {
  18349. width: width,
  18350. height: height
  18351. };
  18352. this.mipmaps = mipmaps; // no flipping for cube textures
  18353. // (also flipping doesn't work for compressed textures )
  18354. this.flipY = false; // can't generate mipmaps for compressed textures
  18355. // mips must be embedded in DDS files
  18356. this.generateMipmaps = false;
  18357. }
  18358. }
  18359. class CanvasTexture extends Texture {
  18360. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18361. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18362. this.isCanvasTexture = true;
  18363. this.needsUpdate = true;
  18364. }
  18365. }
  18366. /**
  18367. * Extensible curve object.
  18368. *
  18369. * Some common of curve methods:
  18370. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18371. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18372. * .getPoints(), .getSpacedPoints()
  18373. * .getLength()
  18374. * .updateArcLengths()
  18375. *
  18376. * This following curves inherit from THREE.Curve:
  18377. *
  18378. * -- 2D curves --
  18379. * THREE.ArcCurve
  18380. * THREE.CubicBezierCurve
  18381. * THREE.EllipseCurve
  18382. * THREE.LineCurve
  18383. * THREE.QuadraticBezierCurve
  18384. * THREE.SplineCurve
  18385. *
  18386. * -- 3D curves --
  18387. * THREE.CatmullRomCurve3
  18388. * THREE.CubicBezierCurve3
  18389. * THREE.LineCurve3
  18390. * THREE.QuadraticBezierCurve3
  18391. *
  18392. * A series of curves can be represented as a THREE.CurvePath.
  18393. *
  18394. **/
  18395. class Curve {
  18396. constructor() {
  18397. this.type = 'Curve';
  18398. this.arcLengthDivisions = 200;
  18399. } // Virtual base class method to overwrite and implement in subclasses
  18400. // - t [0 .. 1]
  18401. getPoint() {
  18402. console.warn('THREE.Curve: .getPoint() not implemented.');
  18403. return null;
  18404. } // Get point at relative position in curve according to arc length
  18405. // - u [0 .. 1]
  18406. getPointAt(u, optionalTarget) {
  18407. const t = this.getUtoTmapping(u);
  18408. return this.getPoint(t, optionalTarget);
  18409. } // Get sequence of points using getPoint( t )
  18410. getPoints(divisions = 5) {
  18411. const points = [];
  18412. for (let d = 0; d <= divisions; d++) {
  18413. points.push(this.getPoint(d / divisions));
  18414. }
  18415. return points;
  18416. } // Get sequence of points using getPointAt( u )
  18417. getSpacedPoints(divisions = 5) {
  18418. const points = [];
  18419. for (let d = 0; d <= divisions; d++) {
  18420. points.push(this.getPointAt(d / divisions));
  18421. }
  18422. return points;
  18423. } // Get total curve arc length
  18424. getLength() {
  18425. const lengths = this.getLengths();
  18426. return lengths[lengths.length - 1];
  18427. } // Get list of cumulative segment lengths
  18428. getLengths(divisions = this.arcLengthDivisions) {
  18429. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18430. return this.cacheArcLengths;
  18431. }
  18432. this.needsUpdate = false;
  18433. const cache = [];
  18434. let current,
  18435. last = this.getPoint(0);
  18436. let sum = 0;
  18437. cache.push(0);
  18438. for (let p = 1; p <= divisions; p++) {
  18439. current = this.getPoint(p / divisions);
  18440. sum += current.distanceTo(last);
  18441. cache.push(sum);
  18442. last = current;
  18443. }
  18444. this.cacheArcLengths = cache;
  18445. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18446. }
  18447. updateArcLengths() {
  18448. this.needsUpdate = true;
  18449. this.getLengths();
  18450. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18451. getUtoTmapping(u, distance) {
  18452. const arcLengths = this.getLengths();
  18453. let i = 0;
  18454. const il = arcLengths.length;
  18455. let targetArcLength; // The targeted u distance value to get
  18456. if (distance) {
  18457. targetArcLength = distance;
  18458. } else {
  18459. targetArcLength = u * arcLengths[il - 1];
  18460. } // binary search for the index with largest value smaller than target u distance
  18461. let low = 0,
  18462. high = il - 1,
  18463. comparison;
  18464. while (low <= high) {
  18465. i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  18466. comparison = arcLengths[i] - targetArcLength;
  18467. if (comparison < 0) {
  18468. low = i + 1;
  18469. } else if (comparison > 0) {
  18470. high = i - 1;
  18471. } else {
  18472. high = i;
  18473. break; // DONE
  18474. }
  18475. }
  18476. i = high;
  18477. if (arcLengths[i] === targetArcLength) {
  18478. return i / (il - 1);
  18479. } // we could get finer grain at lengths, or use simple interpolation between two points
  18480. const lengthBefore = arcLengths[i];
  18481. const lengthAfter = arcLengths[i + 1];
  18482. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18483. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18484. const t = (i + segmentFraction) / (il - 1);
  18485. return t;
  18486. } // Returns a unit vector tangent at t
  18487. // In case any sub curve does not implement its tangent derivation,
  18488. // 2 points a small delta apart will be used to find its gradient
  18489. // which seems to give a reasonable approximation
  18490. getTangent(t, optionalTarget) {
  18491. const delta = 0.0001;
  18492. let t1 = t - delta;
  18493. let t2 = t + delta; // Capping in case of danger
  18494. if (t1 < 0) t1 = 0;
  18495. if (t2 > 1) t2 = 1;
  18496. const pt1 = this.getPoint(t1);
  18497. const pt2 = this.getPoint(t2);
  18498. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18499. tangent.copy(pt2).sub(pt1).normalize();
  18500. return tangent;
  18501. }
  18502. getTangentAt(u, optionalTarget) {
  18503. const t = this.getUtoTmapping(u);
  18504. return this.getTangent(t, optionalTarget);
  18505. }
  18506. computeFrenetFrames(segments, closed) {
  18507. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18508. const normal = new Vector3();
  18509. const tangents = [];
  18510. const normals = [];
  18511. const binormals = [];
  18512. const vec = new Vector3();
  18513. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18514. for (let i = 0; i <= segments; i++) {
  18515. const u = i / segments;
  18516. tangents[i] = this.getTangentAt(u, new Vector3());
  18517. } // select an initial normal vector perpendicular to the first tangent vector,
  18518. // and in the direction of the minimum tangent xyz component
  18519. normals[0] = new Vector3();
  18520. binormals[0] = new Vector3();
  18521. let min = Number.MAX_VALUE;
  18522. const tx = Math.abs(tangents[0].x);
  18523. const ty = Math.abs(tangents[0].y);
  18524. const tz = Math.abs(tangents[0].z);
  18525. if (tx <= min) {
  18526. min = tx;
  18527. normal.set(1, 0, 0);
  18528. }
  18529. if (ty <= min) {
  18530. min = ty;
  18531. normal.set(0, 1, 0);
  18532. }
  18533. if (tz <= min) {
  18534. normal.set(0, 0, 1);
  18535. }
  18536. vec.crossVectors(tangents[0], normal).normalize();
  18537. normals[0].crossVectors(tangents[0], vec);
  18538. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18539. for (let i = 1; i <= segments; i++) {
  18540. normals[i] = normals[i - 1].clone();
  18541. binormals[i] = binormals[i - 1].clone();
  18542. vec.crossVectors(tangents[i - 1], tangents[i]);
  18543. if (vec.length() > Number.EPSILON) {
  18544. vec.normalize();
  18545. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18546. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18547. }
  18548. binormals[i].crossVectors(tangents[i], normals[i]);
  18549. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18550. if (closed === true) {
  18551. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18552. theta /= segments;
  18553. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18554. theta = -theta;
  18555. }
  18556. for (let i = 1; i <= segments; i++) {
  18557. // twist a little...
  18558. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18559. binormals[i].crossVectors(tangents[i], normals[i]);
  18560. }
  18561. }
  18562. return {
  18563. tangents: tangents,
  18564. normals: normals,
  18565. binormals: binormals
  18566. };
  18567. }
  18568. clone() {
  18569. return new this.constructor().copy(this);
  18570. }
  18571. copy(source) {
  18572. this.arcLengthDivisions = source.arcLengthDivisions;
  18573. return this;
  18574. }
  18575. toJSON() {
  18576. const data = {
  18577. metadata: {
  18578. version: 4.5,
  18579. type: 'Curve',
  18580. generator: 'Curve.toJSON'
  18581. }
  18582. };
  18583. data.arcLengthDivisions = this.arcLengthDivisions;
  18584. data.type = this.type;
  18585. return data;
  18586. }
  18587. fromJSON(json) {
  18588. this.arcLengthDivisions = json.arcLengthDivisions;
  18589. return this;
  18590. }
  18591. }
  18592. class EllipseCurve extends Curve {
  18593. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18594. super();
  18595. this.isEllipseCurve = true;
  18596. this.type = 'EllipseCurve';
  18597. this.aX = aX;
  18598. this.aY = aY;
  18599. this.xRadius = xRadius;
  18600. this.yRadius = yRadius;
  18601. this.aStartAngle = aStartAngle;
  18602. this.aEndAngle = aEndAngle;
  18603. this.aClockwise = aClockwise;
  18604. this.aRotation = aRotation;
  18605. }
  18606. getPoint(t, optionalTarget) {
  18607. const point = optionalTarget || new Vector2();
  18608. const twoPi = Math.PI * 2;
  18609. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18610. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18611. while (deltaAngle < 0) deltaAngle += twoPi;
  18612. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18613. if (deltaAngle < Number.EPSILON) {
  18614. if (samePoints) {
  18615. deltaAngle = 0;
  18616. } else {
  18617. deltaAngle = twoPi;
  18618. }
  18619. }
  18620. if (this.aClockwise === true && !samePoints) {
  18621. if (deltaAngle === twoPi) {
  18622. deltaAngle = -twoPi;
  18623. } else {
  18624. deltaAngle = deltaAngle - twoPi;
  18625. }
  18626. }
  18627. const angle = this.aStartAngle + t * deltaAngle;
  18628. let x = this.aX + this.xRadius * Math.cos(angle);
  18629. let y = this.aY + this.yRadius * Math.sin(angle);
  18630. if (this.aRotation !== 0) {
  18631. const cos = Math.cos(this.aRotation);
  18632. const sin = Math.sin(this.aRotation);
  18633. const tx = x - this.aX;
  18634. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18635. x = tx * cos - ty * sin + this.aX;
  18636. y = tx * sin + ty * cos + this.aY;
  18637. }
  18638. return point.set(x, y);
  18639. }
  18640. copy(source) {
  18641. super.copy(source);
  18642. this.aX = source.aX;
  18643. this.aY = source.aY;
  18644. this.xRadius = source.xRadius;
  18645. this.yRadius = source.yRadius;
  18646. this.aStartAngle = source.aStartAngle;
  18647. this.aEndAngle = source.aEndAngle;
  18648. this.aClockwise = source.aClockwise;
  18649. this.aRotation = source.aRotation;
  18650. return this;
  18651. }
  18652. toJSON() {
  18653. const data = super.toJSON();
  18654. data.aX = this.aX;
  18655. data.aY = this.aY;
  18656. data.xRadius = this.xRadius;
  18657. data.yRadius = this.yRadius;
  18658. data.aStartAngle = this.aStartAngle;
  18659. data.aEndAngle = this.aEndAngle;
  18660. data.aClockwise = this.aClockwise;
  18661. data.aRotation = this.aRotation;
  18662. return data;
  18663. }
  18664. fromJSON(json) {
  18665. super.fromJSON(json);
  18666. this.aX = json.aX;
  18667. this.aY = json.aY;
  18668. this.xRadius = json.xRadius;
  18669. this.yRadius = json.yRadius;
  18670. this.aStartAngle = json.aStartAngle;
  18671. this.aEndAngle = json.aEndAngle;
  18672. this.aClockwise = json.aClockwise;
  18673. this.aRotation = json.aRotation;
  18674. return this;
  18675. }
  18676. }
  18677. class ArcCurve extends EllipseCurve {
  18678. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18679. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18680. this.isArcCurve = true;
  18681. this.type = 'ArcCurve';
  18682. }
  18683. }
  18684. /**
  18685. * Centripetal CatmullRom Curve - which is useful for avoiding
  18686. * cusps and self-intersections in non-uniform catmull rom curves.
  18687. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18688. *
  18689. * curve.type accepts centripetal(default), chordal and catmullrom
  18690. * curve.tension is used for catmullrom which defaults to 0.5
  18691. */
  18692. /*
  18693. Based on an optimized c++ solution in
  18694. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18695. - http://ideone.com/NoEbVM
  18696. This CubicPoly class could be used for reusing some variables and calculations,
  18697. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18698. which can be placed in CurveUtils.
  18699. */
  18700. function CubicPoly() {
  18701. let c0 = 0,
  18702. c1 = 0,
  18703. c2 = 0,
  18704. c3 = 0;
  18705. /*
  18706. * Compute coefficients for a cubic polynomial
  18707. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18708. * such that
  18709. * p(0) = x0, p(1) = x1
  18710. * and
  18711. * p'(0) = t0, p'(1) = t1.
  18712. */
  18713. function init(x0, x1, t0, t1) {
  18714. c0 = x0;
  18715. c1 = t0;
  18716. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18717. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18718. }
  18719. return {
  18720. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18721. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18722. },
  18723. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18724. // compute tangents when parameterized in [t1,t2]
  18725. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18726. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18727. t1 *= dt1;
  18728. t2 *= dt1;
  18729. init(x1, x2, t1, t2);
  18730. },
  18731. calc: function (t) {
  18732. const t2 = t * t;
  18733. const t3 = t2 * t;
  18734. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18735. }
  18736. };
  18737. } //
  18738. const tmp = /*@__PURE__*/new Vector3();
  18739. const px = /*@__PURE__*/new CubicPoly();
  18740. const py = /*@__PURE__*/new CubicPoly();
  18741. const pz = /*@__PURE__*/new CubicPoly();
  18742. class CatmullRomCurve3 extends Curve {
  18743. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18744. super();
  18745. this.isCatmullRomCurve3 = true;
  18746. this.type = 'CatmullRomCurve3';
  18747. this.points = points;
  18748. this.closed = closed;
  18749. this.curveType = curveType;
  18750. this.tension = tension;
  18751. }
  18752. getPoint(t, optionalTarget = new Vector3()) {
  18753. const point = optionalTarget;
  18754. const points = this.points;
  18755. const l = points.length;
  18756. const p = (l - (this.closed ? 0 : 1)) * t;
  18757. let intPoint = Math.floor(p);
  18758. let weight = p - intPoint;
  18759. if (this.closed) {
  18760. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18761. } else if (weight === 0 && intPoint === l - 1) {
  18762. intPoint = l - 2;
  18763. weight = 1;
  18764. }
  18765. let p0, p3; // 4 points (p1 & p2 defined below)
  18766. if (this.closed || intPoint > 0) {
  18767. p0 = points[(intPoint - 1) % l];
  18768. } else {
  18769. // extrapolate first point
  18770. tmp.subVectors(points[0], points[1]).add(points[0]);
  18771. p0 = tmp;
  18772. }
  18773. const p1 = points[intPoint % l];
  18774. const p2 = points[(intPoint + 1) % l];
  18775. if (this.closed || intPoint + 2 < l) {
  18776. p3 = points[(intPoint + 2) % l];
  18777. } else {
  18778. // extrapolate last point
  18779. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18780. p3 = tmp;
  18781. }
  18782. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18783. // init Centripetal / Chordal Catmull-Rom
  18784. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18785. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18786. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18787. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18788. if (dt1 < 1e-4) dt1 = 1.0;
  18789. if (dt0 < 1e-4) dt0 = dt1;
  18790. if (dt2 < 1e-4) dt2 = dt1;
  18791. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18792. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18793. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18794. } else if (this.curveType === 'catmullrom') {
  18795. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18796. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18797. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18798. }
  18799. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18800. return point;
  18801. }
  18802. copy(source) {
  18803. super.copy(source);
  18804. this.points = [];
  18805. for (let i = 0, l = source.points.length; i < l; i++) {
  18806. const point = source.points[i];
  18807. this.points.push(point.clone());
  18808. }
  18809. this.closed = source.closed;
  18810. this.curveType = source.curveType;
  18811. this.tension = source.tension;
  18812. return this;
  18813. }
  18814. toJSON() {
  18815. const data = super.toJSON();
  18816. data.points = [];
  18817. for (let i = 0, l = this.points.length; i < l; i++) {
  18818. const point = this.points[i];
  18819. data.points.push(point.toArray());
  18820. }
  18821. data.closed = this.closed;
  18822. data.curveType = this.curveType;
  18823. data.tension = this.tension;
  18824. return data;
  18825. }
  18826. fromJSON(json) {
  18827. super.fromJSON(json);
  18828. this.points = [];
  18829. for (let i = 0, l = json.points.length; i < l; i++) {
  18830. const point = json.points[i];
  18831. this.points.push(new Vector3().fromArray(point));
  18832. }
  18833. this.closed = json.closed;
  18834. this.curveType = json.curveType;
  18835. this.tension = json.tension;
  18836. return this;
  18837. }
  18838. }
  18839. /**
  18840. * Bezier Curves formulas obtained from
  18841. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18842. */
  18843. function CatmullRom(t, p0, p1, p2, p3) {
  18844. const v0 = (p2 - p0) * 0.5;
  18845. const v1 = (p3 - p1) * 0.5;
  18846. const t2 = t * t;
  18847. const t3 = t * t2;
  18848. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18849. } //
  18850. function QuadraticBezierP0(t, p) {
  18851. const k = 1 - t;
  18852. return k * k * p;
  18853. }
  18854. function QuadraticBezierP1(t, p) {
  18855. return 2 * (1 - t) * t * p;
  18856. }
  18857. function QuadraticBezierP2(t, p) {
  18858. return t * t * p;
  18859. }
  18860. function QuadraticBezier(t, p0, p1, p2) {
  18861. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18862. } //
  18863. function CubicBezierP0(t, p) {
  18864. const k = 1 - t;
  18865. return k * k * k * p;
  18866. }
  18867. function CubicBezierP1(t, p) {
  18868. const k = 1 - t;
  18869. return 3 * k * k * t * p;
  18870. }
  18871. function CubicBezierP2(t, p) {
  18872. return 3 * (1 - t) * t * t * p;
  18873. }
  18874. function CubicBezierP3(t, p) {
  18875. return t * t * t * p;
  18876. }
  18877. function CubicBezier(t, p0, p1, p2, p3) {
  18878. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18879. }
  18880. class CubicBezierCurve extends Curve {
  18881. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18882. super();
  18883. this.isCubicBezierCurve = true;
  18884. this.type = 'CubicBezierCurve';
  18885. this.v0 = v0;
  18886. this.v1 = v1;
  18887. this.v2 = v2;
  18888. this.v3 = v3;
  18889. }
  18890. getPoint(t, optionalTarget = new Vector2()) {
  18891. const point = optionalTarget;
  18892. const v0 = this.v0,
  18893. v1 = this.v1,
  18894. v2 = this.v2,
  18895. v3 = this.v3;
  18896. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18897. return point;
  18898. }
  18899. copy(source) {
  18900. super.copy(source);
  18901. this.v0.copy(source.v0);
  18902. this.v1.copy(source.v1);
  18903. this.v2.copy(source.v2);
  18904. this.v3.copy(source.v3);
  18905. return this;
  18906. }
  18907. toJSON() {
  18908. const data = super.toJSON();
  18909. data.v0 = this.v0.toArray();
  18910. data.v1 = this.v1.toArray();
  18911. data.v2 = this.v2.toArray();
  18912. data.v3 = this.v3.toArray();
  18913. return data;
  18914. }
  18915. fromJSON(json) {
  18916. super.fromJSON(json);
  18917. this.v0.fromArray(json.v0);
  18918. this.v1.fromArray(json.v1);
  18919. this.v2.fromArray(json.v2);
  18920. this.v3.fromArray(json.v3);
  18921. return this;
  18922. }
  18923. }
  18924. class CubicBezierCurve3 extends Curve {
  18925. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18926. super();
  18927. this.isCubicBezierCurve3 = true;
  18928. this.type = 'CubicBezierCurve3';
  18929. this.v0 = v0;
  18930. this.v1 = v1;
  18931. this.v2 = v2;
  18932. this.v3 = v3;
  18933. }
  18934. getPoint(t, optionalTarget = new Vector3()) {
  18935. const point = optionalTarget;
  18936. const v0 = this.v0,
  18937. v1 = this.v1,
  18938. v2 = this.v2,
  18939. v3 = this.v3;
  18940. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  18941. return point;
  18942. }
  18943. copy(source) {
  18944. super.copy(source);
  18945. this.v0.copy(source.v0);
  18946. this.v1.copy(source.v1);
  18947. this.v2.copy(source.v2);
  18948. this.v3.copy(source.v3);
  18949. return this;
  18950. }
  18951. toJSON() {
  18952. const data = super.toJSON();
  18953. data.v0 = this.v0.toArray();
  18954. data.v1 = this.v1.toArray();
  18955. data.v2 = this.v2.toArray();
  18956. data.v3 = this.v3.toArray();
  18957. return data;
  18958. }
  18959. fromJSON(json) {
  18960. super.fromJSON(json);
  18961. this.v0.fromArray(json.v0);
  18962. this.v1.fromArray(json.v1);
  18963. this.v2.fromArray(json.v2);
  18964. this.v3.fromArray(json.v3);
  18965. return this;
  18966. }
  18967. }
  18968. class LineCurve extends Curve {
  18969. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18970. super();
  18971. this.isLineCurve = true;
  18972. this.type = 'LineCurve';
  18973. this.v1 = v1;
  18974. this.v2 = v2;
  18975. }
  18976. getPoint(t, optionalTarget = new Vector2()) {
  18977. const point = optionalTarget;
  18978. if (t === 1) {
  18979. point.copy(this.v2);
  18980. } else {
  18981. point.copy(this.v2).sub(this.v1);
  18982. point.multiplyScalar(t).add(this.v1);
  18983. }
  18984. return point;
  18985. } // Line curve is linear, so we can overwrite default getPointAt
  18986. getPointAt(u, optionalTarget) {
  18987. return this.getPoint(u, optionalTarget);
  18988. }
  18989. getTangent(t, optionalTarget) {
  18990. const tangent = optionalTarget || new Vector2();
  18991. tangent.copy(this.v2).sub(this.v1).normalize();
  18992. return tangent;
  18993. }
  18994. copy(source) {
  18995. super.copy(source);
  18996. this.v1.copy(source.v1);
  18997. this.v2.copy(source.v2);
  18998. return this;
  18999. }
  19000. toJSON() {
  19001. const data = super.toJSON();
  19002. data.v1 = this.v1.toArray();
  19003. data.v2 = this.v2.toArray();
  19004. return data;
  19005. }
  19006. fromJSON(json) {
  19007. super.fromJSON(json);
  19008. this.v1.fromArray(json.v1);
  19009. this.v2.fromArray(json.v2);
  19010. return this;
  19011. }
  19012. }
  19013. class LineCurve3 extends Curve {
  19014. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  19015. super();
  19016. this.isLineCurve3 = true;
  19017. this.type = 'LineCurve3';
  19018. this.v1 = v1;
  19019. this.v2 = v2;
  19020. }
  19021. getPoint(t, optionalTarget = new Vector3()) {
  19022. const point = optionalTarget;
  19023. if (t === 1) {
  19024. point.copy(this.v2);
  19025. } else {
  19026. point.copy(this.v2).sub(this.v1);
  19027. point.multiplyScalar(t).add(this.v1);
  19028. }
  19029. return point;
  19030. } // Line curve is linear, so we can overwrite default getPointAt
  19031. getPointAt(u, optionalTarget) {
  19032. return this.getPoint(u, optionalTarget);
  19033. }
  19034. copy(source) {
  19035. super.copy(source);
  19036. this.v1.copy(source.v1);
  19037. this.v2.copy(source.v2);
  19038. return this;
  19039. }
  19040. toJSON() {
  19041. const data = super.toJSON();
  19042. data.v1 = this.v1.toArray();
  19043. data.v2 = this.v2.toArray();
  19044. return data;
  19045. }
  19046. fromJSON(json) {
  19047. super.fromJSON(json);
  19048. this.v1.fromArray(json.v1);
  19049. this.v2.fromArray(json.v2);
  19050. return this;
  19051. }
  19052. }
  19053. class QuadraticBezierCurve extends Curve {
  19054. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19055. super();
  19056. this.isQuadraticBezierCurve = true;
  19057. this.type = 'QuadraticBezierCurve';
  19058. this.v0 = v0;
  19059. this.v1 = v1;
  19060. this.v2 = v2;
  19061. }
  19062. getPoint(t, optionalTarget = new Vector2()) {
  19063. const point = optionalTarget;
  19064. const v0 = this.v0,
  19065. v1 = this.v1,
  19066. v2 = this.v2;
  19067. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19068. return point;
  19069. }
  19070. copy(source) {
  19071. super.copy(source);
  19072. this.v0.copy(source.v0);
  19073. this.v1.copy(source.v1);
  19074. this.v2.copy(source.v2);
  19075. return this;
  19076. }
  19077. toJSON() {
  19078. const data = super.toJSON();
  19079. data.v0 = this.v0.toArray();
  19080. data.v1 = this.v1.toArray();
  19081. data.v2 = this.v2.toArray();
  19082. return data;
  19083. }
  19084. fromJSON(json) {
  19085. super.fromJSON(json);
  19086. this.v0.fromArray(json.v0);
  19087. this.v1.fromArray(json.v1);
  19088. this.v2.fromArray(json.v2);
  19089. return this;
  19090. }
  19091. }
  19092. class QuadraticBezierCurve3 extends Curve {
  19093. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19094. super();
  19095. this.isQuadraticBezierCurve3 = true;
  19096. this.type = 'QuadraticBezierCurve3';
  19097. this.v0 = v0;
  19098. this.v1 = v1;
  19099. this.v2 = v2;
  19100. }
  19101. getPoint(t, optionalTarget = new Vector3()) {
  19102. const point = optionalTarget;
  19103. const v0 = this.v0,
  19104. v1 = this.v1,
  19105. v2 = this.v2;
  19106. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  19107. return point;
  19108. }
  19109. copy(source) {
  19110. super.copy(source);
  19111. this.v0.copy(source.v0);
  19112. this.v1.copy(source.v1);
  19113. this.v2.copy(source.v2);
  19114. return this;
  19115. }
  19116. toJSON() {
  19117. const data = super.toJSON();
  19118. data.v0 = this.v0.toArray();
  19119. data.v1 = this.v1.toArray();
  19120. data.v2 = this.v2.toArray();
  19121. return data;
  19122. }
  19123. fromJSON(json) {
  19124. super.fromJSON(json);
  19125. this.v0.fromArray(json.v0);
  19126. this.v1.fromArray(json.v1);
  19127. this.v2.fromArray(json.v2);
  19128. return this;
  19129. }
  19130. }
  19131. class SplineCurve extends Curve {
  19132. constructor(points = []) {
  19133. super();
  19134. this.isSplineCurve = true;
  19135. this.type = 'SplineCurve';
  19136. this.points = points;
  19137. }
  19138. getPoint(t, optionalTarget = new Vector2()) {
  19139. const point = optionalTarget;
  19140. const points = this.points;
  19141. const p = (points.length - 1) * t;
  19142. const intPoint = Math.floor(p);
  19143. const weight = p - intPoint;
  19144. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19145. const p1 = points[intPoint];
  19146. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19147. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19148. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19149. return point;
  19150. }
  19151. copy(source) {
  19152. super.copy(source);
  19153. this.points = [];
  19154. for (let i = 0, l = source.points.length; i < l; i++) {
  19155. const point = source.points[i];
  19156. this.points.push(point.clone());
  19157. }
  19158. return this;
  19159. }
  19160. toJSON() {
  19161. const data = super.toJSON();
  19162. data.points = [];
  19163. for (let i = 0, l = this.points.length; i < l; i++) {
  19164. const point = this.points[i];
  19165. data.points.push(point.toArray());
  19166. }
  19167. return data;
  19168. }
  19169. fromJSON(json) {
  19170. super.fromJSON(json);
  19171. this.points = [];
  19172. for (let i = 0, l = json.points.length; i < l; i++) {
  19173. const point = json.points[i];
  19174. this.points.push(new Vector2().fromArray(point));
  19175. }
  19176. return this;
  19177. }
  19178. }
  19179. var Curves = /*#__PURE__*/Object.freeze({
  19180. __proto__: null,
  19181. ArcCurve: ArcCurve,
  19182. CatmullRomCurve3: CatmullRomCurve3,
  19183. CubicBezierCurve: CubicBezierCurve,
  19184. CubicBezierCurve3: CubicBezierCurve3,
  19185. EllipseCurve: EllipseCurve,
  19186. LineCurve: LineCurve,
  19187. LineCurve3: LineCurve3,
  19188. QuadraticBezierCurve: QuadraticBezierCurve,
  19189. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19190. SplineCurve: SplineCurve
  19191. });
  19192. /**************************************************************
  19193. * Curved Path - a curve path is simply a array of connected
  19194. * curves, but retains the api of a curve
  19195. **************************************************************/
  19196. class CurvePath extends Curve {
  19197. constructor() {
  19198. super();
  19199. this.type = 'CurvePath';
  19200. this.curves = [];
  19201. this.autoClose = false; // Automatically closes the path
  19202. }
  19203. add(curve) {
  19204. this.curves.push(curve);
  19205. }
  19206. closePath() {
  19207. // Add a line curve if start and end of lines are not connected
  19208. const startPoint = this.curves[0].getPoint(0);
  19209. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19210. if (!startPoint.equals(endPoint)) {
  19211. this.curves.push(new LineCurve(endPoint, startPoint));
  19212. }
  19213. } // To get accurate point with reference to
  19214. // entire path distance at time t,
  19215. // following has to be done:
  19216. // 1. Length of each sub path have to be known
  19217. // 2. Locate and identify type of curve
  19218. // 3. Get t for the curve
  19219. // 4. Return curve.getPointAt(t')
  19220. getPoint(t, optionalTarget) {
  19221. const d = t * this.getLength();
  19222. const curveLengths = this.getCurveLengths();
  19223. let i = 0; // To think about boundaries points.
  19224. while (i < curveLengths.length) {
  19225. if (curveLengths[i] >= d) {
  19226. const diff = curveLengths[i] - d;
  19227. const curve = this.curves[i];
  19228. const segmentLength = curve.getLength();
  19229. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19230. return curve.getPointAt(u, optionalTarget);
  19231. }
  19232. i++;
  19233. }
  19234. return null; // loop where sum != 0, sum > d , sum+1 <d
  19235. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19236. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19237. // getPoint() depends on getLength
  19238. getLength() {
  19239. const lens = this.getCurveLengths();
  19240. return lens[lens.length - 1];
  19241. } // cacheLengths must be recalculated.
  19242. updateArcLengths() {
  19243. this.needsUpdate = true;
  19244. this.cacheLengths = null;
  19245. this.getCurveLengths();
  19246. } // Compute lengths and cache them
  19247. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19248. getCurveLengths() {
  19249. // We use cache values if curves and cache array are same length
  19250. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19251. return this.cacheLengths;
  19252. } // Get length of sub-curve
  19253. // Push sums into cached array
  19254. const lengths = [];
  19255. let sums = 0;
  19256. for (let i = 0, l = this.curves.length; i < l; i++) {
  19257. sums += this.curves[i].getLength();
  19258. lengths.push(sums);
  19259. }
  19260. this.cacheLengths = lengths;
  19261. return lengths;
  19262. }
  19263. getSpacedPoints(divisions = 40) {
  19264. const points = [];
  19265. for (let i = 0; i <= divisions; i++) {
  19266. points.push(this.getPoint(i / divisions));
  19267. }
  19268. if (this.autoClose) {
  19269. points.push(points[0]);
  19270. }
  19271. return points;
  19272. }
  19273. getPoints(divisions = 12) {
  19274. const points = [];
  19275. let last;
  19276. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19277. const curve = curves[i];
  19278. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19279. const pts = curve.getPoints(resolution);
  19280. for (let j = 0; j < pts.length; j++) {
  19281. const point = pts[j];
  19282. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19283. points.push(point);
  19284. last = point;
  19285. }
  19286. }
  19287. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19288. points.push(points[0]);
  19289. }
  19290. return points;
  19291. }
  19292. copy(source) {
  19293. super.copy(source);
  19294. this.curves = [];
  19295. for (let i = 0, l = source.curves.length; i < l; i++) {
  19296. const curve = source.curves[i];
  19297. this.curves.push(curve.clone());
  19298. }
  19299. this.autoClose = source.autoClose;
  19300. return this;
  19301. }
  19302. toJSON() {
  19303. const data = super.toJSON();
  19304. data.autoClose = this.autoClose;
  19305. data.curves = [];
  19306. for (let i = 0, l = this.curves.length; i < l; i++) {
  19307. const curve = this.curves[i];
  19308. data.curves.push(curve.toJSON());
  19309. }
  19310. return data;
  19311. }
  19312. fromJSON(json) {
  19313. super.fromJSON(json);
  19314. this.autoClose = json.autoClose;
  19315. this.curves = [];
  19316. for (let i = 0, l = json.curves.length; i < l; i++) {
  19317. const curve = json.curves[i];
  19318. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19319. }
  19320. return this;
  19321. }
  19322. }
  19323. class Path extends CurvePath {
  19324. constructor(points) {
  19325. super();
  19326. this.type = 'Path';
  19327. this.currentPoint = new Vector2();
  19328. if (points) {
  19329. this.setFromPoints(points);
  19330. }
  19331. }
  19332. setFromPoints(points) {
  19333. this.moveTo(points[0].x, points[0].y);
  19334. for (let i = 1, l = points.length; i < l; i++) {
  19335. this.lineTo(points[i].x, points[i].y);
  19336. }
  19337. return this;
  19338. }
  19339. moveTo(x, y) {
  19340. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19341. return this;
  19342. }
  19343. lineTo(x, y) {
  19344. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19345. this.curves.push(curve);
  19346. this.currentPoint.set(x, y);
  19347. return this;
  19348. }
  19349. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19350. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19351. this.curves.push(curve);
  19352. this.currentPoint.set(aX, aY);
  19353. return this;
  19354. }
  19355. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19356. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19357. this.curves.push(curve);
  19358. this.currentPoint.set(aX, aY);
  19359. return this;
  19360. }
  19361. splineThru(pts
  19362. /*Array of Vector*/
  19363. ) {
  19364. const npts = [this.currentPoint.clone()].concat(pts);
  19365. const curve = new SplineCurve(npts);
  19366. this.curves.push(curve);
  19367. this.currentPoint.copy(pts[pts.length - 1]);
  19368. return this;
  19369. }
  19370. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19371. const x0 = this.currentPoint.x;
  19372. const y0 = this.currentPoint.y;
  19373. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19374. return this;
  19375. }
  19376. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19377. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19378. return this;
  19379. }
  19380. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19381. const x0 = this.currentPoint.x;
  19382. const y0 = this.currentPoint.y;
  19383. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19384. return this;
  19385. }
  19386. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19387. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19388. if (this.curves.length > 0) {
  19389. // if a previous curve is present, attempt to join
  19390. const firstPoint = curve.getPoint(0);
  19391. if (!firstPoint.equals(this.currentPoint)) {
  19392. this.lineTo(firstPoint.x, firstPoint.y);
  19393. }
  19394. }
  19395. this.curves.push(curve);
  19396. const lastPoint = curve.getPoint(1);
  19397. this.currentPoint.copy(lastPoint);
  19398. return this;
  19399. }
  19400. copy(source) {
  19401. super.copy(source);
  19402. this.currentPoint.copy(source.currentPoint);
  19403. return this;
  19404. }
  19405. toJSON() {
  19406. const data = super.toJSON();
  19407. data.currentPoint = this.currentPoint.toArray();
  19408. return data;
  19409. }
  19410. fromJSON(json) {
  19411. super.fromJSON(json);
  19412. this.currentPoint.fromArray(json.currentPoint);
  19413. return this;
  19414. }
  19415. }
  19416. class LatheGeometry extends BufferGeometry {
  19417. constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19418. super();
  19419. this.type = 'LatheGeometry';
  19420. this.parameters = {
  19421. points: points,
  19422. segments: segments,
  19423. phiStart: phiStart,
  19424. phiLength: phiLength
  19425. };
  19426. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19427. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19428. const indices = [];
  19429. const vertices = [];
  19430. const uvs = [];
  19431. const initNormals = [];
  19432. const normals = []; // helper variables
  19433. const inverseSegments = 1.0 / segments;
  19434. const vertex = new Vector3();
  19435. const uv = new Vector2();
  19436. const normal = new Vector3();
  19437. const curNormal = new Vector3();
  19438. const prevNormal = new Vector3();
  19439. let dx = 0;
  19440. let dy = 0; // pre-compute normals for initial "meridian"
  19441. for (let j = 0; j <= points.length - 1; j++) {
  19442. switch (j) {
  19443. case 0:
  19444. // special handling for 1st vertex on path
  19445. dx = points[j + 1].x - points[j].x;
  19446. dy = points[j + 1].y - points[j].y;
  19447. normal.x = dy * 1.0;
  19448. normal.y = -dx;
  19449. normal.z = dy * 0.0;
  19450. prevNormal.copy(normal);
  19451. normal.normalize();
  19452. initNormals.push(normal.x, normal.y, normal.z);
  19453. break;
  19454. case points.length - 1:
  19455. // special handling for last Vertex on path
  19456. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  19457. break;
  19458. default:
  19459. // default handling for all vertices in between
  19460. dx = points[j + 1].x - points[j].x;
  19461. dy = points[j + 1].y - points[j].y;
  19462. normal.x = dy * 1.0;
  19463. normal.y = -dx;
  19464. normal.z = dy * 0.0;
  19465. curNormal.copy(normal);
  19466. normal.x += prevNormal.x;
  19467. normal.y += prevNormal.y;
  19468. normal.z += prevNormal.z;
  19469. normal.normalize();
  19470. initNormals.push(normal.x, normal.y, normal.z);
  19471. prevNormal.copy(curNormal);
  19472. }
  19473. } // generate vertices, uvs and normals
  19474. for (let i = 0; i <= segments; i++) {
  19475. const phi = phiStart + i * inverseSegments * phiLength;
  19476. const sin = Math.sin(phi);
  19477. const cos = Math.cos(phi);
  19478. for (let j = 0; j <= points.length - 1; j++) {
  19479. // vertex
  19480. vertex.x = points[j].x * sin;
  19481. vertex.y = points[j].y;
  19482. vertex.z = points[j].x * cos;
  19483. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19484. uv.x = i / segments;
  19485. uv.y = j / (points.length - 1);
  19486. uvs.push(uv.x, uv.y); // normal
  19487. const x = initNormals[3 * j + 0] * sin;
  19488. const y = initNormals[3 * j + 1];
  19489. const z = initNormals[3 * j + 0] * cos;
  19490. normals.push(x, y, z);
  19491. }
  19492. } // indices
  19493. for (let i = 0; i < segments; i++) {
  19494. for (let j = 0; j < points.length - 1; j++) {
  19495. const base = j + i * points.length;
  19496. const a = base;
  19497. const b = base + points.length;
  19498. const c = base + points.length + 1;
  19499. const d = base + 1; // faces
  19500. indices.push(a, b, d);
  19501. indices.push(c, d, b);
  19502. }
  19503. } // build geometry
  19504. this.setIndex(indices);
  19505. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19506. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19507. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19508. }
  19509. static fromJSON(data) {
  19510. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19511. }
  19512. }
  19513. class CapsuleGeometry extends LatheGeometry {
  19514. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  19515. const path = new Path();
  19516. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  19517. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  19518. super(path.getPoints(capSegments), radialSegments);
  19519. this.type = 'CapsuleGeometry';
  19520. this.parameters = {
  19521. radius: radius,
  19522. height: length,
  19523. capSegments: capSegments,
  19524. radialSegments: radialSegments
  19525. };
  19526. }
  19527. static fromJSON(data) {
  19528. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  19529. }
  19530. }
  19531. class CircleGeometry extends BufferGeometry {
  19532. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  19533. super();
  19534. this.type = 'CircleGeometry';
  19535. this.parameters = {
  19536. radius: radius,
  19537. segments: segments,
  19538. thetaStart: thetaStart,
  19539. thetaLength: thetaLength
  19540. };
  19541. segments = Math.max(3, segments); // buffers
  19542. const indices = [];
  19543. const vertices = [];
  19544. const normals = [];
  19545. const uvs = []; // helper variables
  19546. const vertex = new Vector3();
  19547. const uv = new Vector2(); // center point
  19548. vertices.push(0, 0, 0);
  19549. normals.push(0, 0, 1);
  19550. uvs.push(0.5, 0.5);
  19551. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  19552. const segment = thetaStart + s / segments * thetaLength; // vertex
  19553. vertex.x = radius * Math.cos(segment);
  19554. vertex.y = radius * Math.sin(segment);
  19555. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19556. normals.push(0, 0, 1); // uvs
  19557. uv.x = (vertices[i] / radius + 1) / 2;
  19558. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19559. uvs.push(uv.x, uv.y);
  19560. } // indices
  19561. for (let i = 1; i <= segments; i++) {
  19562. indices.push(i, i + 1, 0);
  19563. } // build geometry
  19564. this.setIndex(indices);
  19565. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19566. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19567. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19568. }
  19569. static fromJSON(data) {
  19570. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  19571. }
  19572. }
  19573. class CylinderGeometry extends BufferGeometry {
  19574. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19575. super();
  19576. this.type = 'CylinderGeometry';
  19577. this.parameters = {
  19578. radiusTop: radiusTop,
  19579. radiusBottom: radiusBottom,
  19580. height: height,
  19581. radialSegments: radialSegments,
  19582. heightSegments: heightSegments,
  19583. openEnded: openEnded,
  19584. thetaStart: thetaStart,
  19585. thetaLength: thetaLength
  19586. };
  19587. const scope = this;
  19588. radialSegments = Math.floor(radialSegments);
  19589. heightSegments = Math.floor(heightSegments); // buffers
  19590. const indices = [];
  19591. const vertices = [];
  19592. const normals = [];
  19593. const uvs = []; // helper variables
  19594. let index = 0;
  19595. const indexArray = [];
  19596. const halfHeight = height / 2;
  19597. let groupStart = 0; // generate geometry
  19598. generateTorso();
  19599. if (openEnded === false) {
  19600. if (radiusTop > 0) generateCap(true);
  19601. if (radiusBottom > 0) generateCap(false);
  19602. } // build geometry
  19603. this.setIndex(indices);
  19604. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19605. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19606. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19607. function generateTorso() {
  19608. const normal = new Vector3();
  19609. const vertex = new Vector3();
  19610. let groupCount = 0; // this will be used to calculate the normal
  19611. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19612. for (let y = 0; y <= heightSegments; y++) {
  19613. const indexRow = [];
  19614. const v = y / heightSegments; // calculate the radius of the current row
  19615. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  19616. for (let x = 0; x <= radialSegments; x++) {
  19617. const u = x / radialSegments;
  19618. const theta = u * thetaLength + thetaStart;
  19619. const sinTheta = Math.sin(theta);
  19620. const cosTheta = Math.cos(theta); // vertex
  19621. vertex.x = radius * sinTheta;
  19622. vertex.y = -v * height + halfHeight;
  19623. vertex.z = radius * cosTheta;
  19624. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19625. normal.set(sinTheta, slope, cosTheta).normalize();
  19626. normals.push(normal.x, normal.y, normal.z); // uv
  19627. uvs.push(u, 1 - v); // save index of vertex in respective row
  19628. indexRow.push(index++);
  19629. } // now save vertices of the row in our index array
  19630. indexArray.push(indexRow);
  19631. } // generate indices
  19632. for (let x = 0; x < radialSegments; x++) {
  19633. for (let y = 0; y < heightSegments; y++) {
  19634. // we use the index array to access the correct indices
  19635. const a = indexArray[y][x];
  19636. const b = indexArray[y + 1][x];
  19637. const c = indexArray[y + 1][x + 1];
  19638. const d = indexArray[y][x + 1]; // faces
  19639. indices.push(a, b, d);
  19640. indices.push(b, c, d); // update group counter
  19641. groupCount += 6;
  19642. }
  19643. } // add a group to the geometry. this will ensure multi material support
  19644. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19645. groupStart += groupCount;
  19646. }
  19647. function generateCap(top) {
  19648. // save the index of the first center vertex
  19649. const centerIndexStart = index;
  19650. const uv = new Vector2();
  19651. const vertex = new Vector3();
  19652. let groupCount = 0;
  19653. const radius = top === true ? radiusTop : radiusBottom;
  19654. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  19655. // because the geometry needs one set of uvs per face,
  19656. // we must generate a center vertex per face/segment
  19657. for (let x = 1; x <= radialSegments; x++) {
  19658. // vertex
  19659. vertices.push(0, halfHeight * sign, 0); // normal
  19660. normals.push(0, sign, 0); // uv
  19661. uvs.push(0.5, 0.5); // increase index
  19662. index++;
  19663. } // save the index of the last center vertex
  19664. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19665. for (let x = 0; x <= radialSegments; x++) {
  19666. const u = x / radialSegments;
  19667. const theta = u * thetaLength + thetaStart;
  19668. const cosTheta = Math.cos(theta);
  19669. const sinTheta = Math.sin(theta); // vertex
  19670. vertex.x = radius * sinTheta;
  19671. vertex.y = halfHeight * sign;
  19672. vertex.z = radius * cosTheta;
  19673. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19674. normals.push(0, sign, 0); // uv
  19675. uv.x = cosTheta * 0.5 + 0.5;
  19676. uv.y = sinTheta * 0.5 * sign + 0.5;
  19677. uvs.push(uv.x, uv.y); // increase index
  19678. index++;
  19679. } // generate indices
  19680. for (let x = 0; x < radialSegments; x++) {
  19681. const c = centerIndexStart + x;
  19682. const i = centerIndexEnd + x;
  19683. if (top === true) {
  19684. // face top
  19685. indices.push(i, i + 1, c);
  19686. } else {
  19687. // face bottom
  19688. indices.push(i + 1, i, c);
  19689. }
  19690. groupCount += 3;
  19691. } // add a group to the geometry. this will ensure multi material support
  19692. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19693. groupStart += groupCount;
  19694. }
  19695. }
  19696. static fromJSON(data) {
  19697. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19698. }
  19699. }
  19700. class ConeGeometry extends CylinderGeometry {
  19701. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19702. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19703. this.type = 'ConeGeometry';
  19704. this.parameters = {
  19705. radius: radius,
  19706. height: height,
  19707. radialSegments: radialSegments,
  19708. heightSegments: heightSegments,
  19709. openEnded: openEnded,
  19710. thetaStart: thetaStart,
  19711. thetaLength: thetaLength
  19712. };
  19713. }
  19714. static fromJSON(data) {
  19715. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19716. }
  19717. }
  19718. class PolyhedronGeometry extends BufferGeometry {
  19719. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  19720. super();
  19721. this.type = 'PolyhedronGeometry';
  19722. this.parameters = {
  19723. vertices: vertices,
  19724. indices: indices,
  19725. radius: radius,
  19726. detail: detail
  19727. }; // default buffer data
  19728. const vertexBuffer = [];
  19729. const uvBuffer = []; // the subdivision creates the vertex buffer data
  19730. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  19731. applyRadius(radius); // finally, create the uv data
  19732. generateUVs(); // build non-indexed geometry
  19733. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  19734. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  19735. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  19736. if (detail === 0) {
  19737. this.computeVertexNormals(); // flat normals
  19738. } else {
  19739. this.normalizeNormals(); // smooth normals
  19740. } // helper functions
  19741. function subdivide(detail) {
  19742. const a = new Vector3();
  19743. const b = new Vector3();
  19744. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  19745. for (let i = 0; i < indices.length; i += 3) {
  19746. // get the vertices of the face
  19747. getVertexByIndex(indices[i + 0], a);
  19748. getVertexByIndex(indices[i + 1], b);
  19749. getVertexByIndex(indices[i + 2], c); // perform subdivision
  19750. subdivideFace(a, b, c, detail);
  19751. }
  19752. }
  19753. function subdivideFace(a, b, c, detail) {
  19754. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  19755. const v = []; // construct all of the vertices for this subdivision
  19756. for (let i = 0; i <= cols; i++) {
  19757. v[i] = [];
  19758. const aj = a.clone().lerp(c, i / cols);
  19759. const bj = b.clone().lerp(c, i / cols);
  19760. const rows = cols - i;
  19761. for (let j = 0; j <= rows; j++) {
  19762. if (j === 0 && i === cols) {
  19763. v[i][j] = aj;
  19764. } else {
  19765. v[i][j] = aj.clone().lerp(bj, j / rows);
  19766. }
  19767. }
  19768. } // construct all of the faces
  19769. for (let i = 0; i < cols; i++) {
  19770. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  19771. const k = Math.floor(j / 2);
  19772. if (j % 2 === 0) {
  19773. pushVertex(v[i][k + 1]);
  19774. pushVertex(v[i + 1][k]);
  19775. pushVertex(v[i][k]);
  19776. } else {
  19777. pushVertex(v[i][k + 1]);
  19778. pushVertex(v[i + 1][k + 1]);
  19779. pushVertex(v[i + 1][k]);
  19780. }
  19781. }
  19782. }
  19783. }
  19784. function applyRadius(radius) {
  19785. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  19786. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19787. vertex.x = vertexBuffer[i + 0];
  19788. vertex.y = vertexBuffer[i + 1];
  19789. vertex.z = vertexBuffer[i + 2];
  19790. vertex.normalize().multiplyScalar(radius);
  19791. vertexBuffer[i + 0] = vertex.x;
  19792. vertexBuffer[i + 1] = vertex.y;
  19793. vertexBuffer[i + 2] = vertex.z;
  19794. }
  19795. }
  19796. function generateUVs() {
  19797. const vertex = new Vector3();
  19798. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19799. vertex.x = vertexBuffer[i + 0];
  19800. vertex.y = vertexBuffer[i + 1];
  19801. vertex.z = vertexBuffer[i + 2];
  19802. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  19803. const v = inclination(vertex) / Math.PI + 0.5;
  19804. uvBuffer.push(u, 1 - v);
  19805. }
  19806. correctUVs();
  19807. correctSeam();
  19808. }
  19809. function correctSeam() {
  19810. // handle case when face straddles the seam, see #3269
  19811. for (let i = 0; i < uvBuffer.length; i += 6) {
  19812. // uv data of a single face
  19813. const x0 = uvBuffer[i + 0];
  19814. const x1 = uvBuffer[i + 2];
  19815. const x2 = uvBuffer[i + 4];
  19816. const max = Math.max(x0, x1, x2);
  19817. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  19818. if (max > 0.9 && min < 0.1) {
  19819. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  19820. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  19821. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  19822. }
  19823. }
  19824. }
  19825. function pushVertex(vertex) {
  19826. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  19827. }
  19828. function getVertexByIndex(index, vertex) {
  19829. const stride = index * 3;
  19830. vertex.x = vertices[stride + 0];
  19831. vertex.y = vertices[stride + 1];
  19832. vertex.z = vertices[stride + 2];
  19833. }
  19834. function correctUVs() {
  19835. const a = new Vector3();
  19836. const b = new Vector3();
  19837. const c = new Vector3();
  19838. const centroid = new Vector3();
  19839. const uvA = new Vector2();
  19840. const uvB = new Vector2();
  19841. const uvC = new Vector2();
  19842. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  19843. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  19844. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  19845. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  19846. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  19847. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  19848. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  19849. centroid.copy(a).add(b).add(c).divideScalar(3);
  19850. const azi = azimuth(centroid);
  19851. correctUV(uvA, j + 0, a, azi);
  19852. correctUV(uvB, j + 2, b, azi);
  19853. correctUV(uvC, j + 4, c, azi);
  19854. }
  19855. }
  19856. function correctUV(uv, stride, vector, azimuth) {
  19857. if (azimuth < 0 && uv.x === 1) {
  19858. uvBuffer[stride] = uv.x - 1;
  19859. }
  19860. if (vector.x === 0 && vector.z === 0) {
  19861. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  19862. }
  19863. } // Angle around the Y axis, counter-clockwise when looking from above.
  19864. function azimuth(vector) {
  19865. return Math.atan2(vector.z, -vector.x);
  19866. } // Angle above the XZ plane.
  19867. function inclination(vector) {
  19868. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  19869. }
  19870. }
  19871. static fromJSON(data) {
  19872. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  19873. }
  19874. }
  19875. class DodecahedronGeometry extends PolyhedronGeometry {
  19876. constructor(radius = 1, detail = 0) {
  19877. const t = (1 + Math.sqrt(5)) / 2;
  19878. const r = 1 / t;
  19879. const vertices = [// (±1, ±1, ±1)
  19880. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  19881. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  19882. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  19883. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  19884. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  19885. super(vertices, indices, radius, detail);
  19886. this.type = 'DodecahedronGeometry';
  19887. this.parameters = {
  19888. radius: radius,
  19889. detail: detail
  19890. };
  19891. }
  19892. static fromJSON(data) {
  19893. return new DodecahedronGeometry(data.radius, data.detail);
  19894. }
  19895. }
  19896. const _v0 = /*@__PURE__*/new Vector3();
  19897. const _v1$1 = /*@__PURE__*/new Vector3();
  19898. const _normal = /*@__PURE__*/new Vector3();
  19899. const _triangle = /*@__PURE__*/new Triangle();
  19900. class EdgesGeometry extends BufferGeometry {
  19901. constructor(geometry = null, thresholdAngle = 1) {
  19902. super();
  19903. this.type = 'EdgesGeometry';
  19904. this.parameters = {
  19905. geometry: geometry,
  19906. thresholdAngle: thresholdAngle
  19907. };
  19908. if (geometry !== null) {
  19909. const precisionPoints = 4;
  19910. const precision = Math.pow(10, precisionPoints);
  19911. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  19912. const indexAttr = geometry.getIndex();
  19913. const positionAttr = geometry.getAttribute('position');
  19914. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19915. const indexArr = [0, 0, 0];
  19916. const vertKeys = ['a', 'b', 'c'];
  19917. const hashes = new Array(3);
  19918. const edgeData = {};
  19919. const vertices = [];
  19920. for (let i = 0; i < indexCount; i += 3) {
  19921. if (indexAttr) {
  19922. indexArr[0] = indexAttr.getX(i);
  19923. indexArr[1] = indexAttr.getX(i + 1);
  19924. indexArr[2] = indexAttr.getX(i + 2);
  19925. } else {
  19926. indexArr[0] = i;
  19927. indexArr[1] = i + 1;
  19928. indexArr[2] = i + 2;
  19929. }
  19930. const {
  19931. a,
  19932. b,
  19933. c
  19934. } = _triangle;
  19935. a.fromBufferAttribute(positionAttr, indexArr[0]);
  19936. b.fromBufferAttribute(positionAttr, indexArr[1]);
  19937. c.fromBufferAttribute(positionAttr, indexArr[2]);
  19938. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  19939. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  19940. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  19941. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  19942. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  19943. continue;
  19944. } // iterate over every edge
  19945. for (let j = 0; j < 3; j++) {
  19946. // get the first and next vertex making up the edge
  19947. const jNext = (j + 1) % 3;
  19948. const vecHash0 = hashes[j];
  19949. const vecHash1 = hashes[jNext];
  19950. const v0 = _triangle[vertKeys[j]];
  19951. const v1 = _triangle[vertKeys[jNext]];
  19952. const hash = `${vecHash0}_${vecHash1}`;
  19953. const reverseHash = `${vecHash1}_${vecHash0}`;
  19954. if (reverseHash in edgeData && edgeData[reverseHash]) {
  19955. // if we found a sibling edge add it into the vertex array if
  19956. // it meets the angle threshold and delete the edge from the map.
  19957. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  19958. vertices.push(v0.x, v0.y, v0.z);
  19959. vertices.push(v1.x, v1.y, v1.z);
  19960. }
  19961. edgeData[reverseHash] = null;
  19962. } else if (!(hash in edgeData)) {
  19963. // if we've already got an edge here then skip adding a new one
  19964. edgeData[hash] = {
  19965. index0: indexArr[j],
  19966. index1: indexArr[jNext],
  19967. normal: _normal.clone()
  19968. };
  19969. }
  19970. }
  19971. } // iterate over all remaining, unmatched edges and add them to the vertex array
  19972. for (const key in edgeData) {
  19973. if (edgeData[key]) {
  19974. const {
  19975. index0,
  19976. index1
  19977. } = edgeData[key];
  19978. _v0.fromBufferAttribute(positionAttr, index0);
  19979. _v1$1.fromBufferAttribute(positionAttr, index1);
  19980. vertices.push(_v0.x, _v0.y, _v0.z);
  19981. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  19982. }
  19983. }
  19984. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19985. }
  19986. }
  19987. }
  19988. class Shape extends Path {
  19989. constructor(points) {
  19990. super(points);
  19991. this.uuid = generateUUID();
  19992. this.type = 'Shape';
  19993. this.holes = [];
  19994. }
  19995. getPointsHoles(divisions) {
  19996. const holesPts = [];
  19997. for (let i = 0, l = this.holes.length; i < l; i++) {
  19998. holesPts[i] = this.holes[i].getPoints(divisions);
  19999. }
  20000. return holesPts;
  20001. } // get points of shape and holes (keypoints based on segments parameter)
  20002. extractPoints(divisions) {
  20003. return {
  20004. shape: this.getPoints(divisions),
  20005. holes: this.getPointsHoles(divisions)
  20006. };
  20007. }
  20008. copy(source) {
  20009. super.copy(source);
  20010. this.holes = [];
  20011. for (let i = 0, l = source.holes.length; i < l; i++) {
  20012. const hole = source.holes[i];
  20013. this.holes.push(hole.clone());
  20014. }
  20015. return this;
  20016. }
  20017. toJSON() {
  20018. const data = super.toJSON();
  20019. data.uuid = this.uuid;
  20020. data.holes = [];
  20021. for (let i = 0, l = this.holes.length; i < l; i++) {
  20022. const hole = this.holes[i];
  20023. data.holes.push(hole.toJSON());
  20024. }
  20025. return data;
  20026. }
  20027. fromJSON(json) {
  20028. super.fromJSON(json);
  20029. this.uuid = json.uuid;
  20030. this.holes = [];
  20031. for (let i = 0, l = json.holes.length; i < l; i++) {
  20032. const hole = json.holes[i];
  20033. this.holes.push(new Path().fromJSON(hole));
  20034. }
  20035. return this;
  20036. }
  20037. }
  20038. /**
  20039. * Port from https://github.com/mapbox/earcut (v2.2.2)
  20040. */
  20041. const Earcut = {
  20042. triangulate: function (data, holeIndices, dim = 2) {
  20043. const hasHoles = holeIndices && holeIndices.length;
  20044. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  20045. let outerNode = linkedList(data, 0, outerLen, dim, true);
  20046. const triangles = [];
  20047. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  20048. let minX, minY, maxX, maxY, x, y, invSize;
  20049. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20050. if (data.length > 80 * dim) {
  20051. minX = maxX = data[0];
  20052. minY = maxY = data[1];
  20053. for (let i = dim; i < outerLen; i += dim) {
  20054. x = data[i];
  20055. y = data[i + 1];
  20056. if (x < minX) minX = x;
  20057. if (y < minY) minY = y;
  20058. if (x > maxX) maxX = x;
  20059. if (y > maxY) maxY = y;
  20060. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20061. invSize = Math.max(maxX - minX, maxY - minY);
  20062. invSize = invSize !== 0 ? 1 / invSize : 0;
  20063. }
  20064. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  20065. return triangles;
  20066. }
  20067. }; // create a circular doubly linked list from polygon points in the specified winding order
  20068. function linkedList(data, start, end, dim, clockwise) {
  20069. let i, last;
  20070. if (clockwise === signedArea(data, start, end, dim) > 0) {
  20071. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  20072. } else {
  20073. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  20074. }
  20075. if (last && equals(last, last.next)) {
  20076. removeNode(last);
  20077. last = last.next;
  20078. }
  20079. return last;
  20080. } // eliminate colinear or duplicate points
  20081. function filterPoints(start, end) {
  20082. if (!start) return start;
  20083. if (!end) end = start;
  20084. let p = start,
  20085. again;
  20086. do {
  20087. again = false;
  20088. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  20089. removeNode(p);
  20090. p = end = p.prev;
  20091. if (p === p.next) break;
  20092. again = true;
  20093. } else {
  20094. p = p.next;
  20095. }
  20096. } while (again || p !== end);
  20097. return end;
  20098. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  20099. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  20100. if (!ear) return; // interlink polygon nodes in z-order
  20101. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  20102. let stop = ear,
  20103. prev,
  20104. next; // iterate through ears, slicing them one by one
  20105. while (ear.prev !== ear.next) {
  20106. prev = ear.prev;
  20107. next = ear.next;
  20108. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  20109. // cut off the triangle
  20110. triangles.push(prev.i / dim);
  20111. triangles.push(ear.i / dim);
  20112. triangles.push(next.i / dim);
  20113. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  20114. ear = next.next;
  20115. stop = next.next;
  20116. continue;
  20117. }
  20118. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  20119. if (ear === stop) {
  20120. // try filtering points and slicing again
  20121. if (!pass) {
  20122. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  20123. } else if (pass === 1) {
  20124. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  20125. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  20126. } else if (pass === 2) {
  20127. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  20128. }
  20129. break;
  20130. }
  20131. }
  20132. } // check whether a polygon node forms a valid ear with adjacent nodes
  20133. function isEar(ear) {
  20134. const a = ear.prev,
  20135. b = ear,
  20136. c = ear.next;
  20137. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20138. // now make sure we don't have other points inside the potential ear
  20139. let p = ear.next.next;
  20140. while (p !== ear.prev) {
  20141. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20142. p = p.next;
  20143. }
  20144. return true;
  20145. }
  20146. function isEarHashed(ear, minX, minY, invSize) {
  20147. const a = ear.prev,
  20148. b = ear,
  20149. c = ear.next;
  20150. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  20151. // triangle bbox; min & max are calculated like this for speed
  20152. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  20153. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  20154. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  20155. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  20156. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  20157. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  20158. let p = ear.prevZ,
  20159. n = ear.nextZ; // look for points inside the triangle in both directions
  20160. while (p && p.z >= minZ && n && n.z <= maxZ) {
  20161. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20162. p = p.prevZ;
  20163. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20164. n = n.nextZ;
  20165. } // look for remaining points in decreasing z-order
  20166. while (p && p.z >= minZ) {
  20167. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  20168. p = p.prevZ;
  20169. } // look for remaining points in increasing z-order
  20170. while (n && n.z <= maxZ) {
  20171. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  20172. n = n.nextZ;
  20173. }
  20174. return true;
  20175. } // go through all polygon nodes and cure small local self-intersections
  20176. function cureLocalIntersections(start, triangles, dim) {
  20177. let p = start;
  20178. do {
  20179. const a = p.prev,
  20180. b = p.next.next;
  20181. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  20182. triangles.push(a.i / dim);
  20183. triangles.push(p.i / dim);
  20184. triangles.push(b.i / dim); // remove two nodes involved
  20185. removeNode(p);
  20186. removeNode(p.next);
  20187. p = start = b;
  20188. }
  20189. p = p.next;
  20190. } while (p !== start);
  20191. return filterPoints(p);
  20192. } // try splitting polygon into two and triangulate them independently
  20193. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  20194. // look for a valid diagonal that divides the polygon into two
  20195. let a = start;
  20196. do {
  20197. let b = a.next.next;
  20198. while (b !== a.prev) {
  20199. if (a.i !== b.i && isValidDiagonal(a, b)) {
  20200. // split the polygon in two by the diagonal
  20201. let c = splitPolygon(a, b); // filter colinear points around the cuts
  20202. a = filterPoints(a, a.next);
  20203. c = filterPoints(c, c.next); // run earcut on each half
  20204. earcutLinked(a, triangles, dim, minX, minY, invSize);
  20205. earcutLinked(c, triangles, dim, minX, minY, invSize);
  20206. return;
  20207. }
  20208. b = b.next;
  20209. }
  20210. a = a.next;
  20211. } while (a !== start);
  20212. } // link every hole into the outer loop, producing a single-ring polygon without holes
  20213. function eliminateHoles(data, holeIndices, outerNode, dim) {
  20214. const queue = [];
  20215. let i, len, start, end, list;
  20216. for (i = 0, len = holeIndices.length; i < len; i++) {
  20217. start = holeIndices[i] * dim;
  20218. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  20219. list = linkedList(data, start, end, dim, false);
  20220. if (list === list.next) list.steiner = true;
  20221. queue.push(getLeftmost(list));
  20222. }
  20223. queue.sort(compareX); // process holes from left to right
  20224. for (i = 0; i < queue.length; i++) {
  20225. eliminateHole(queue[i], outerNode);
  20226. outerNode = filterPoints(outerNode, outerNode.next);
  20227. }
  20228. return outerNode;
  20229. }
  20230. function compareX(a, b) {
  20231. return a.x - b.x;
  20232. } // find a bridge between vertices that connects hole with an outer ring and link it
  20233. function eliminateHole(hole, outerNode) {
  20234. outerNode = findHoleBridge(hole, outerNode);
  20235. if (outerNode) {
  20236. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  20237. filterPoints(outerNode, outerNode.next);
  20238. filterPoints(b, b.next);
  20239. }
  20240. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20241. function findHoleBridge(hole, outerNode) {
  20242. let p = outerNode;
  20243. const hx = hole.x;
  20244. const hy = hole.y;
  20245. let qx = -Infinity,
  20246. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  20247. // segment's endpoint with lesser x will be potential connection point
  20248. do {
  20249. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  20250. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  20251. if (x <= hx && x > qx) {
  20252. qx = x;
  20253. if (x === hx) {
  20254. if (hy === p.y) return p;
  20255. if (hy === p.next.y) return p.next;
  20256. }
  20257. m = p.x < p.next.x ? p : p.next;
  20258. }
  20259. }
  20260. p = p.next;
  20261. } while (p !== outerNode);
  20262. if (!m) return null;
  20263. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  20264. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20265. // if there are no points found, we have a valid connection;
  20266. // otherwise choose the point of the minimum angle with the ray as connection point
  20267. const stop = m,
  20268. mx = m.x,
  20269. my = m.y;
  20270. let tanMin = Infinity,
  20271. tan;
  20272. p = m;
  20273. do {
  20274. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  20275. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  20276. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  20277. m = p;
  20278. tanMin = tan;
  20279. }
  20280. }
  20281. p = p.next;
  20282. } while (p !== stop);
  20283. return m;
  20284. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  20285. function sectorContainsSector(m, p) {
  20286. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  20287. } // interlink polygon nodes in z-order
  20288. function indexCurve(start, minX, minY, invSize) {
  20289. let p = start;
  20290. do {
  20291. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  20292. p.prevZ = p.prev;
  20293. p.nextZ = p.next;
  20294. p = p.next;
  20295. } while (p !== start);
  20296. p.prevZ.nextZ = null;
  20297. p.prevZ = null;
  20298. sortLinked(p);
  20299. } // Simon Tatham's linked list merge sort algorithm
  20300. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20301. function sortLinked(list) {
  20302. let i,
  20303. p,
  20304. q,
  20305. e,
  20306. tail,
  20307. numMerges,
  20308. pSize,
  20309. qSize,
  20310. inSize = 1;
  20311. do {
  20312. p = list;
  20313. list = null;
  20314. tail = null;
  20315. numMerges = 0;
  20316. while (p) {
  20317. numMerges++;
  20318. q = p;
  20319. pSize = 0;
  20320. for (i = 0; i < inSize; i++) {
  20321. pSize++;
  20322. q = q.nextZ;
  20323. if (!q) break;
  20324. }
  20325. qSize = inSize;
  20326. while (pSize > 0 || qSize > 0 && q) {
  20327. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  20328. e = p;
  20329. p = p.nextZ;
  20330. pSize--;
  20331. } else {
  20332. e = q;
  20333. q = q.nextZ;
  20334. qSize--;
  20335. }
  20336. if (tail) tail.nextZ = e;else list = e;
  20337. e.prevZ = tail;
  20338. tail = e;
  20339. }
  20340. p = q;
  20341. }
  20342. tail.nextZ = null;
  20343. inSize *= 2;
  20344. } while (numMerges > 1);
  20345. return list;
  20346. } // z-order of a point given coords and inverse of the longer side of data bbox
  20347. function zOrder(x, y, minX, minY, invSize) {
  20348. // coords are transformed into non-negative 15-bit integer range
  20349. x = 32767 * (x - minX) * invSize;
  20350. y = 32767 * (y - minY) * invSize;
  20351. x = (x | x << 8) & 0x00FF00FF;
  20352. x = (x | x << 4) & 0x0F0F0F0F;
  20353. x = (x | x << 2) & 0x33333333;
  20354. x = (x | x << 1) & 0x55555555;
  20355. y = (y | y << 8) & 0x00FF00FF;
  20356. y = (y | y << 4) & 0x0F0F0F0F;
  20357. y = (y | y << 2) & 0x33333333;
  20358. y = (y | y << 1) & 0x55555555;
  20359. return x | y << 1;
  20360. } // find the leftmost node of a polygon ring
  20361. function getLeftmost(start) {
  20362. let p = start,
  20363. leftmost = start;
  20364. do {
  20365. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  20366. p = p.next;
  20367. } while (p !== start);
  20368. return leftmost;
  20369. } // check if a point lies within a convex triangle
  20370. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  20371. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  20372. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20373. function isValidDiagonal(a, b) {
  20374. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // doesn't intersect other edges
  20375. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  20376. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  20377. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  20378. } // signed area of a triangle
  20379. function area(p, q, r) {
  20380. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  20381. } // check if two points are equal
  20382. function equals(p1, p2) {
  20383. return p1.x === p2.x && p1.y === p2.y;
  20384. } // check if two segments intersect
  20385. function intersects(p1, q1, p2, q2) {
  20386. const o1 = sign(area(p1, q1, p2));
  20387. const o2 = sign(area(p1, q1, q2));
  20388. const o3 = sign(area(p2, q2, p1));
  20389. const o4 = sign(area(p2, q2, q1));
  20390. if (o1 !== o2 && o3 !== o4) return true; // general case
  20391. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20392. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20393. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20394. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20395. return false;
  20396. } // for collinear points p, q, r, check if point q lies on segment pr
  20397. function onSegment(p, q, r) {
  20398. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  20399. }
  20400. function sign(num) {
  20401. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20402. } // check if a polygon diagonal intersects any polygon segments
  20403. function intersectsPolygon(a, b) {
  20404. let p = a;
  20405. do {
  20406. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  20407. p = p.next;
  20408. } while (p !== a);
  20409. return false;
  20410. } // check if a polygon diagonal is locally inside the polygon
  20411. function locallyInside(a, b) {
  20412. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  20413. } // check if the middle point of a polygon diagonal is inside the polygon
  20414. function middleInside(a, b) {
  20415. let p = a,
  20416. inside = false;
  20417. const px = (a.x + b.x) / 2,
  20418. py = (a.y + b.y) / 2;
  20419. do {
  20420. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  20421. p = p.next;
  20422. } while (p !== a);
  20423. return inside;
  20424. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20425. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20426. function splitPolygon(a, b) {
  20427. const a2 = new Node(a.i, a.x, a.y),
  20428. b2 = new Node(b.i, b.x, b.y),
  20429. an = a.next,
  20430. bp = b.prev;
  20431. a.next = b;
  20432. b.prev = a;
  20433. a2.next = an;
  20434. an.prev = a2;
  20435. b2.next = a2;
  20436. a2.prev = b2;
  20437. bp.next = b2;
  20438. b2.prev = bp;
  20439. return b2;
  20440. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  20441. function insertNode(i, x, y, last) {
  20442. const p = new Node(i, x, y);
  20443. if (!last) {
  20444. p.prev = p;
  20445. p.next = p;
  20446. } else {
  20447. p.next = last.next;
  20448. p.prev = last;
  20449. last.next.prev = p;
  20450. last.next = p;
  20451. }
  20452. return p;
  20453. }
  20454. function removeNode(p) {
  20455. p.next.prev = p.prev;
  20456. p.prev.next = p.next;
  20457. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  20458. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  20459. }
  20460. function Node(i, x, y) {
  20461. // vertex index in coordinates array
  20462. this.i = i; // vertex coordinates
  20463. this.x = x;
  20464. this.y = y; // previous and next vertex nodes in a polygon ring
  20465. this.prev = null;
  20466. this.next = null; // z-order curve value
  20467. this.z = null; // previous and next nodes in z-order
  20468. this.prevZ = null;
  20469. this.nextZ = null; // indicates whether this is a steiner point
  20470. this.steiner = false;
  20471. }
  20472. function signedArea(data, start, end, dim) {
  20473. let sum = 0;
  20474. for (let i = start, j = end - dim; i < end; i += dim) {
  20475. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  20476. j = i;
  20477. }
  20478. return sum;
  20479. }
  20480. class ShapeUtils {
  20481. // calculate area of the contour polygon
  20482. static area(contour) {
  20483. const n = contour.length;
  20484. let a = 0.0;
  20485. for (let p = n - 1, q = 0; q < n; p = q++) {
  20486. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  20487. }
  20488. return a * 0.5;
  20489. }
  20490. static isClockWise(pts) {
  20491. return ShapeUtils.area(pts) < 0;
  20492. }
  20493. static triangulateShape(contour, holes) {
  20494. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20495. const holeIndices = []; // array of hole indices
  20496. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20497. removeDupEndPts(contour);
  20498. addContour(vertices, contour); //
  20499. let holeIndex = contour.length;
  20500. holes.forEach(removeDupEndPts);
  20501. for (let i = 0; i < holes.length; i++) {
  20502. holeIndices.push(holeIndex);
  20503. holeIndex += holes[i].length;
  20504. addContour(vertices, holes[i]);
  20505. } //
  20506. const triangles = Earcut.triangulate(vertices, holeIndices); //
  20507. for (let i = 0; i < triangles.length; i += 3) {
  20508. faces.push(triangles.slice(i, i + 3));
  20509. }
  20510. return faces;
  20511. }
  20512. }
  20513. function removeDupEndPts(points) {
  20514. const l = points.length;
  20515. if (l > 2 && points[l - 1].equals(points[0])) {
  20516. points.pop();
  20517. }
  20518. }
  20519. function addContour(vertices, contour) {
  20520. for (let i = 0; i < contour.length; i++) {
  20521. vertices.push(contour[i].x);
  20522. vertices.push(contour[i].y);
  20523. }
  20524. }
  20525. /**
  20526. * Creates extruded geometry from a path shape.
  20527. *
  20528. * parameters = {
  20529. *
  20530. * curveSegments: <int>, // number of points on the curves
  20531. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20532. * depth: <float>, // Depth to extrude the shape
  20533. *
  20534. * bevelEnabled: <bool>, // turn on bevel
  20535. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20536. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20537. * bevelOffset: <float>, // how far from shape outline does bevel start
  20538. * bevelSegments: <int>, // number of bevel layers
  20539. *
  20540. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20541. *
  20542. * UVGenerator: <Object> // object that provides UV generator functions
  20543. *
  20544. * }
  20545. */
  20546. class ExtrudeGeometry extends BufferGeometry {
  20547. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  20548. super();
  20549. this.type = 'ExtrudeGeometry';
  20550. this.parameters = {
  20551. shapes: shapes,
  20552. options: options
  20553. };
  20554. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20555. const scope = this;
  20556. const verticesArray = [];
  20557. const uvArray = [];
  20558. for (let i = 0, l = shapes.length; i < l; i++) {
  20559. const shape = shapes[i];
  20560. addShape(shape);
  20561. } // build geometry
  20562. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20563. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20564. this.computeVertexNormals(); // functions
  20565. function addShape(shape) {
  20566. const placeholder = []; // options
  20567. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20568. const steps = options.steps !== undefined ? options.steps : 1;
  20569. const depth = options.depth !== undefined ? options.depth : 1;
  20570. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20571. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20572. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20573. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20574. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20575. const extrudePath = options.extrudePath;
  20576. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; //
  20577. let extrudePts,
  20578. extrudeByPath = false;
  20579. let splineTube, binormal, normal, position2;
  20580. if (extrudePath) {
  20581. extrudePts = extrudePath.getSpacedPoints(steps);
  20582. extrudeByPath = true;
  20583. bevelEnabled = false; // bevels not supported for path extrusion
  20584. // SETUP TNB variables
  20585. // TODO1 - have a .isClosed in spline?
  20586. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20587. binormal = new Vector3();
  20588. normal = new Vector3();
  20589. position2 = new Vector3();
  20590. } // Safeguards if bevels are not enabled
  20591. if (!bevelEnabled) {
  20592. bevelSegments = 0;
  20593. bevelThickness = 0;
  20594. bevelSize = 0;
  20595. bevelOffset = 0;
  20596. } // Variables initialization
  20597. const shapePoints = shape.extractPoints(curveSegments);
  20598. let vertices = shapePoints.shape;
  20599. const holes = shapePoints.holes;
  20600. const reverse = !ShapeUtils.isClockWise(vertices);
  20601. if (reverse) {
  20602. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20603. for (let h = 0, hl = holes.length; h < hl; h++) {
  20604. const ahole = holes[h];
  20605. if (ShapeUtils.isClockWise(ahole)) {
  20606. holes[h] = ahole.reverse();
  20607. }
  20608. }
  20609. }
  20610. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20611. /* Vertices */
  20612. const contour = vertices; // vertices has all points but contour has only points of circumference
  20613. for (let h = 0, hl = holes.length; h < hl; h++) {
  20614. const ahole = holes[h];
  20615. vertices = vertices.concat(ahole);
  20616. }
  20617. function scalePt2(pt, vec, size) {
  20618. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20619. return vec.clone().multiplyScalar(size).add(pt);
  20620. }
  20621. const vlen = vertices.length,
  20622. flen = faces.length; // Find directions for point movement
  20623. function getBevelVec(inPt, inPrev, inNext) {
  20624. // computes for inPt the corresponding point inPt' on a new contour
  20625. // shifted by 1 unit (length of normalized vector) to the left
  20626. // if we walk along contour clockwise, this new contour is outside the old one
  20627. //
  20628. // inPt' is the intersection of the two lines parallel to the two
  20629. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20630. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20631. // good reading for geometry algorithms (here: line-line intersection)
  20632. // http://geomalgorithms.com/a05-_intersect-1.html
  20633. const v_prev_x = inPt.x - inPrev.x,
  20634. v_prev_y = inPt.y - inPrev.y;
  20635. const v_next_x = inNext.x - inPt.x,
  20636. v_next_y = inNext.y - inPt.y;
  20637. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20638. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20639. if (Math.abs(collinear0) > Number.EPSILON) {
  20640. // not collinear
  20641. // length of vectors for normalizing
  20642. const v_prev_len = Math.sqrt(v_prev_lensq);
  20643. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  20644. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20645. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20646. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20647. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20648. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  20649. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20650. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20651. // but prevent crazy spikes
  20652. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20653. if (v_trans_lensq <= 2) {
  20654. return new Vector2(v_trans_x, v_trans_y);
  20655. } else {
  20656. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20657. }
  20658. } else {
  20659. // handle special case of collinear edges
  20660. let direction_eq = false; // assumes: opposite
  20661. if (v_prev_x > Number.EPSILON) {
  20662. if (v_next_x > Number.EPSILON) {
  20663. direction_eq = true;
  20664. }
  20665. } else {
  20666. if (v_prev_x < -Number.EPSILON) {
  20667. if (v_next_x < -Number.EPSILON) {
  20668. direction_eq = true;
  20669. }
  20670. } else {
  20671. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20672. direction_eq = true;
  20673. }
  20674. }
  20675. }
  20676. if (direction_eq) {
  20677. // console.log("Warning: lines are a straight sequence");
  20678. v_trans_x = -v_prev_y;
  20679. v_trans_y = v_prev_x;
  20680. shrink_by = Math.sqrt(v_prev_lensq);
  20681. } else {
  20682. // console.log("Warning: lines are a straight spike");
  20683. v_trans_x = v_prev_x;
  20684. v_trans_y = v_prev_y;
  20685. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20686. }
  20687. }
  20688. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20689. }
  20690. const contourMovements = [];
  20691. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20692. if (j === il) j = 0;
  20693. if (k === il) k = 0; // (j)---(i)---(k)
  20694. // console.log('i,j,k', i, j , k)
  20695. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20696. }
  20697. const holesMovements = [];
  20698. let oneHoleMovements,
  20699. verticesMovements = contourMovements.concat();
  20700. for (let h = 0, hl = holes.length; h < hl; h++) {
  20701. const ahole = holes[h];
  20702. oneHoleMovements = [];
  20703. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20704. if (j === il) j = 0;
  20705. if (k === il) k = 0; // (j)---(i)---(k)
  20706. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20707. }
  20708. holesMovements.push(oneHoleMovements);
  20709. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20710. } // Loop bevelSegments, 1 for the front, 1 for the back
  20711. for (let b = 0; b < bevelSegments; b++) {
  20712. //for ( b = bevelSegments; b > 0; b -- ) {
  20713. const t = b / bevelSegments;
  20714. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20715. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20716. for (let i = 0, il = contour.length; i < il; i++) {
  20717. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20718. v(vert.x, vert.y, -z);
  20719. } // expand holes
  20720. for (let h = 0, hl = holes.length; h < hl; h++) {
  20721. const ahole = holes[h];
  20722. oneHoleMovements = holesMovements[h];
  20723. for (let i = 0, il = ahole.length; i < il; i++) {
  20724. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20725. v(vert.x, vert.y, -z);
  20726. }
  20727. }
  20728. }
  20729. const bs = bevelSize + bevelOffset; // Back facing vertices
  20730. for (let i = 0; i < vlen; i++) {
  20731. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20732. if (!extrudeByPath) {
  20733. v(vert.x, vert.y, 0);
  20734. } else {
  20735. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20736. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20737. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20738. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20739. v(position2.x, position2.y, position2.z);
  20740. }
  20741. } // Add stepped vertices...
  20742. // Including front facing vertices
  20743. for (let s = 1; s <= steps; s++) {
  20744. for (let i = 0; i < vlen; i++) {
  20745. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20746. if (!extrudeByPath) {
  20747. v(vert.x, vert.y, depth / steps * s);
  20748. } else {
  20749. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20750. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20751. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20752. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20753. v(position2.x, position2.y, position2.z);
  20754. }
  20755. }
  20756. } // Add bevel segments planes
  20757. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20758. for (let b = bevelSegments - 1; b >= 0; b--) {
  20759. const t = b / bevelSegments;
  20760. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20761. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20762. for (let i = 0, il = contour.length; i < il; i++) {
  20763. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20764. v(vert.x, vert.y, depth + z);
  20765. } // expand holes
  20766. for (let h = 0, hl = holes.length; h < hl; h++) {
  20767. const ahole = holes[h];
  20768. oneHoleMovements = holesMovements[h];
  20769. for (let i = 0, il = ahole.length; i < il; i++) {
  20770. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20771. if (!extrudeByPath) {
  20772. v(vert.x, vert.y, depth + z);
  20773. } else {
  20774. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20775. }
  20776. }
  20777. }
  20778. }
  20779. /* Faces */
  20780. // Top and bottom faces
  20781. buildLidFaces(); // Sides faces
  20782. buildSideFaces(); ///// Internal functions
  20783. function buildLidFaces() {
  20784. const start = verticesArray.length / 3;
  20785. if (bevelEnabled) {
  20786. let layer = 0; // steps + 1
  20787. let offset = vlen * layer; // Bottom faces
  20788. for (let i = 0; i < flen; i++) {
  20789. const face = faces[i];
  20790. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20791. }
  20792. layer = steps + bevelSegments * 2;
  20793. offset = vlen * layer; // Top faces
  20794. for (let i = 0; i < flen; i++) {
  20795. const face = faces[i];
  20796. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20797. }
  20798. } else {
  20799. // Bottom faces
  20800. for (let i = 0; i < flen; i++) {
  20801. const face = faces[i];
  20802. f3(face[2], face[1], face[0]);
  20803. } // Top faces
  20804. for (let i = 0; i < flen; i++) {
  20805. const face = faces[i];
  20806. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20807. }
  20808. }
  20809. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20810. } // Create faces for the z-sides of the shape
  20811. function buildSideFaces() {
  20812. const start = verticesArray.length / 3;
  20813. let layeroffset = 0;
  20814. sidewalls(contour, layeroffset);
  20815. layeroffset += contour.length;
  20816. for (let h = 0, hl = holes.length; h < hl; h++) {
  20817. const ahole = holes[h];
  20818. sidewalls(ahole, layeroffset); //, true
  20819. layeroffset += ahole.length;
  20820. }
  20821. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20822. }
  20823. function sidewalls(contour, layeroffset) {
  20824. let i = contour.length;
  20825. while (--i >= 0) {
  20826. const j = i;
  20827. let k = i - 1;
  20828. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20829. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20830. const slen1 = vlen * s;
  20831. const slen2 = vlen * (s + 1);
  20832. const a = layeroffset + j + slen1,
  20833. b = layeroffset + k + slen1,
  20834. c = layeroffset + k + slen2,
  20835. d = layeroffset + j + slen2;
  20836. f4(a, b, c, d);
  20837. }
  20838. }
  20839. }
  20840. function v(x, y, z) {
  20841. placeholder.push(x);
  20842. placeholder.push(y);
  20843. placeholder.push(z);
  20844. }
  20845. function f3(a, b, c) {
  20846. addVertex(a);
  20847. addVertex(b);
  20848. addVertex(c);
  20849. const nextIndex = verticesArray.length / 3;
  20850. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20851. addUV(uvs[0]);
  20852. addUV(uvs[1]);
  20853. addUV(uvs[2]);
  20854. }
  20855. function f4(a, b, c, d) {
  20856. addVertex(a);
  20857. addVertex(b);
  20858. addVertex(d);
  20859. addVertex(b);
  20860. addVertex(c);
  20861. addVertex(d);
  20862. const nextIndex = verticesArray.length / 3;
  20863. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20864. addUV(uvs[0]);
  20865. addUV(uvs[1]);
  20866. addUV(uvs[3]);
  20867. addUV(uvs[1]);
  20868. addUV(uvs[2]);
  20869. addUV(uvs[3]);
  20870. }
  20871. function addVertex(index) {
  20872. verticesArray.push(placeholder[index * 3 + 0]);
  20873. verticesArray.push(placeholder[index * 3 + 1]);
  20874. verticesArray.push(placeholder[index * 3 + 2]);
  20875. }
  20876. function addUV(vector2) {
  20877. uvArray.push(vector2.x);
  20878. uvArray.push(vector2.y);
  20879. }
  20880. }
  20881. }
  20882. toJSON() {
  20883. const data = super.toJSON();
  20884. const shapes = this.parameters.shapes;
  20885. const options = this.parameters.options;
  20886. return toJSON$1(shapes, options, data);
  20887. }
  20888. static fromJSON(data, shapes) {
  20889. const geometryShapes = [];
  20890. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20891. const shape = shapes[data.shapes[j]];
  20892. geometryShapes.push(shape);
  20893. }
  20894. const extrudePath = data.options.extrudePath;
  20895. if (extrudePath !== undefined) {
  20896. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20897. }
  20898. return new ExtrudeGeometry(geometryShapes, data.options);
  20899. }
  20900. }
  20901. const WorldUVGenerator = {
  20902. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20903. const a_x = vertices[indexA * 3];
  20904. const a_y = vertices[indexA * 3 + 1];
  20905. const b_x = vertices[indexB * 3];
  20906. const b_y = vertices[indexB * 3 + 1];
  20907. const c_x = vertices[indexC * 3];
  20908. const c_y = vertices[indexC * 3 + 1];
  20909. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20910. },
  20911. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20912. const a_x = vertices[indexA * 3];
  20913. const a_y = vertices[indexA * 3 + 1];
  20914. const a_z = vertices[indexA * 3 + 2];
  20915. const b_x = vertices[indexB * 3];
  20916. const b_y = vertices[indexB * 3 + 1];
  20917. const b_z = vertices[indexB * 3 + 2];
  20918. const c_x = vertices[indexC * 3];
  20919. const c_y = vertices[indexC * 3 + 1];
  20920. const c_z = vertices[indexC * 3 + 2];
  20921. const d_x = vertices[indexD * 3];
  20922. const d_y = vertices[indexD * 3 + 1];
  20923. const d_z = vertices[indexD * 3 + 2];
  20924. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20925. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  20926. } else {
  20927. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  20928. }
  20929. }
  20930. };
  20931. function toJSON$1(shapes, options, data) {
  20932. data.shapes = [];
  20933. if (Array.isArray(shapes)) {
  20934. for (let i = 0, l = shapes.length; i < l; i++) {
  20935. const shape = shapes[i];
  20936. data.shapes.push(shape.uuid);
  20937. }
  20938. } else {
  20939. data.shapes.push(shapes.uuid);
  20940. }
  20941. data.options = Object.assign({}, options);
  20942. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20943. return data;
  20944. }
  20945. class IcosahedronGeometry extends PolyhedronGeometry {
  20946. constructor(radius = 1, detail = 0) {
  20947. const t = (1 + Math.sqrt(5)) / 2;
  20948. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  20949. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  20950. super(vertices, indices, radius, detail);
  20951. this.type = 'IcosahedronGeometry';
  20952. this.parameters = {
  20953. radius: radius,
  20954. detail: detail
  20955. };
  20956. }
  20957. static fromJSON(data) {
  20958. return new IcosahedronGeometry(data.radius, data.detail);
  20959. }
  20960. }
  20961. class OctahedronGeometry extends PolyhedronGeometry {
  20962. constructor(radius = 1, detail = 0) {
  20963. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20964. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  20965. super(vertices, indices, radius, detail);
  20966. this.type = 'OctahedronGeometry';
  20967. this.parameters = {
  20968. radius: radius,
  20969. detail: detail
  20970. };
  20971. }
  20972. static fromJSON(data) {
  20973. return new OctahedronGeometry(data.radius, data.detail);
  20974. }
  20975. }
  20976. class RingGeometry extends BufferGeometry {
  20977. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20978. super();
  20979. this.type = 'RingGeometry';
  20980. this.parameters = {
  20981. innerRadius: innerRadius,
  20982. outerRadius: outerRadius,
  20983. thetaSegments: thetaSegments,
  20984. phiSegments: phiSegments,
  20985. thetaStart: thetaStart,
  20986. thetaLength: thetaLength
  20987. };
  20988. thetaSegments = Math.max(3, thetaSegments);
  20989. phiSegments = Math.max(1, phiSegments); // buffers
  20990. const indices = [];
  20991. const vertices = [];
  20992. const normals = [];
  20993. const uvs = []; // some helper variables
  20994. let radius = innerRadius;
  20995. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20996. const vertex = new Vector3();
  20997. const uv = new Vector2(); // generate vertices, normals and uvs
  20998. for (let j = 0; j <= phiSegments; j++) {
  20999. for (let i = 0; i <= thetaSegments; i++) {
  21000. // values are generate from the inside of the ring to the outside
  21001. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  21002. vertex.x = radius * Math.cos(segment);
  21003. vertex.y = radius * Math.sin(segment);
  21004. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21005. normals.push(0, 0, 1); // uv
  21006. uv.x = (vertex.x / outerRadius + 1) / 2;
  21007. uv.y = (vertex.y / outerRadius + 1) / 2;
  21008. uvs.push(uv.x, uv.y);
  21009. } // increase the radius for next row of vertices
  21010. radius += radiusStep;
  21011. } // indices
  21012. for (let j = 0; j < phiSegments; j++) {
  21013. const thetaSegmentLevel = j * (thetaSegments + 1);
  21014. for (let i = 0; i < thetaSegments; i++) {
  21015. const segment = i + thetaSegmentLevel;
  21016. const a = segment;
  21017. const b = segment + thetaSegments + 1;
  21018. const c = segment + thetaSegments + 2;
  21019. const d = segment + 1; // faces
  21020. indices.push(a, b, d);
  21021. indices.push(b, c, d);
  21022. }
  21023. } // build geometry
  21024. this.setIndex(indices);
  21025. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21026. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21027. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21028. }
  21029. static fromJSON(data) {
  21030. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  21031. }
  21032. }
  21033. class ShapeGeometry extends BufferGeometry {
  21034. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  21035. super();
  21036. this.type = 'ShapeGeometry';
  21037. this.parameters = {
  21038. shapes: shapes,
  21039. curveSegments: curveSegments
  21040. }; // buffers
  21041. const indices = [];
  21042. const vertices = [];
  21043. const normals = [];
  21044. const uvs = []; // helper variables
  21045. let groupStart = 0;
  21046. let groupCount = 0; // allow single and array values for "shapes" parameter
  21047. if (Array.isArray(shapes) === false) {
  21048. addShape(shapes);
  21049. } else {
  21050. for (let i = 0; i < shapes.length; i++) {
  21051. addShape(shapes[i]);
  21052. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  21053. groupStart += groupCount;
  21054. groupCount = 0;
  21055. }
  21056. } // build geometry
  21057. this.setIndex(indices);
  21058. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21059. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21060. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  21061. function addShape(shape) {
  21062. const indexOffset = vertices.length / 3;
  21063. const points = shape.extractPoints(curveSegments);
  21064. let shapeVertices = points.shape;
  21065. const shapeHoles = points.holes; // check direction of vertices
  21066. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  21067. shapeVertices = shapeVertices.reverse();
  21068. }
  21069. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21070. const shapeHole = shapeHoles[i];
  21071. if (ShapeUtils.isClockWise(shapeHole) === true) {
  21072. shapeHoles[i] = shapeHole.reverse();
  21073. }
  21074. }
  21075. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  21076. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  21077. const shapeHole = shapeHoles[i];
  21078. shapeVertices = shapeVertices.concat(shapeHole);
  21079. } // vertices, normals, uvs
  21080. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  21081. const vertex = shapeVertices[i];
  21082. vertices.push(vertex.x, vertex.y, 0);
  21083. normals.push(0, 0, 1);
  21084. uvs.push(vertex.x, vertex.y); // world uvs
  21085. } // incides
  21086. for (let i = 0, l = faces.length; i < l; i++) {
  21087. const face = faces[i];
  21088. const a = face[0] + indexOffset;
  21089. const b = face[1] + indexOffset;
  21090. const c = face[2] + indexOffset;
  21091. indices.push(a, b, c);
  21092. groupCount += 3;
  21093. }
  21094. }
  21095. }
  21096. toJSON() {
  21097. const data = super.toJSON();
  21098. const shapes = this.parameters.shapes;
  21099. return toJSON(shapes, data);
  21100. }
  21101. static fromJSON(data, shapes) {
  21102. const geometryShapes = [];
  21103. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  21104. const shape = shapes[data.shapes[j]];
  21105. geometryShapes.push(shape);
  21106. }
  21107. return new ShapeGeometry(geometryShapes, data.curveSegments);
  21108. }
  21109. }
  21110. function toJSON(shapes, data) {
  21111. data.shapes = [];
  21112. if (Array.isArray(shapes)) {
  21113. for (let i = 0, l = shapes.length; i < l; i++) {
  21114. const shape = shapes[i];
  21115. data.shapes.push(shape.uuid);
  21116. }
  21117. } else {
  21118. data.shapes.push(shapes.uuid);
  21119. }
  21120. return data;
  21121. }
  21122. class SphereGeometry extends BufferGeometry {
  21123. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  21124. super();
  21125. this.type = 'SphereGeometry';
  21126. this.parameters = {
  21127. radius: radius,
  21128. widthSegments: widthSegments,
  21129. heightSegments: heightSegments,
  21130. phiStart: phiStart,
  21131. phiLength: phiLength,
  21132. thetaStart: thetaStart,
  21133. thetaLength: thetaLength
  21134. };
  21135. widthSegments = Math.max(3, Math.floor(widthSegments));
  21136. heightSegments = Math.max(2, Math.floor(heightSegments));
  21137. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  21138. let index = 0;
  21139. const grid = [];
  21140. const vertex = new Vector3();
  21141. const normal = new Vector3(); // buffers
  21142. const indices = [];
  21143. const vertices = [];
  21144. const normals = [];
  21145. const uvs = []; // generate vertices, normals and uvs
  21146. for (let iy = 0; iy <= heightSegments; iy++) {
  21147. const verticesRow = [];
  21148. const v = iy / heightSegments; // special case for the poles
  21149. let uOffset = 0;
  21150. if (iy == 0 && thetaStart == 0) {
  21151. uOffset = 0.5 / widthSegments;
  21152. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  21153. uOffset = -0.5 / widthSegments;
  21154. }
  21155. for (let ix = 0; ix <= widthSegments; ix++) {
  21156. const u = ix / widthSegments; // vertex
  21157. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21158. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  21159. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  21160. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21161. normal.copy(vertex).normalize();
  21162. normals.push(normal.x, normal.y, normal.z); // uv
  21163. uvs.push(u + uOffset, 1 - v);
  21164. verticesRow.push(index++);
  21165. }
  21166. grid.push(verticesRow);
  21167. } // indices
  21168. for (let iy = 0; iy < heightSegments; iy++) {
  21169. for (let ix = 0; ix < widthSegments; ix++) {
  21170. const a = grid[iy][ix + 1];
  21171. const b = grid[iy][ix];
  21172. const c = grid[iy + 1][ix];
  21173. const d = grid[iy + 1][ix + 1];
  21174. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  21175. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  21176. }
  21177. } // build geometry
  21178. this.setIndex(indices);
  21179. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21180. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21181. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21182. }
  21183. static fromJSON(data) {
  21184. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  21185. }
  21186. }
  21187. class TetrahedronGeometry extends PolyhedronGeometry {
  21188. constructor(radius = 1, detail = 0) {
  21189. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  21190. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  21191. super(vertices, indices, radius, detail);
  21192. this.type = 'TetrahedronGeometry';
  21193. this.parameters = {
  21194. radius: radius,
  21195. detail: detail
  21196. };
  21197. }
  21198. static fromJSON(data) {
  21199. return new TetrahedronGeometry(data.radius, data.detail);
  21200. }
  21201. }
  21202. class TorusGeometry extends BufferGeometry {
  21203. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  21204. super();
  21205. this.type = 'TorusGeometry';
  21206. this.parameters = {
  21207. radius: radius,
  21208. tube: tube,
  21209. radialSegments: radialSegments,
  21210. tubularSegments: tubularSegments,
  21211. arc: arc
  21212. };
  21213. radialSegments = Math.floor(radialSegments);
  21214. tubularSegments = Math.floor(tubularSegments); // buffers
  21215. const indices = [];
  21216. const vertices = [];
  21217. const normals = [];
  21218. const uvs = []; // helper variables
  21219. const center = new Vector3();
  21220. const vertex = new Vector3();
  21221. const normal = new Vector3(); // generate vertices, normals and uvs
  21222. for (let j = 0; j <= radialSegments; j++) {
  21223. for (let i = 0; i <= tubularSegments; i++) {
  21224. const u = i / tubularSegments * arc;
  21225. const v = j / radialSegments * Math.PI * 2; // vertex
  21226. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  21227. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  21228. vertex.z = tube * Math.sin(v);
  21229. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  21230. center.x = radius * Math.cos(u);
  21231. center.y = radius * Math.sin(u);
  21232. normal.subVectors(vertex, center).normalize();
  21233. normals.push(normal.x, normal.y, normal.z); // uv
  21234. uvs.push(i / tubularSegments);
  21235. uvs.push(j / radialSegments);
  21236. }
  21237. } // generate indices
  21238. for (let j = 1; j <= radialSegments; j++) {
  21239. for (let i = 1; i <= tubularSegments; i++) {
  21240. // indices
  21241. const a = (tubularSegments + 1) * j + i - 1;
  21242. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  21243. const c = (tubularSegments + 1) * (j - 1) + i;
  21244. const d = (tubularSegments + 1) * j + i; // faces
  21245. indices.push(a, b, d);
  21246. indices.push(b, c, d);
  21247. }
  21248. } // build geometry
  21249. this.setIndex(indices);
  21250. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21251. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21252. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  21253. }
  21254. static fromJSON(data) {
  21255. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  21256. }
  21257. }
  21258. class TorusKnotGeometry extends BufferGeometry {
  21259. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  21260. super();
  21261. this.type = 'TorusKnotGeometry';
  21262. this.parameters = {
  21263. radius: radius,
  21264. tube: tube,
  21265. tubularSegments: tubularSegments,
  21266. radialSegments: radialSegments,
  21267. p: p,
  21268. q: q
  21269. };
  21270. tubularSegments = Math.floor(tubularSegments);
  21271. radialSegments = Math.floor(radialSegments); // buffers
  21272. const indices = [];
  21273. const vertices = [];
  21274. const normals = [];
  21275. const uvs = []; // helper variables
  21276. const vertex = new Vector3();
  21277. const normal = new Vector3();
  21278. const P1 = new Vector3();
  21279. const P2 = new Vector3();
  21280. const B = new Vector3();
  21281. const T = new Vector3();
  21282. const N = new Vector3(); // generate vertices, normals and uvs
  21283. for (let i = 0; i <= tubularSegments; ++i) {
  21284. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21285. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21286. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21287. calculatePositionOnCurve(u, p, q, radius, P1);
  21288. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  21289. T.subVectors(P2, P1);
  21290. N.addVectors(P2, P1);
  21291. B.crossVectors(T, N);
  21292. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  21293. B.normalize();
  21294. N.normalize();
  21295. for (let j = 0; j <= radialSegments; ++j) {
  21296. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21297. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21298. const v = j / radialSegments * Math.PI * 2;
  21299. const cx = -tube * Math.cos(v);
  21300. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  21301. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21302. vertex.x = P1.x + (cx * N.x + cy * B.x);
  21303. vertex.y = P1.y + (cx * N.y + cy * B.y);
  21304. vertex.z = P1.z + (cx * N.z + cy * B.z);
  21305. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21306. normal.subVectors(vertex, P1).normalize();
  21307. normals.push(normal.x, normal.y, normal.z); // uv
  21308. uvs.push(i / tubularSegments);
  21309. uvs.push(j / radialSegments);
  21310. }
  21311. } // generate indices
  21312. for (let j = 1; j <= tubularSegments; j++) {
  21313. for (let i = 1; i <= radialSegments; i++) {
  21314. // indices
  21315. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21316. const b = (radialSegments + 1) * j + (i - 1);
  21317. const c = (radialSegments + 1) * j + i;
  21318. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21319. indices.push(a, b, d);
  21320. indices.push(b, c, d);
  21321. }
  21322. } // build geometry
  21323. this.setIndex(indices);
  21324. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21325. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21326. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  21327. function calculatePositionOnCurve(u, p, q, radius, position) {
  21328. const cu = Math.cos(u);
  21329. const su = Math.sin(u);
  21330. const quOverP = q / p * u;
  21331. const cs = Math.cos(quOverP);
  21332. position.x = radius * (2 + cs) * 0.5 * cu;
  21333. position.y = radius * (2 + cs) * su * 0.5;
  21334. position.z = radius * Math.sin(quOverP) * 0.5;
  21335. }
  21336. }
  21337. static fromJSON(data) {
  21338. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  21339. }
  21340. }
  21341. class TubeGeometry extends BufferGeometry {
  21342. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  21343. super();
  21344. this.type = 'TubeGeometry';
  21345. this.parameters = {
  21346. path: path,
  21347. tubularSegments: tubularSegments,
  21348. radius: radius,
  21349. radialSegments: radialSegments,
  21350. closed: closed
  21351. };
  21352. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  21353. this.tangents = frames.tangents;
  21354. this.normals = frames.normals;
  21355. this.binormals = frames.binormals; // helper variables
  21356. const vertex = new Vector3();
  21357. const normal = new Vector3();
  21358. const uv = new Vector2();
  21359. let P = new Vector3(); // buffer
  21360. const vertices = [];
  21361. const normals = [];
  21362. const uvs = [];
  21363. const indices = []; // create buffer data
  21364. generateBufferData(); // build geometry
  21365. this.setIndex(indices);
  21366. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21367. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21368. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  21369. function generateBufferData() {
  21370. for (let i = 0; i < tubularSegments; i++) {
  21371. generateSegment(i);
  21372. } // if the geometry is not closed, generate the last row of vertices and normals
  21373. // at the regular position on the given path
  21374. //
  21375. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21376. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  21377. // this makes it easy compute correct values for closed geometries
  21378. generateUVs(); // finally create faces
  21379. generateIndices();
  21380. }
  21381. function generateSegment(i) {
  21382. // we use getPointAt to sample evenly distributed points from the given path
  21383. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  21384. const N = frames.normals[i];
  21385. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  21386. for (let j = 0; j <= radialSegments; j++) {
  21387. const v = j / radialSegments * Math.PI * 2;
  21388. const sin = Math.sin(v);
  21389. const cos = -Math.cos(v); // normal
  21390. normal.x = cos * N.x + sin * B.x;
  21391. normal.y = cos * N.y + sin * B.y;
  21392. normal.z = cos * N.z + sin * B.z;
  21393. normal.normalize();
  21394. normals.push(normal.x, normal.y, normal.z); // vertex
  21395. vertex.x = P.x + radius * normal.x;
  21396. vertex.y = P.y + radius * normal.y;
  21397. vertex.z = P.z + radius * normal.z;
  21398. vertices.push(vertex.x, vertex.y, vertex.z);
  21399. }
  21400. }
  21401. function generateIndices() {
  21402. for (let j = 1; j <= tubularSegments; j++) {
  21403. for (let i = 1; i <= radialSegments; i++) {
  21404. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21405. const b = (radialSegments + 1) * j + (i - 1);
  21406. const c = (radialSegments + 1) * j + i;
  21407. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21408. indices.push(a, b, d);
  21409. indices.push(b, c, d);
  21410. }
  21411. }
  21412. }
  21413. function generateUVs() {
  21414. for (let i = 0; i <= tubularSegments; i++) {
  21415. for (let j = 0; j <= radialSegments; j++) {
  21416. uv.x = i / tubularSegments;
  21417. uv.y = j / radialSegments;
  21418. uvs.push(uv.x, uv.y);
  21419. }
  21420. }
  21421. }
  21422. }
  21423. toJSON() {
  21424. const data = super.toJSON();
  21425. data.path = this.parameters.path.toJSON();
  21426. return data;
  21427. }
  21428. static fromJSON(data) {
  21429. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21430. // User defined curves or instances of CurvePath will not be deserialized.
  21431. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  21432. }
  21433. }
  21434. class WireframeGeometry extends BufferGeometry {
  21435. constructor(geometry = null) {
  21436. super();
  21437. this.type = 'WireframeGeometry';
  21438. this.parameters = {
  21439. geometry: geometry
  21440. };
  21441. if (geometry !== null) {
  21442. // buffer
  21443. const vertices = [];
  21444. const edges = new Set(); // helper variables
  21445. const start = new Vector3();
  21446. const end = new Vector3();
  21447. if (geometry.index !== null) {
  21448. // indexed BufferGeometry
  21449. const position = geometry.attributes.position;
  21450. const indices = geometry.index;
  21451. let groups = geometry.groups;
  21452. if (groups.length === 0) {
  21453. groups = [{
  21454. start: 0,
  21455. count: indices.count,
  21456. materialIndex: 0
  21457. }];
  21458. } // create a data structure that contains all edges without duplicates
  21459. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21460. const group = groups[o];
  21461. const groupStart = group.start;
  21462. const groupCount = group.count;
  21463. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21464. for (let j = 0; j < 3; j++) {
  21465. const index1 = indices.getX(i + j);
  21466. const index2 = indices.getX(i + (j + 1) % 3);
  21467. start.fromBufferAttribute(position, index1);
  21468. end.fromBufferAttribute(position, index2);
  21469. if (isUniqueEdge(start, end, edges) === true) {
  21470. vertices.push(start.x, start.y, start.z);
  21471. vertices.push(end.x, end.y, end.z);
  21472. }
  21473. }
  21474. }
  21475. }
  21476. } else {
  21477. // non-indexed BufferGeometry
  21478. const position = geometry.attributes.position;
  21479. for (let i = 0, l = position.count / 3; i < l; i++) {
  21480. for (let j = 0; j < 3; j++) {
  21481. // three edges per triangle, an edge is represented as (index1, index2)
  21482. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21483. const index1 = 3 * i + j;
  21484. const index2 = 3 * i + (j + 1) % 3;
  21485. start.fromBufferAttribute(position, index1);
  21486. end.fromBufferAttribute(position, index2);
  21487. if (isUniqueEdge(start, end, edges) === true) {
  21488. vertices.push(start.x, start.y, start.z);
  21489. vertices.push(end.x, end.y, end.z);
  21490. }
  21491. }
  21492. }
  21493. } // build geometry
  21494. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21495. }
  21496. }
  21497. }
  21498. function isUniqueEdge(start, end, edges) {
  21499. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21500. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21501. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21502. return false;
  21503. } else {
  21504. edges.add(hash1);
  21505. edges.add(hash2);
  21506. return true;
  21507. }
  21508. }
  21509. var Geometries = /*#__PURE__*/Object.freeze({
  21510. __proto__: null,
  21511. BoxGeometry: BoxGeometry,
  21512. CapsuleGeometry: CapsuleGeometry,
  21513. CircleGeometry: CircleGeometry,
  21514. ConeGeometry: ConeGeometry,
  21515. CylinderGeometry: CylinderGeometry,
  21516. DodecahedronGeometry: DodecahedronGeometry,
  21517. EdgesGeometry: EdgesGeometry,
  21518. ExtrudeGeometry: ExtrudeGeometry,
  21519. IcosahedronGeometry: IcosahedronGeometry,
  21520. LatheGeometry: LatheGeometry,
  21521. OctahedronGeometry: OctahedronGeometry,
  21522. PlaneGeometry: PlaneGeometry,
  21523. PolyhedronGeometry: PolyhedronGeometry,
  21524. RingGeometry: RingGeometry,
  21525. ShapeGeometry: ShapeGeometry,
  21526. SphereGeometry: SphereGeometry,
  21527. TetrahedronGeometry: TetrahedronGeometry,
  21528. TorusGeometry: TorusGeometry,
  21529. TorusKnotGeometry: TorusKnotGeometry,
  21530. TubeGeometry: TubeGeometry,
  21531. WireframeGeometry: WireframeGeometry
  21532. });
  21533. class ShadowMaterial extends Material {
  21534. constructor(parameters) {
  21535. super();
  21536. this.isShadowMaterial = true;
  21537. this.type = 'ShadowMaterial';
  21538. this.color = new Color(0x000000);
  21539. this.transparent = true;
  21540. this.fog = true;
  21541. this.setValues(parameters);
  21542. }
  21543. copy(source) {
  21544. super.copy(source);
  21545. this.color.copy(source.color);
  21546. this.fog = source.fog;
  21547. return this;
  21548. }
  21549. }
  21550. class RawShaderMaterial extends ShaderMaterial {
  21551. constructor(parameters) {
  21552. super(parameters);
  21553. this.isRawShaderMaterial = true;
  21554. this.type = 'RawShaderMaterial';
  21555. }
  21556. }
  21557. class MeshStandardMaterial extends Material {
  21558. constructor(parameters) {
  21559. super();
  21560. this.isMeshStandardMaterial = true;
  21561. this.defines = {
  21562. 'STANDARD': ''
  21563. };
  21564. this.type = 'MeshStandardMaterial';
  21565. this.color = new Color(0xffffff); // diffuse
  21566. this.roughness = 1.0;
  21567. this.metalness = 0.0;
  21568. this.map = null;
  21569. this.lightMap = null;
  21570. this.lightMapIntensity = 1.0;
  21571. this.aoMap = null;
  21572. this.aoMapIntensity = 1.0;
  21573. this.emissive = new Color(0x000000);
  21574. this.emissiveIntensity = 1.0;
  21575. this.emissiveMap = null;
  21576. this.bumpMap = null;
  21577. this.bumpScale = 1;
  21578. this.normalMap = null;
  21579. this.normalMapType = TangentSpaceNormalMap;
  21580. this.normalScale = new Vector2(1, 1);
  21581. this.displacementMap = null;
  21582. this.displacementScale = 1;
  21583. this.displacementBias = 0;
  21584. this.roughnessMap = null;
  21585. this.metalnessMap = null;
  21586. this.alphaMap = null;
  21587. this.envMap = null;
  21588. this.envMapIntensity = 1.0;
  21589. this.wireframe = false;
  21590. this.wireframeLinewidth = 1;
  21591. this.wireframeLinecap = 'round';
  21592. this.wireframeLinejoin = 'round';
  21593. this.flatShading = false;
  21594. this.fog = true;
  21595. this.setValues(parameters);
  21596. }
  21597. copy(source) {
  21598. super.copy(source);
  21599. this.defines = {
  21600. 'STANDARD': ''
  21601. };
  21602. this.color.copy(source.color);
  21603. this.roughness = source.roughness;
  21604. this.metalness = source.metalness;
  21605. this.map = source.map;
  21606. this.lightMap = source.lightMap;
  21607. this.lightMapIntensity = source.lightMapIntensity;
  21608. this.aoMap = source.aoMap;
  21609. this.aoMapIntensity = source.aoMapIntensity;
  21610. this.emissive.copy(source.emissive);
  21611. this.emissiveMap = source.emissiveMap;
  21612. this.emissiveIntensity = source.emissiveIntensity;
  21613. this.bumpMap = source.bumpMap;
  21614. this.bumpScale = source.bumpScale;
  21615. this.normalMap = source.normalMap;
  21616. this.normalMapType = source.normalMapType;
  21617. this.normalScale.copy(source.normalScale);
  21618. this.displacementMap = source.displacementMap;
  21619. this.displacementScale = source.displacementScale;
  21620. this.displacementBias = source.displacementBias;
  21621. this.roughnessMap = source.roughnessMap;
  21622. this.metalnessMap = source.metalnessMap;
  21623. this.alphaMap = source.alphaMap;
  21624. this.envMap = source.envMap;
  21625. this.envMapIntensity = source.envMapIntensity;
  21626. this.wireframe = source.wireframe;
  21627. this.wireframeLinewidth = source.wireframeLinewidth;
  21628. this.wireframeLinecap = source.wireframeLinecap;
  21629. this.wireframeLinejoin = source.wireframeLinejoin;
  21630. this.flatShading = source.flatShading;
  21631. this.fog = source.fog;
  21632. return this;
  21633. }
  21634. }
  21635. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21636. constructor(parameters) {
  21637. super();
  21638. this.isMeshPhysicalMaterial = true;
  21639. this.defines = {
  21640. 'STANDARD': '',
  21641. 'PHYSICAL': ''
  21642. };
  21643. this.type = 'MeshPhysicalMaterial';
  21644. this.clearcoatMap = null;
  21645. this.clearcoatRoughness = 0.0;
  21646. this.clearcoatRoughnessMap = null;
  21647. this.clearcoatNormalScale = new Vector2(1, 1);
  21648. this.clearcoatNormalMap = null;
  21649. this.ior = 1.5;
  21650. Object.defineProperty(this, 'reflectivity', {
  21651. get: function () {
  21652. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21653. },
  21654. set: function (reflectivity) {
  21655. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21656. }
  21657. });
  21658. this.iridescenceMap = null;
  21659. this.iridescenceIOR = 1.3;
  21660. this.iridescenceThicknessRange = [100, 400];
  21661. this.iridescenceThicknessMap = null;
  21662. this.sheenColor = new Color(0x000000);
  21663. this.sheenColorMap = null;
  21664. this.sheenRoughness = 1.0;
  21665. this.sheenRoughnessMap = null;
  21666. this.transmissionMap = null;
  21667. this.thickness = 0;
  21668. this.thicknessMap = null;
  21669. this.attenuationDistance = 0.0;
  21670. this.attenuationColor = new Color(1, 1, 1);
  21671. this.specularIntensity = 1.0;
  21672. this.specularIntensityMap = null;
  21673. this.specularColor = new Color(1, 1, 1);
  21674. this.specularColorMap = null;
  21675. this._sheen = 0.0;
  21676. this._clearcoat = 0;
  21677. this._iridescence = 0;
  21678. this._transmission = 0;
  21679. this.setValues(parameters);
  21680. }
  21681. get sheen() {
  21682. return this._sheen;
  21683. }
  21684. set sheen(value) {
  21685. if (this._sheen > 0 !== value > 0) {
  21686. this.version++;
  21687. }
  21688. this._sheen = value;
  21689. }
  21690. get clearcoat() {
  21691. return this._clearcoat;
  21692. }
  21693. set clearcoat(value) {
  21694. if (this._clearcoat > 0 !== value > 0) {
  21695. this.version++;
  21696. }
  21697. this._clearcoat = value;
  21698. }
  21699. get iridescence() {
  21700. return this._iridescence;
  21701. }
  21702. set iridescence(value) {
  21703. if (this._iridescence > 0 !== value > 0) {
  21704. this.version++;
  21705. }
  21706. this._iridescence = value;
  21707. }
  21708. get transmission() {
  21709. return this._transmission;
  21710. }
  21711. set transmission(value) {
  21712. if (this._transmission > 0 !== value > 0) {
  21713. this.version++;
  21714. }
  21715. this._transmission = value;
  21716. }
  21717. copy(source) {
  21718. super.copy(source);
  21719. this.defines = {
  21720. 'STANDARD': '',
  21721. 'PHYSICAL': ''
  21722. };
  21723. this.clearcoat = source.clearcoat;
  21724. this.clearcoatMap = source.clearcoatMap;
  21725. this.clearcoatRoughness = source.clearcoatRoughness;
  21726. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21727. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21728. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21729. this.ior = source.ior;
  21730. this.iridescence = source.iridescence;
  21731. this.iridescenceMap = source.iridescenceMap;
  21732. this.iridescenceIOR = source.iridescenceIOR;
  21733. this.iridescenceThicknessRange = [...source.iridescenceThicknessRange];
  21734. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  21735. this.sheen = source.sheen;
  21736. this.sheenColor.copy(source.sheenColor);
  21737. this.sheenColorMap = source.sheenColorMap;
  21738. this.sheenRoughness = source.sheenRoughness;
  21739. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21740. this.transmission = source.transmission;
  21741. this.transmissionMap = source.transmissionMap;
  21742. this.thickness = source.thickness;
  21743. this.thicknessMap = source.thicknessMap;
  21744. this.attenuationDistance = source.attenuationDistance;
  21745. this.attenuationColor.copy(source.attenuationColor);
  21746. this.specularIntensity = source.specularIntensity;
  21747. this.specularIntensityMap = source.specularIntensityMap;
  21748. this.specularColor.copy(source.specularColor);
  21749. this.specularColorMap = source.specularColorMap;
  21750. return this;
  21751. }
  21752. }
  21753. class MeshPhongMaterial extends Material {
  21754. constructor(parameters) {
  21755. super();
  21756. this.isMeshPhongMaterial = true;
  21757. this.type = 'MeshPhongMaterial';
  21758. this.color = new Color(0xffffff); // diffuse
  21759. this.specular = new Color(0x111111);
  21760. this.shininess = 30;
  21761. this.map = null;
  21762. this.lightMap = null;
  21763. this.lightMapIntensity = 1.0;
  21764. this.aoMap = null;
  21765. this.aoMapIntensity = 1.0;
  21766. this.emissive = new Color(0x000000);
  21767. this.emissiveIntensity = 1.0;
  21768. this.emissiveMap = null;
  21769. this.bumpMap = null;
  21770. this.bumpScale = 1;
  21771. this.normalMap = null;
  21772. this.normalMapType = TangentSpaceNormalMap;
  21773. this.normalScale = new Vector2(1, 1);
  21774. this.displacementMap = null;
  21775. this.displacementScale = 1;
  21776. this.displacementBias = 0;
  21777. this.specularMap = null;
  21778. this.alphaMap = null;
  21779. this.envMap = null;
  21780. this.combine = MultiplyOperation;
  21781. this.reflectivity = 1;
  21782. this.refractionRatio = 0.98;
  21783. this.wireframe = false;
  21784. this.wireframeLinewidth = 1;
  21785. this.wireframeLinecap = 'round';
  21786. this.wireframeLinejoin = 'round';
  21787. this.flatShading = false;
  21788. this.fog = true;
  21789. this.setValues(parameters);
  21790. }
  21791. copy(source) {
  21792. super.copy(source);
  21793. this.color.copy(source.color);
  21794. this.specular.copy(source.specular);
  21795. this.shininess = source.shininess;
  21796. this.map = source.map;
  21797. this.lightMap = source.lightMap;
  21798. this.lightMapIntensity = source.lightMapIntensity;
  21799. this.aoMap = source.aoMap;
  21800. this.aoMapIntensity = source.aoMapIntensity;
  21801. this.emissive.copy(source.emissive);
  21802. this.emissiveMap = source.emissiveMap;
  21803. this.emissiveIntensity = source.emissiveIntensity;
  21804. this.bumpMap = source.bumpMap;
  21805. this.bumpScale = source.bumpScale;
  21806. this.normalMap = source.normalMap;
  21807. this.normalMapType = source.normalMapType;
  21808. this.normalScale.copy(source.normalScale);
  21809. this.displacementMap = source.displacementMap;
  21810. this.displacementScale = source.displacementScale;
  21811. this.displacementBias = source.displacementBias;
  21812. this.specularMap = source.specularMap;
  21813. this.alphaMap = source.alphaMap;
  21814. this.envMap = source.envMap;
  21815. this.combine = source.combine;
  21816. this.reflectivity = source.reflectivity;
  21817. this.refractionRatio = source.refractionRatio;
  21818. this.wireframe = source.wireframe;
  21819. this.wireframeLinewidth = source.wireframeLinewidth;
  21820. this.wireframeLinecap = source.wireframeLinecap;
  21821. this.wireframeLinejoin = source.wireframeLinejoin;
  21822. this.flatShading = source.flatShading;
  21823. this.fog = source.fog;
  21824. return this;
  21825. }
  21826. }
  21827. class MeshToonMaterial extends Material {
  21828. constructor(parameters) {
  21829. super();
  21830. this.isMeshToonMaterial = true;
  21831. this.defines = {
  21832. 'TOON': ''
  21833. };
  21834. this.type = 'MeshToonMaterial';
  21835. this.color = new Color(0xffffff);
  21836. this.map = null;
  21837. this.gradientMap = null;
  21838. this.lightMap = null;
  21839. this.lightMapIntensity = 1.0;
  21840. this.aoMap = null;
  21841. this.aoMapIntensity = 1.0;
  21842. this.emissive = new Color(0x000000);
  21843. this.emissiveIntensity = 1.0;
  21844. this.emissiveMap = null;
  21845. this.bumpMap = null;
  21846. this.bumpScale = 1;
  21847. this.normalMap = null;
  21848. this.normalMapType = TangentSpaceNormalMap;
  21849. this.normalScale = new Vector2(1, 1);
  21850. this.displacementMap = null;
  21851. this.displacementScale = 1;
  21852. this.displacementBias = 0;
  21853. this.alphaMap = null;
  21854. this.wireframe = false;
  21855. this.wireframeLinewidth = 1;
  21856. this.wireframeLinecap = 'round';
  21857. this.wireframeLinejoin = 'round';
  21858. this.fog = true;
  21859. this.setValues(parameters);
  21860. }
  21861. copy(source) {
  21862. super.copy(source);
  21863. this.color.copy(source.color);
  21864. this.map = source.map;
  21865. this.gradientMap = source.gradientMap;
  21866. this.lightMap = source.lightMap;
  21867. this.lightMapIntensity = source.lightMapIntensity;
  21868. this.aoMap = source.aoMap;
  21869. this.aoMapIntensity = source.aoMapIntensity;
  21870. this.emissive.copy(source.emissive);
  21871. this.emissiveMap = source.emissiveMap;
  21872. this.emissiveIntensity = source.emissiveIntensity;
  21873. this.bumpMap = source.bumpMap;
  21874. this.bumpScale = source.bumpScale;
  21875. this.normalMap = source.normalMap;
  21876. this.normalMapType = source.normalMapType;
  21877. this.normalScale.copy(source.normalScale);
  21878. this.displacementMap = source.displacementMap;
  21879. this.displacementScale = source.displacementScale;
  21880. this.displacementBias = source.displacementBias;
  21881. this.alphaMap = source.alphaMap;
  21882. this.wireframe = source.wireframe;
  21883. this.wireframeLinewidth = source.wireframeLinewidth;
  21884. this.wireframeLinecap = source.wireframeLinecap;
  21885. this.wireframeLinejoin = source.wireframeLinejoin;
  21886. this.fog = source.fog;
  21887. return this;
  21888. }
  21889. }
  21890. class MeshNormalMaterial extends Material {
  21891. constructor(parameters) {
  21892. super();
  21893. this.isMeshNormalMaterial = true;
  21894. this.type = 'MeshNormalMaterial';
  21895. this.bumpMap = null;
  21896. this.bumpScale = 1;
  21897. this.normalMap = null;
  21898. this.normalMapType = TangentSpaceNormalMap;
  21899. this.normalScale = new Vector2(1, 1);
  21900. this.displacementMap = null;
  21901. this.displacementScale = 1;
  21902. this.displacementBias = 0;
  21903. this.wireframe = false;
  21904. this.wireframeLinewidth = 1;
  21905. this.flatShading = false;
  21906. this.setValues(parameters);
  21907. }
  21908. copy(source) {
  21909. super.copy(source);
  21910. this.bumpMap = source.bumpMap;
  21911. this.bumpScale = source.bumpScale;
  21912. this.normalMap = source.normalMap;
  21913. this.normalMapType = source.normalMapType;
  21914. this.normalScale.copy(source.normalScale);
  21915. this.displacementMap = source.displacementMap;
  21916. this.displacementScale = source.displacementScale;
  21917. this.displacementBias = source.displacementBias;
  21918. this.wireframe = source.wireframe;
  21919. this.wireframeLinewidth = source.wireframeLinewidth;
  21920. this.flatShading = source.flatShading;
  21921. return this;
  21922. }
  21923. }
  21924. class MeshLambertMaterial extends Material {
  21925. constructor(parameters) {
  21926. super();
  21927. this.isMeshLambertMaterial = true;
  21928. this.type = 'MeshLambertMaterial';
  21929. this.color = new Color(0xffffff); // diffuse
  21930. this.map = null;
  21931. this.lightMap = null;
  21932. this.lightMapIntensity = 1.0;
  21933. this.aoMap = null;
  21934. this.aoMapIntensity = 1.0;
  21935. this.emissive = new Color(0x000000);
  21936. this.emissiveIntensity = 1.0;
  21937. this.emissiveMap = null;
  21938. this.bumpMap = null;
  21939. this.bumpScale = 1;
  21940. this.normalMap = null;
  21941. this.normalMapType = TangentSpaceNormalMap;
  21942. this.normalScale = new Vector2(1, 1);
  21943. this.displacementMap = null;
  21944. this.displacementScale = 1;
  21945. this.displacementBias = 0;
  21946. this.specularMap = null;
  21947. this.alphaMap = null;
  21948. this.envMap = null;
  21949. this.combine = MultiplyOperation;
  21950. this.reflectivity = 1;
  21951. this.refractionRatio = 0.98;
  21952. this.wireframe = false;
  21953. this.wireframeLinewidth = 1;
  21954. this.wireframeLinecap = 'round';
  21955. this.wireframeLinejoin = 'round';
  21956. this.flatShading = false;
  21957. this.fog = true;
  21958. this.setValues(parameters);
  21959. }
  21960. copy(source) {
  21961. super.copy(source);
  21962. this.color.copy(source.color);
  21963. this.map = source.map;
  21964. this.lightMap = source.lightMap;
  21965. this.lightMapIntensity = source.lightMapIntensity;
  21966. this.aoMap = source.aoMap;
  21967. this.aoMapIntensity = source.aoMapIntensity;
  21968. this.emissive.copy(source.emissive);
  21969. this.emissiveMap = source.emissiveMap;
  21970. this.emissiveIntensity = source.emissiveIntensity;
  21971. this.bumpMap = source.bumpMap;
  21972. this.bumpScale = source.bumpScale;
  21973. this.normalMap = source.normalMap;
  21974. this.normalMapType = source.normalMapType;
  21975. this.normalScale.copy(source.normalScale);
  21976. this.displacementMap = source.displacementMap;
  21977. this.displacementScale = source.displacementScale;
  21978. this.displacementBias = source.displacementBias;
  21979. this.specularMap = source.specularMap;
  21980. this.alphaMap = source.alphaMap;
  21981. this.envMap = source.envMap;
  21982. this.combine = source.combine;
  21983. this.reflectivity = source.reflectivity;
  21984. this.refractionRatio = source.refractionRatio;
  21985. this.wireframe = source.wireframe;
  21986. this.wireframeLinewidth = source.wireframeLinewidth;
  21987. this.wireframeLinecap = source.wireframeLinecap;
  21988. this.wireframeLinejoin = source.wireframeLinejoin;
  21989. this.flatShading = source.flatShading;
  21990. this.fog = source.fog;
  21991. return this;
  21992. }
  21993. }
  21994. class MeshMatcapMaterial extends Material {
  21995. constructor(parameters) {
  21996. super();
  21997. this.isMeshMatcapMaterial = true;
  21998. this.defines = {
  21999. 'MATCAP': ''
  22000. };
  22001. this.type = 'MeshMatcapMaterial';
  22002. this.color = new Color(0xffffff); // diffuse
  22003. this.matcap = null;
  22004. this.map = null;
  22005. this.bumpMap = null;
  22006. this.bumpScale = 1;
  22007. this.normalMap = null;
  22008. this.normalMapType = TangentSpaceNormalMap;
  22009. this.normalScale = new Vector2(1, 1);
  22010. this.displacementMap = null;
  22011. this.displacementScale = 1;
  22012. this.displacementBias = 0;
  22013. this.alphaMap = null;
  22014. this.flatShading = false;
  22015. this.fog = true;
  22016. this.setValues(parameters);
  22017. }
  22018. copy(source) {
  22019. super.copy(source);
  22020. this.defines = {
  22021. 'MATCAP': ''
  22022. };
  22023. this.color.copy(source.color);
  22024. this.matcap = source.matcap;
  22025. this.map = source.map;
  22026. this.bumpMap = source.bumpMap;
  22027. this.bumpScale = source.bumpScale;
  22028. this.normalMap = source.normalMap;
  22029. this.normalMapType = source.normalMapType;
  22030. this.normalScale.copy(source.normalScale);
  22031. this.displacementMap = source.displacementMap;
  22032. this.displacementScale = source.displacementScale;
  22033. this.displacementBias = source.displacementBias;
  22034. this.alphaMap = source.alphaMap;
  22035. this.flatShading = source.flatShading;
  22036. this.fog = source.fog;
  22037. return this;
  22038. }
  22039. }
  22040. class LineDashedMaterial extends LineBasicMaterial {
  22041. constructor(parameters) {
  22042. super();
  22043. this.isLineDashedMaterial = true;
  22044. this.type = 'LineDashedMaterial';
  22045. this.scale = 1;
  22046. this.dashSize = 3;
  22047. this.gapSize = 1;
  22048. this.setValues(parameters);
  22049. }
  22050. copy(source) {
  22051. super.copy(source);
  22052. this.scale = source.scale;
  22053. this.dashSize = source.dashSize;
  22054. this.gapSize = source.gapSize;
  22055. return this;
  22056. }
  22057. }
  22058. function arraySlice(array, from, to) {
  22059. if (isTypedArray(array)) {
  22060. // in ios9 array.subarray(from, undefined) will return empty array
  22061. // but array.subarray(from) or array.subarray(from, len) is correct
  22062. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  22063. }
  22064. return array.slice(from, to);
  22065. } // converts an array to a specific type
  22066. function convertArray(array, type, forceClone) {
  22067. if (!array || // let 'undefined' and 'null' pass
  22068. !forceClone && array.constructor === type) return array;
  22069. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  22070. return new type(array); // create typed array
  22071. }
  22072. return Array.prototype.slice.call(array); // create Array
  22073. }
  22074. function isTypedArray(object) {
  22075. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  22076. } // returns an array by which times and values can be sorted
  22077. function getKeyframeOrder(times) {
  22078. function compareTime(i, j) {
  22079. return times[i] - times[j];
  22080. }
  22081. const n = times.length;
  22082. const result = new Array(n);
  22083. for (let i = 0; i !== n; ++i) result[i] = i;
  22084. result.sort(compareTime);
  22085. return result;
  22086. } // uses the array previously returned by 'getKeyframeOrder' to sort data
  22087. function sortedArray(values, stride, order) {
  22088. const nValues = values.length;
  22089. const result = new values.constructor(nValues);
  22090. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  22091. const srcOffset = order[i] * stride;
  22092. for (let j = 0; j !== stride; ++j) {
  22093. result[dstOffset++] = values[srcOffset + j];
  22094. }
  22095. }
  22096. return result;
  22097. } // function for parsing AOS keyframe formats
  22098. function flattenJSON(jsonKeys, times, values, valuePropertyName) {
  22099. let i = 1,
  22100. key = jsonKeys[0];
  22101. while (key !== undefined && key[valuePropertyName] === undefined) {
  22102. key = jsonKeys[i++];
  22103. }
  22104. if (key === undefined) return; // no data
  22105. let value = key[valuePropertyName];
  22106. if (value === undefined) return; // no data
  22107. if (Array.isArray(value)) {
  22108. do {
  22109. value = key[valuePropertyName];
  22110. if (value !== undefined) {
  22111. times.push(key.time);
  22112. values.push.apply(values, value); // push all elements
  22113. }
  22114. key = jsonKeys[i++];
  22115. } while (key !== undefined);
  22116. } else if (value.toArray !== undefined) {
  22117. // ...assume THREE.Math-ish
  22118. do {
  22119. value = key[valuePropertyName];
  22120. if (value !== undefined) {
  22121. times.push(key.time);
  22122. value.toArray(values, values.length);
  22123. }
  22124. key = jsonKeys[i++];
  22125. } while (key !== undefined);
  22126. } else {
  22127. // otherwise push as-is
  22128. do {
  22129. value = key[valuePropertyName];
  22130. if (value !== undefined) {
  22131. times.push(key.time);
  22132. values.push(value);
  22133. }
  22134. key = jsonKeys[i++];
  22135. } while (key !== undefined);
  22136. }
  22137. }
  22138. function subclip(sourceClip, name, startFrame, endFrame, fps = 30) {
  22139. const clip = sourceClip.clone();
  22140. clip.name = name;
  22141. const tracks = [];
  22142. for (let i = 0; i < clip.tracks.length; ++i) {
  22143. const track = clip.tracks[i];
  22144. const valueSize = track.getValueSize();
  22145. const times = [];
  22146. const values = [];
  22147. for (let j = 0; j < track.times.length; ++j) {
  22148. const frame = track.times[j] * fps;
  22149. if (frame < startFrame || frame >= endFrame) continue;
  22150. times.push(track.times[j]);
  22151. for (let k = 0; k < valueSize; ++k) {
  22152. values.push(track.values[j * valueSize + k]);
  22153. }
  22154. }
  22155. if (times.length === 0) continue;
  22156. track.times = convertArray(times, track.times.constructor);
  22157. track.values = convertArray(values, track.values.constructor);
  22158. tracks.push(track);
  22159. }
  22160. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  22161. let minStartTime = Infinity;
  22162. for (let i = 0; i < clip.tracks.length; ++i) {
  22163. if (minStartTime > clip.tracks[i].times[0]) {
  22164. minStartTime = clip.tracks[i].times[0];
  22165. }
  22166. } // shift all tracks such that clip begins at t=0
  22167. for (let i = 0; i < clip.tracks.length; ++i) {
  22168. clip.tracks[i].shift(-1 * minStartTime);
  22169. }
  22170. clip.resetDuration();
  22171. return clip;
  22172. }
  22173. function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  22174. if (fps <= 0) fps = 30;
  22175. const numTracks = referenceClip.tracks.length;
  22176. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  22177. for (let i = 0; i < numTracks; ++i) {
  22178. const referenceTrack = referenceClip.tracks[i];
  22179. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  22180. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  22181. const targetTrack = targetClip.tracks.find(function (track) {
  22182. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  22183. });
  22184. if (targetTrack === undefined) continue;
  22185. let referenceOffset = 0;
  22186. const referenceValueSize = referenceTrack.getValueSize();
  22187. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22188. referenceOffset = referenceValueSize / 3;
  22189. }
  22190. let targetOffset = 0;
  22191. const targetValueSize = targetTrack.getValueSize();
  22192. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22193. targetOffset = targetValueSize / 3;
  22194. }
  22195. const lastIndex = referenceTrack.times.length - 1;
  22196. let referenceValue; // Find the value to subtract out of the track
  22197. if (referenceTime <= referenceTrack.times[0]) {
  22198. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22199. const startIndex = referenceOffset;
  22200. const endIndex = referenceValueSize - referenceOffset;
  22201. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22202. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  22203. // Reference frame is after the last keyframe, so just use the last keyframe
  22204. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22205. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22206. referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex);
  22207. } else {
  22208. // Interpolate to the reference value
  22209. const interpolant = referenceTrack.createInterpolant();
  22210. const startIndex = referenceOffset;
  22211. const endIndex = referenceValueSize - referenceOffset;
  22212. interpolant.evaluate(referenceTime);
  22213. referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  22214. } // Conjugate the quaternion
  22215. if (referenceTrackType === 'quaternion') {
  22216. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  22217. referenceQuat.toArray(referenceValue);
  22218. } // Subtract the reference value from all of the track values
  22219. const numTimes = targetTrack.times.length;
  22220. for (let j = 0; j < numTimes; ++j) {
  22221. const valueStart = j * targetValueSize + targetOffset;
  22222. if (referenceTrackType === 'quaternion') {
  22223. // Multiply the conjugate for quaternion track types
  22224. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  22225. } else {
  22226. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  22227. for (let k = 0; k < valueEnd; ++k) {
  22228. targetTrack.values[valueStart + k] -= referenceValue[k];
  22229. }
  22230. }
  22231. }
  22232. }
  22233. targetClip.blendMode = AdditiveAnimationBlendMode;
  22234. return targetClip;
  22235. }
  22236. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22237. __proto__: null,
  22238. arraySlice: arraySlice,
  22239. convertArray: convertArray,
  22240. isTypedArray: isTypedArray,
  22241. getKeyframeOrder: getKeyframeOrder,
  22242. sortedArray: sortedArray,
  22243. flattenJSON: flattenJSON,
  22244. subclip: subclip,
  22245. makeClipAdditive: makeClipAdditive
  22246. });
  22247. /**
  22248. * Abstract base class of interpolants over parametric samples.
  22249. *
  22250. * The parameter domain is one dimensional, typically the time or a path
  22251. * along a curve defined by the data.
  22252. *
  22253. * The sample values can have any dimensionality and derived classes may
  22254. * apply special interpretations to the data.
  22255. *
  22256. * This class provides the interval seek in a Template Method, deferring
  22257. * the actual interpolation to derived classes.
  22258. *
  22259. * Time complexity is O(1) for linear access crossing at most two points
  22260. * and O(log N) for random access, where N is the number of positions.
  22261. *
  22262. * References:
  22263. *
  22264. * http://www.oodesign.com/template-method-pattern.html
  22265. *
  22266. */
  22267. class Interpolant {
  22268. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22269. this.parameterPositions = parameterPositions;
  22270. this._cachedIndex = 0;
  22271. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22272. this.sampleValues = sampleValues;
  22273. this.valueSize = sampleSize;
  22274. this.settings = null;
  22275. this.DefaultSettings_ = {};
  22276. }
  22277. evaluate(t) {
  22278. const pp = this.parameterPositions;
  22279. let i1 = this._cachedIndex,
  22280. t1 = pp[i1],
  22281. t0 = pp[i1 - 1];
  22282. validate_interval: {
  22283. seek: {
  22284. let right;
  22285. linear_scan: {
  22286. //- See http://jsperf.com/comparison-to-undefined/3
  22287. //- slower code:
  22288. //-
  22289. //- if ( t >= t1 || t1 === undefined ) {
  22290. forward_scan: if (!(t < t1)) {
  22291. for (let giveUpAt = i1 + 2;;) {
  22292. if (t1 === undefined) {
  22293. if (t < t0) break forward_scan; // after end
  22294. i1 = pp.length;
  22295. this._cachedIndex = i1;
  22296. return this.copySampleValue_(i1 - 1);
  22297. }
  22298. if (i1 === giveUpAt) break; // this loop
  22299. t0 = t1;
  22300. t1 = pp[++i1];
  22301. if (t < t1) {
  22302. // we have arrived at the sought interval
  22303. break seek;
  22304. }
  22305. } // prepare binary search on the right side of the index
  22306. right = pp.length;
  22307. break linear_scan;
  22308. } //- slower code:
  22309. //- if ( t < t0 || t0 === undefined ) {
  22310. if (!(t >= t0)) {
  22311. // looping?
  22312. const t1global = pp[1];
  22313. if (t < t1global) {
  22314. i1 = 2; // + 1, using the scan for the details
  22315. t0 = t1global;
  22316. } // linear reverse scan
  22317. for (let giveUpAt = i1 - 2;;) {
  22318. if (t0 === undefined) {
  22319. // before start
  22320. this._cachedIndex = 0;
  22321. return this.copySampleValue_(0);
  22322. }
  22323. if (i1 === giveUpAt) break; // this loop
  22324. t1 = t0;
  22325. t0 = pp[--i1 - 1];
  22326. if (t >= t0) {
  22327. // we have arrived at the sought interval
  22328. break seek;
  22329. }
  22330. } // prepare binary search on the left side of the index
  22331. right = i1;
  22332. i1 = 0;
  22333. break linear_scan;
  22334. } // the interval is valid
  22335. break validate_interval;
  22336. } // linear scan
  22337. // binary search
  22338. while (i1 < right) {
  22339. const mid = i1 + right >>> 1;
  22340. if (t < pp[mid]) {
  22341. right = mid;
  22342. } else {
  22343. i1 = mid + 1;
  22344. }
  22345. }
  22346. t1 = pp[i1];
  22347. t0 = pp[i1 - 1]; // check boundary cases, again
  22348. if (t0 === undefined) {
  22349. this._cachedIndex = 0;
  22350. return this.copySampleValue_(0);
  22351. }
  22352. if (t1 === undefined) {
  22353. i1 = pp.length;
  22354. this._cachedIndex = i1;
  22355. return this.copySampleValue_(i1 - 1);
  22356. }
  22357. } // seek
  22358. this._cachedIndex = i1;
  22359. this.intervalChanged_(i1, t0, t1);
  22360. } // validate_interval
  22361. return this.interpolate_(i1, t0, t, t1);
  22362. }
  22363. getSettings_() {
  22364. return this.settings || this.DefaultSettings_;
  22365. }
  22366. copySampleValue_(index) {
  22367. // copies a sample value to the result buffer
  22368. const result = this.resultBuffer,
  22369. values = this.sampleValues,
  22370. stride = this.valueSize,
  22371. offset = index * stride;
  22372. for (let i = 0; i !== stride; ++i) {
  22373. result[i] = values[offset + i];
  22374. }
  22375. return result;
  22376. } // Template methods for derived classes:
  22377. interpolate_() {
  22378. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22379. }
  22380. intervalChanged_() {// empty
  22381. }
  22382. }
  22383. /**
  22384. * Fast and simple cubic spline interpolant.
  22385. *
  22386. * It was derived from a Hermitian construction setting the first derivative
  22387. * at each sample position to the linear slope between neighboring positions
  22388. * over their parameter interval.
  22389. */
  22390. class CubicInterpolant extends Interpolant {
  22391. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22392. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22393. this._weightPrev = -0;
  22394. this._offsetPrev = -0;
  22395. this._weightNext = -0;
  22396. this._offsetNext = -0;
  22397. this.DefaultSettings_ = {
  22398. endingStart: ZeroCurvatureEnding,
  22399. endingEnd: ZeroCurvatureEnding
  22400. };
  22401. }
  22402. intervalChanged_(i1, t0, t1) {
  22403. const pp = this.parameterPositions;
  22404. let iPrev = i1 - 2,
  22405. iNext = i1 + 1,
  22406. tPrev = pp[iPrev],
  22407. tNext = pp[iNext];
  22408. if (tPrev === undefined) {
  22409. switch (this.getSettings_().endingStart) {
  22410. case ZeroSlopeEnding:
  22411. // f'(t0) = 0
  22412. iPrev = i1;
  22413. tPrev = 2 * t0 - t1;
  22414. break;
  22415. case WrapAroundEnding:
  22416. // use the other end of the curve
  22417. iPrev = pp.length - 2;
  22418. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22419. break;
  22420. default:
  22421. // ZeroCurvatureEnding
  22422. // f''(t0) = 0 a.k.a. Natural Spline
  22423. iPrev = i1;
  22424. tPrev = t1;
  22425. }
  22426. }
  22427. if (tNext === undefined) {
  22428. switch (this.getSettings_().endingEnd) {
  22429. case ZeroSlopeEnding:
  22430. // f'(tN) = 0
  22431. iNext = i1;
  22432. tNext = 2 * t1 - t0;
  22433. break;
  22434. case WrapAroundEnding:
  22435. // use the other end of the curve
  22436. iNext = 1;
  22437. tNext = t1 + pp[1] - pp[0];
  22438. break;
  22439. default:
  22440. // ZeroCurvatureEnding
  22441. // f''(tN) = 0, a.k.a. Natural Spline
  22442. iNext = i1 - 1;
  22443. tNext = t0;
  22444. }
  22445. }
  22446. const halfDt = (t1 - t0) * 0.5,
  22447. stride = this.valueSize;
  22448. this._weightPrev = halfDt / (t0 - tPrev);
  22449. this._weightNext = halfDt / (tNext - t1);
  22450. this._offsetPrev = iPrev * stride;
  22451. this._offsetNext = iNext * stride;
  22452. }
  22453. interpolate_(i1, t0, t, t1) {
  22454. const result = this.resultBuffer,
  22455. values = this.sampleValues,
  22456. stride = this.valueSize,
  22457. o1 = i1 * stride,
  22458. o0 = o1 - stride,
  22459. oP = this._offsetPrev,
  22460. oN = this._offsetNext,
  22461. wP = this._weightPrev,
  22462. wN = this._weightNext,
  22463. p = (t - t0) / (t1 - t0),
  22464. pp = p * p,
  22465. ppp = pp * p; // evaluate polynomials
  22466. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22467. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22468. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22469. const sN = wN * ppp - wN * pp; // combine data linearly
  22470. for (let i = 0; i !== stride; ++i) {
  22471. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22472. }
  22473. return result;
  22474. }
  22475. }
  22476. class LinearInterpolant extends Interpolant {
  22477. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22478. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22479. }
  22480. interpolate_(i1, t0, t, t1) {
  22481. const result = this.resultBuffer,
  22482. values = this.sampleValues,
  22483. stride = this.valueSize,
  22484. offset1 = i1 * stride,
  22485. offset0 = offset1 - stride,
  22486. weight1 = (t - t0) / (t1 - t0),
  22487. weight0 = 1 - weight1;
  22488. for (let i = 0; i !== stride; ++i) {
  22489. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22490. }
  22491. return result;
  22492. }
  22493. }
  22494. /**
  22495. *
  22496. * Interpolant that evaluates to the sample value at the position preceding
  22497. * the parameter.
  22498. */
  22499. class DiscreteInterpolant extends Interpolant {
  22500. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22501. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22502. }
  22503. interpolate_(i1
  22504. /*, t0, t, t1 */
  22505. ) {
  22506. return this.copySampleValue_(i1 - 1);
  22507. }
  22508. }
  22509. class KeyframeTrack {
  22510. constructor(name, times, values, interpolation) {
  22511. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22512. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22513. this.name = name;
  22514. this.times = convertArray(times, this.TimeBufferType);
  22515. this.values = convertArray(values, this.ValueBufferType);
  22516. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22517. } // Serialization (in static context, because of constructor invocation
  22518. // and automatic invocation of .toJSON):
  22519. static toJSON(track) {
  22520. const trackType = track.constructor;
  22521. let json; // derived classes can define a static toJSON method
  22522. if (trackType.toJSON !== this.toJSON) {
  22523. json = trackType.toJSON(track);
  22524. } else {
  22525. // by default, we assume the data can be serialized as-is
  22526. json = {
  22527. 'name': track.name,
  22528. 'times': convertArray(track.times, Array),
  22529. 'values': convertArray(track.values, Array)
  22530. };
  22531. const interpolation = track.getInterpolation();
  22532. if (interpolation !== track.DefaultInterpolation) {
  22533. json.interpolation = interpolation;
  22534. }
  22535. }
  22536. json.type = track.ValueTypeName; // mandatory
  22537. return json;
  22538. }
  22539. InterpolantFactoryMethodDiscrete(result) {
  22540. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22541. }
  22542. InterpolantFactoryMethodLinear(result) {
  22543. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22544. }
  22545. InterpolantFactoryMethodSmooth(result) {
  22546. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22547. }
  22548. setInterpolation(interpolation) {
  22549. let factoryMethod;
  22550. switch (interpolation) {
  22551. case InterpolateDiscrete:
  22552. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22553. break;
  22554. case InterpolateLinear:
  22555. factoryMethod = this.InterpolantFactoryMethodLinear;
  22556. break;
  22557. case InterpolateSmooth:
  22558. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22559. break;
  22560. }
  22561. if (factoryMethod === undefined) {
  22562. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22563. if (this.createInterpolant === undefined) {
  22564. // fall back to default, unless the default itself is messed up
  22565. if (interpolation !== this.DefaultInterpolation) {
  22566. this.setInterpolation(this.DefaultInterpolation);
  22567. } else {
  22568. throw new Error(message); // fatal, in this case
  22569. }
  22570. }
  22571. console.warn('THREE.KeyframeTrack:', message);
  22572. return this;
  22573. }
  22574. this.createInterpolant = factoryMethod;
  22575. return this;
  22576. }
  22577. getInterpolation() {
  22578. switch (this.createInterpolant) {
  22579. case this.InterpolantFactoryMethodDiscrete:
  22580. return InterpolateDiscrete;
  22581. case this.InterpolantFactoryMethodLinear:
  22582. return InterpolateLinear;
  22583. case this.InterpolantFactoryMethodSmooth:
  22584. return InterpolateSmooth;
  22585. }
  22586. }
  22587. getValueSize() {
  22588. return this.values.length / this.times.length;
  22589. } // move all keyframes either forwards or backwards in time
  22590. shift(timeOffset) {
  22591. if (timeOffset !== 0.0) {
  22592. const times = this.times;
  22593. for (let i = 0, n = times.length; i !== n; ++i) {
  22594. times[i] += timeOffset;
  22595. }
  22596. }
  22597. return this;
  22598. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22599. scale(timeScale) {
  22600. if (timeScale !== 1.0) {
  22601. const times = this.times;
  22602. for (let i = 0, n = times.length; i !== n; ++i) {
  22603. times[i] *= timeScale;
  22604. }
  22605. }
  22606. return this;
  22607. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22608. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22609. trim(startTime, endTime) {
  22610. const times = this.times,
  22611. nKeys = times.length;
  22612. let from = 0,
  22613. to = nKeys - 1;
  22614. while (from !== nKeys && times[from] < startTime) {
  22615. ++from;
  22616. }
  22617. while (to !== -1 && times[to] > endTime) {
  22618. --to;
  22619. }
  22620. ++to; // inclusive -> exclusive bound
  22621. if (from !== 0 || to !== nKeys) {
  22622. // empty tracks are forbidden, so keep at least one keyframe
  22623. if (from >= to) {
  22624. to = Math.max(to, 1);
  22625. from = to - 1;
  22626. }
  22627. const stride = this.getValueSize();
  22628. this.times = arraySlice(times, from, to);
  22629. this.values = arraySlice(this.values, from * stride, to * stride);
  22630. }
  22631. return this;
  22632. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22633. validate() {
  22634. let valid = true;
  22635. const valueSize = this.getValueSize();
  22636. if (valueSize - Math.floor(valueSize) !== 0) {
  22637. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22638. valid = false;
  22639. }
  22640. const times = this.times,
  22641. values = this.values,
  22642. nKeys = times.length;
  22643. if (nKeys === 0) {
  22644. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22645. valid = false;
  22646. }
  22647. let prevTime = null;
  22648. for (let i = 0; i !== nKeys; i++) {
  22649. const currTime = times[i];
  22650. if (typeof currTime === 'number' && isNaN(currTime)) {
  22651. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22652. valid = false;
  22653. break;
  22654. }
  22655. if (prevTime !== null && prevTime > currTime) {
  22656. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22657. valid = false;
  22658. break;
  22659. }
  22660. prevTime = currTime;
  22661. }
  22662. if (values !== undefined) {
  22663. if (isTypedArray(values)) {
  22664. for (let i = 0, n = values.length; i !== n; ++i) {
  22665. const value = values[i];
  22666. if (isNaN(value)) {
  22667. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22668. valid = false;
  22669. break;
  22670. }
  22671. }
  22672. }
  22673. }
  22674. return valid;
  22675. } // removes equivalent sequential keys as common in morph target sequences
  22676. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22677. optimize() {
  22678. // times or values may be shared with other tracks, so overwriting is unsafe
  22679. const times = arraySlice(this.times),
  22680. values = arraySlice(this.values),
  22681. stride = this.getValueSize(),
  22682. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22683. lastIndex = times.length - 1;
  22684. let writeIndex = 1;
  22685. for (let i = 1; i < lastIndex; ++i) {
  22686. let keep = false;
  22687. const time = times[i];
  22688. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22689. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22690. if (!smoothInterpolation) {
  22691. // remove unnecessary keyframes same as their neighbors
  22692. const offset = i * stride,
  22693. offsetP = offset - stride,
  22694. offsetN = offset + stride;
  22695. for (let j = 0; j !== stride; ++j) {
  22696. const value = values[offset + j];
  22697. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22698. keep = true;
  22699. break;
  22700. }
  22701. }
  22702. } else {
  22703. keep = true;
  22704. }
  22705. } // in-place compaction
  22706. if (keep) {
  22707. if (i !== writeIndex) {
  22708. times[writeIndex] = times[i];
  22709. const readOffset = i * stride,
  22710. writeOffset = writeIndex * stride;
  22711. for (let j = 0; j !== stride; ++j) {
  22712. values[writeOffset + j] = values[readOffset + j];
  22713. }
  22714. }
  22715. ++writeIndex;
  22716. }
  22717. } // flush last keyframe (compaction looks ahead)
  22718. if (lastIndex > 0) {
  22719. times[writeIndex] = times[lastIndex];
  22720. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22721. values[writeOffset + j] = values[readOffset + j];
  22722. }
  22723. ++writeIndex;
  22724. }
  22725. if (writeIndex !== times.length) {
  22726. this.times = arraySlice(times, 0, writeIndex);
  22727. this.values = arraySlice(values, 0, writeIndex * stride);
  22728. } else {
  22729. this.times = times;
  22730. this.values = values;
  22731. }
  22732. return this;
  22733. }
  22734. clone() {
  22735. const times = arraySlice(this.times, 0);
  22736. const values = arraySlice(this.values, 0);
  22737. const TypedKeyframeTrack = this.constructor;
  22738. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22739. track.createInterpolant = this.createInterpolant;
  22740. return track;
  22741. }
  22742. }
  22743. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22744. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22745. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22746. /**
  22747. * A Track of Boolean keyframe values.
  22748. */
  22749. class BooleanKeyframeTrack extends KeyframeTrack {}
  22750. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22751. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22752. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22753. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22754. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22755. /**
  22756. * A Track of keyframe values that represent color.
  22757. */
  22758. class ColorKeyframeTrack extends KeyframeTrack {}
  22759. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22760. /**
  22761. * A Track of numeric keyframe values.
  22762. */
  22763. class NumberKeyframeTrack extends KeyframeTrack {}
  22764. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22765. /**
  22766. * Spherical linear unit quaternion interpolant.
  22767. */
  22768. class QuaternionLinearInterpolant extends Interpolant {
  22769. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22770. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22771. }
  22772. interpolate_(i1, t0, t, t1) {
  22773. const result = this.resultBuffer,
  22774. values = this.sampleValues,
  22775. stride = this.valueSize,
  22776. alpha = (t - t0) / (t1 - t0);
  22777. let offset = i1 * stride;
  22778. for (let end = offset + stride; offset !== end; offset += 4) {
  22779. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22780. }
  22781. return result;
  22782. }
  22783. }
  22784. /**
  22785. * A Track of quaternion keyframe values.
  22786. */
  22787. class QuaternionKeyframeTrack extends KeyframeTrack {
  22788. InterpolantFactoryMethodLinear(result) {
  22789. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22790. }
  22791. }
  22792. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22793. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22794. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22795. /**
  22796. * A Track that interpolates Strings
  22797. */
  22798. class StringKeyframeTrack extends KeyframeTrack {}
  22799. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22800. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22801. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22802. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22803. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22804. /**
  22805. * A Track of vectored keyframe values.
  22806. */
  22807. class VectorKeyframeTrack extends KeyframeTrack {}
  22808. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22809. class AnimationClip {
  22810. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22811. this.name = name;
  22812. this.tracks = tracks;
  22813. this.duration = duration;
  22814. this.blendMode = blendMode;
  22815. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22816. if (this.duration < 0) {
  22817. this.resetDuration();
  22818. }
  22819. }
  22820. static parse(json) {
  22821. const tracks = [],
  22822. jsonTracks = json.tracks,
  22823. frameTime = 1.0 / (json.fps || 1.0);
  22824. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22825. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22826. }
  22827. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22828. clip.uuid = json.uuid;
  22829. return clip;
  22830. }
  22831. static toJSON(clip) {
  22832. const tracks = [],
  22833. clipTracks = clip.tracks;
  22834. const json = {
  22835. 'name': clip.name,
  22836. 'duration': clip.duration,
  22837. 'tracks': tracks,
  22838. 'uuid': clip.uuid,
  22839. 'blendMode': clip.blendMode
  22840. };
  22841. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22842. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22843. }
  22844. return json;
  22845. }
  22846. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22847. const numMorphTargets = morphTargetSequence.length;
  22848. const tracks = [];
  22849. for (let i = 0; i < numMorphTargets; i++) {
  22850. let times = [];
  22851. let values = [];
  22852. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22853. values.push(0, 1, 0);
  22854. const order = getKeyframeOrder(times);
  22855. times = sortedArray(times, 1, order);
  22856. values = sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22857. // last frame as well for perfect loop.
  22858. if (!noLoop && times[0] === 0) {
  22859. times.push(numMorphTargets);
  22860. values.push(values[0]);
  22861. }
  22862. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22863. }
  22864. return new this(name, -1, tracks);
  22865. }
  22866. static findByName(objectOrClipArray, name) {
  22867. let clipArray = objectOrClipArray;
  22868. if (!Array.isArray(objectOrClipArray)) {
  22869. const o = objectOrClipArray;
  22870. clipArray = o.geometry && o.geometry.animations || o.animations;
  22871. }
  22872. for (let i = 0; i < clipArray.length; i++) {
  22873. if (clipArray[i].name === name) {
  22874. return clipArray[i];
  22875. }
  22876. }
  22877. return null;
  22878. }
  22879. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22880. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22881. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22882. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22883. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22884. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22885. const morphTarget = morphTargets[i];
  22886. const parts = morphTarget.name.match(pattern);
  22887. if (parts && parts.length > 1) {
  22888. const name = parts[1];
  22889. let animationMorphTargets = animationToMorphTargets[name];
  22890. if (!animationMorphTargets) {
  22891. animationToMorphTargets[name] = animationMorphTargets = [];
  22892. }
  22893. animationMorphTargets.push(morphTarget);
  22894. }
  22895. }
  22896. const clips = [];
  22897. for (const name in animationToMorphTargets) {
  22898. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22899. }
  22900. return clips;
  22901. } // parse the animation.hierarchy format
  22902. static parseAnimation(animation, bones) {
  22903. if (!animation) {
  22904. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22905. return null;
  22906. }
  22907. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22908. // only return track if there are actually keys.
  22909. if (animationKeys.length !== 0) {
  22910. const times = [];
  22911. const values = [];
  22912. flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22913. if (times.length !== 0) {
  22914. destTracks.push(new trackType(trackName, times, values));
  22915. }
  22916. }
  22917. };
  22918. const tracks = [];
  22919. const clipName = animation.name || 'default';
  22920. const fps = animation.fps || 30;
  22921. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22922. let duration = animation.length || -1;
  22923. const hierarchyTracks = animation.hierarchy || [];
  22924. for (let h = 0; h < hierarchyTracks.length; h++) {
  22925. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22926. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22927. if (animationKeys[0].morphTargets) {
  22928. // figure out all morph targets used in this track
  22929. const morphTargetNames = {};
  22930. let k;
  22931. for (k = 0; k < animationKeys.length; k++) {
  22932. if (animationKeys[k].morphTargets) {
  22933. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22934. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22935. }
  22936. }
  22937. } // create a track for each morph target with all zero
  22938. // morphTargetInfluences except for the keys in which
  22939. // the morphTarget is named.
  22940. for (const morphTargetName in morphTargetNames) {
  22941. const times = [];
  22942. const values = [];
  22943. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22944. const animationKey = animationKeys[k];
  22945. times.push(animationKey.time);
  22946. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22947. }
  22948. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22949. }
  22950. duration = morphTargetNames.length * fps;
  22951. } else {
  22952. // ...assume skeletal animation
  22953. const boneName = '.bones[' + bones[h].name + ']';
  22954. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22955. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22956. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22957. }
  22958. }
  22959. if (tracks.length === 0) {
  22960. return null;
  22961. }
  22962. const clip = new this(clipName, duration, tracks, blendMode);
  22963. return clip;
  22964. }
  22965. resetDuration() {
  22966. const tracks = this.tracks;
  22967. let duration = 0;
  22968. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22969. const track = this.tracks[i];
  22970. duration = Math.max(duration, track.times[track.times.length - 1]);
  22971. }
  22972. this.duration = duration;
  22973. return this;
  22974. }
  22975. trim() {
  22976. for (let i = 0; i < this.tracks.length; i++) {
  22977. this.tracks[i].trim(0, this.duration);
  22978. }
  22979. return this;
  22980. }
  22981. validate() {
  22982. let valid = true;
  22983. for (let i = 0; i < this.tracks.length; i++) {
  22984. valid = valid && this.tracks[i].validate();
  22985. }
  22986. return valid;
  22987. }
  22988. optimize() {
  22989. for (let i = 0; i < this.tracks.length; i++) {
  22990. this.tracks[i].optimize();
  22991. }
  22992. return this;
  22993. }
  22994. clone() {
  22995. const tracks = [];
  22996. for (let i = 0; i < this.tracks.length; i++) {
  22997. tracks.push(this.tracks[i].clone());
  22998. }
  22999. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  23000. }
  23001. toJSON() {
  23002. return this.constructor.toJSON(this);
  23003. }
  23004. }
  23005. function getTrackTypeForValueTypeName(typeName) {
  23006. switch (typeName.toLowerCase()) {
  23007. case 'scalar':
  23008. case 'double':
  23009. case 'float':
  23010. case 'number':
  23011. case 'integer':
  23012. return NumberKeyframeTrack;
  23013. case 'vector':
  23014. case 'vector2':
  23015. case 'vector3':
  23016. case 'vector4':
  23017. return VectorKeyframeTrack;
  23018. case 'color':
  23019. return ColorKeyframeTrack;
  23020. case 'quaternion':
  23021. return QuaternionKeyframeTrack;
  23022. case 'bool':
  23023. case 'boolean':
  23024. return BooleanKeyframeTrack;
  23025. case 'string':
  23026. return StringKeyframeTrack;
  23027. }
  23028. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  23029. }
  23030. function parseKeyframeTrack(json) {
  23031. if (json.type === undefined) {
  23032. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  23033. }
  23034. const trackType = getTrackTypeForValueTypeName(json.type);
  23035. if (json.times === undefined) {
  23036. const times = [],
  23037. values = [];
  23038. flattenJSON(json.keys, times, values, 'value');
  23039. json.times = times;
  23040. json.values = values;
  23041. } // derived classes can define a static parse method
  23042. if (trackType.parse !== undefined) {
  23043. return trackType.parse(json);
  23044. } else {
  23045. // by default, we assume a constructor compatible with the base
  23046. return new trackType(json.name, json.times, json.values, json.interpolation);
  23047. }
  23048. }
  23049. const Cache = {
  23050. enabled: false,
  23051. files: {},
  23052. add: function (key, file) {
  23053. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  23054. this.files[key] = file;
  23055. },
  23056. get: function (key) {
  23057. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  23058. return this.files[key];
  23059. },
  23060. remove: function (key) {
  23061. delete this.files[key];
  23062. },
  23063. clear: function () {
  23064. this.files = {};
  23065. }
  23066. };
  23067. class LoadingManager {
  23068. constructor(onLoad, onProgress, onError) {
  23069. const scope = this;
  23070. let isLoading = false;
  23071. let itemsLoaded = 0;
  23072. let itemsTotal = 0;
  23073. let urlModifier = undefined;
  23074. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  23075. // in the constructor
  23076. this.onStart = undefined;
  23077. this.onLoad = onLoad;
  23078. this.onProgress = onProgress;
  23079. this.onError = onError;
  23080. this.itemStart = function (url) {
  23081. itemsTotal++;
  23082. if (isLoading === false) {
  23083. if (scope.onStart !== undefined) {
  23084. scope.onStart(url, itemsLoaded, itemsTotal);
  23085. }
  23086. }
  23087. isLoading = true;
  23088. };
  23089. this.itemEnd = function (url) {
  23090. itemsLoaded++;
  23091. if (scope.onProgress !== undefined) {
  23092. scope.onProgress(url, itemsLoaded, itemsTotal);
  23093. }
  23094. if (itemsLoaded === itemsTotal) {
  23095. isLoading = false;
  23096. if (scope.onLoad !== undefined) {
  23097. scope.onLoad();
  23098. }
  23099. }
  23100. };
  23101. this.itemError = function (url) {
  23102. if (scope.onError !== undefined) {
  23103. scope.onError(url);
  23104. }
  23105. };
  23106. this.resolveURL = function (url) {
  23107. if (urlModifier) {
  23108. return urlModifier(url);
  23109. }
  23110. return url;
  23111. };
  23112. this.setURLModifier = function (transform) {
  23113. urlModifier = transform;
  23114. return this;
  23115. };
  23116. this.addHandler = function (regex, loader) {
  23117. handlers.push(regex, loader);
  23118. return this;
  23119. };
  23120. this.removeHandler = function (regex) {
  23121. const index = handlers.indexOf(regex);
  23122. if (index !== -1) {
  23123. handlers.splice(index, 2);
  23124. }
  23125. return this;
  23126. };
  23127. this.getHandler = function (file) {
  23128. for (let i = 0, l = handlers.length; i < l; i += 2) {
  23129. const regex = handlers[i];
  23130. const loader = handlers[i + 1];
  23131. if (regex.global) regex.lastIndex = 0; // see #17920
  23132. if (regex.test(file)) {
  23133. return loader;
  23134. }
  23135. }
  23136. return null;
  23137. };
  23138. }
  23139. }
  23140. const DefaultLoadingManager = /*@__PURE__*/new LoadingManager();
  23141. class Loader {
  23142. constructor(manager) {
  23143. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  23144. this.crossOrigin = 'anonymous';
  23145. this.withCredentials = false;
  23146. this.path = '';
  23147. this.resourcePath = '';
  23148. this.requestHeader = {};
  23149. }
  23150. load() {}
  23151. loadAsync(url, onProgress) {
  23152. const scope = this;
  23153. return new Promise(function (resolve, reject) {
  23154. scope.load(url, resolve, onProgress, reject);
  23155. });
  23156. }
  23157. parse() {}
  23158. setCrossOrigin(crossOrigin) {
  23159. this.crossOrigin = crossOrigin;
  23160. return this;
  23161. }
  23162. setWithCredentials(value) {
  23163. this.withCredentials = value;
  23164. return this;
  23165. }
  23166. setPath(path) {
  23167. this.path = path;
  23168. return this;
  23169. }
  23170. setResourcePath(resourcePath) {
  23171. this.resourcePath = resourcePath;
  23172. return this;
  23173. }
  23174. setRequestHeader(requestHeader) {
  23175. this.requestHeader = requestHeader;
  23176. return this;
  23177. }
  23178. }
  23179. const loading = {};
  23180. class HttpError extends Error {
  23181. constructor(message, response) {
  23182. super(message);
  23183. this.response = response;
  23184. }
  23185. }
  23186. class FileLoader extends Loader {
  23187. constructor(manager) {
  23188. super(manager);
  23189. }
  23190. load(url, onLoad, onProgress, onError) {
  23191. if (url === undefined) url = '';
  23192. if (this.path !== undefined) url = this.path + url;
  23193. url = this.manager.resolveURL(url);
  23194. const cached = Cache.get(url);
  23195. if (cached !== undefined) {
  23196. this.manager.itemStart(url);
  23197. setTimeout(() => {
  23198. if (onLoad) onLoad(cached);
  23199. this.manager.itemEnd(url);
  23200. }, 0);
  23201. return cached;
  23202. } // Check if request is duplicate
  23203. if (loading[url] !== undefined) {
  23204. loading[url].push({
  23205. onLoad: onLoad,
  23206. onProgress: onProgress,
  23207. onError: onError
  23208. });
  23209. return;
  23210. } // Initialise array for duplicate requests
  23211. loading[url] = [];
  23212. loading[url].push({
  23213. onLoad: onLoad,
  23214. onProgress: onProgress,
  23215. onError: onError
  23216. }); // create request
  23217. const req = new Request(url, {
  23218. headers: new Headers(this.requestHeader),
  23219. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  23220. }); // record states ( avoid data race )
  23221. const mimeType = this.mimeType;
  23222. const responseType = this.responseType; // start the fetch
  23223. fetch(req).then(response => {
  23224. if (response.status === 200 || response.status === 0) {
  23225. // Some browsers return HTTP Status 0 when using non-http protocol
  23226. // e.g. 'file://' or 'data://'. Handle as success.
  23227. if (response.status === 0) {
  23228. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  23229. } // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23230. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  23231. return response;
  23232. }
  23233. const callbacks = loading[url];
  23234. const reader = response.body.getReader();
  23235. const contentLength = response.headers.get('Content-Length');
  23236. const total = contentLength ? parseInt(contentLength) : 0;
  23237. const lengthComputable = total !== 0;
  23238. let loaded = 0; // periodically read data into the new stream tracking while download progress
  23239. const stream = new ReadableStream({
  23240. start(controller) {
  23241. readData();
  23242. function readData() {
  23243. reader.read().then(({
  23244. done,
  23245. value
  23246. }) => {
  23247. if (done) {
  23248. controller.close();
  23249. } else {
  23250. loaded += value.byteLength;
  23251. const event = new ProgressEvent('progress', {
  23252. lengthComputable,
  23253. loaded,
  23254. total
  23255. });
  23256. for (let i = 0, il = callbacks.length; i < il; i++) {
  23257. const callback = callbacks[i];
  23258. if (callback.onProgress) callback.onProgress(event);
  23259. }
  23260. controller.enqueue(value);
  23261. readData();
  23262. }
  23263. });
  23264. }
  23265. }
  23266. });
  23267. return new Response(stream);
  23268. } else {
  23269. throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response);
  23270. }
  23271. }).then(response => {
  23272. switch (responseType) {
  23273. case 'arraybuffer':
  23274. return response.arrayBuffer();
  23275. case 'blob':
  23276. return response.blob();
  23277. case 'document':
  23278. return response.text().then(text => {
  23279. const parser = new DOMParser();
  23280. return parser.parseFromString(text, mimeType);
  23281. });
  23282. case 'json':
  23283. return response.json();
  23284. default:
  23285. if (mimeType === undefined) {
  23286. return response.text();
  23287. } else {
  23288. // sniff encoding
  23289. const re = /charset="?([^;"\s]*)"?/i;
  23290. const exec = re.exec(mimeType);
  23291. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  23292. const decoder = new TextDecoder(label);
  23293. return response.arrayBuffer().then(ab => decoder.decode(ab));
  23294. }
  23295. }
  23296. }).then(data => {
  23297. // Add to cache only on HTTP success, so that we do not cache
  23298. // error response bodies as proper responses to requests.
  23299. Cache.add(url, data);
  23300. const callbacks = loading[url];
  23301. delete loading[url];
  23302. for (let i = 0, il = callbacks.length; i < il; i++) {
  23303. const callback = callbacks[i];
  23304. if (callback.onLoad) callback.onLoad(data);
  23305. }
  23306. }).catch(err => {
  23307. // Abort errors and other errors are handled the same
  23308. const callbacks = loading[url];
  23309. if (callbacks === undefined) {
  23310. // When onLoad was called and url was deleted in `loading`
  23311. this.manager.itemError(url);
  23312. throw err;
  23313. }
  23314. delete loading[url];
  23315. for (let i = 0, il = callbacks.length; i < il; i++) {
  23316. const callback = callbacks[i];
  23317. if (callback.onError) callback.onError(err);
  23318. }
  23319. this.manager.itemError(url);
  23320. }).finally(() => {
  23321. this.manager.itemEnd(url);
  23322. });
  23323. this.manager.itemStart(url);
  23324. }
  23325. setResponseType(value) {
  23326. this.responseType = value;
  23327. return this;
  23328. }
  23329. setMimeType(value) {
  23330. this.mimeType = value;
  23331. return this;
  23332. }
  23333. }
  23334. class AnimationLoader extends Loader {
  23335. constructor(manager) {
  23336. super(manager);
  23337. }
  23338. load(url, onLoad, onProgress, onError) {
  23339. const scope = this;
  23340. const loader = new FileLoader(this.manager);
  23341. loader.setPath(this.path);
  23342. loader.setRequestHeader(this.requestHeader);
  23343. loader.setWithCredentials(this.withCredentials);
  23344. loader.load(url, function (text) {
  23345. try {
  23346. onLoad(scope.parse(JSON.parse(text)));
  23347. } catch (e) {
  23348. if (onError) {
  23349. onError(e);
  23350. } else {
  23351. console.error(e);
  23352. }
  23353. scope.manager.itemError(url);
  23354. }
  23355. }, onProgress, onError);
  23356. }
  23357. parse(json) {
  23358. const animations = [];
  23359. for (let i = 0; i < json.length; i++) {
  23360. const clip = AnimationClip.parse(json[i]);
  23361. animations.push(clip);
  23362. }
  23363. return animations;
  23364. }
  23365. }
  23366. /**
  23367. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23368. *
  23369. * Sub classes have to implement the parse() method which will be used in load().
  23370. */
  23371. class CompressedTextureLoader extends Loader {
  23372. constructor(manager) {
  23373. super(manager);
  23374. }
  23375. load(url, onLoad, onProgress, onError) {
  23376. const scope = this;
  23377. const images = [];
  23378. const texture = new CompressedTexture();
  23379. const loader = new FileLoader(this.manager);
  23380. loader.setPath(this.path);
  23381. loader.setResponseType('arraybuffer');
  23382. loader.setRequestHeader(this.requestHeader);
  23383. loader.setWithCredentials(scope.withCredentials);
  23384. let loaded = 0;
  23385. function loadTexture(i) {
  23386. loader.load(url[i], function (buffer) {
  23387. const texDatas = scope.parse(buffer, true);
  23388. images[i] = {
  23389. width: texDatas.width,
  23390. height: texDatas.height,
  23391. format: texDatas.format,
  23392. mipmaps: texDatas.mipmaps
  23393. };
  23394. loaded += 1;
  23395. if (loaded === 6) {
  23396. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23397. texture.image = images;
  23398. texture.format = texDatas.format;
  23399. texture.needsUpdate = true;
  23400. if (onLoad) onLoad(texture);
  23401. }
  23402. }, onProgress, onError);
  23403. }
  23404. if (Array.isArray(url)) {
  23405. for (let i = 0, il = url.length; i < il; ++i) {
  23406. loadTexture(i);
  23407. }
  23408. } else {
  23409. // compressed cubemap texture stored in a single DDS file
  23410. loader.load(url, function (buffer) {
  23411. const texDatas = scope.parse(buffer, true);
  23412. if (texDatas.isCubemap) {
  23413. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23414. for (let f = 0; f < faces; f++) {
  23415. images[f] = {
  23416. mipmaps: []
  23417. };
  23418. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23419. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23420. images[f].format = texDatas.format;
  23421. images[f].width = texDatas.width;
  23422. images[f].height = texDatas.height;
  23423. }
  23424. }
  23425. texture.image = images;
  23426. } else {
  23427. texture.image.width = texDatas.width;
  23428. texture.image.height = texDatas.height;
  23429. texture.mipmaps = texDatas.mipmaps;
  23430. }
  23431. if (texDatas.mipmapCount === 1) {
  23432. texture.minFilter = LinearFilter;
  23433. }
  23434. texture.format = texDatas.format;
  23435. texture.needsUpdate = true;
  23436. if (onLoad) onLoad(texture);
  23437. }, onProgress, onError);
  23438. }
  23439. return texture;
  23440. }
  23441. }
  23442. class ImageLoader extends Loader {
  23443. constructor(manager) {
  23444. super(manager);
  23445. }
  23446. load(url, onLoad, onProgress, onError) {
  23447. if (this.path !== undefined) url = this.path + url;
  23448. url = this.manager.resolveURL(url);
  23449. const scope = this;
  23450. const cached = Cache.get(url);
  23451. if (cached !== undefined) {
  23452. scope.manager.itemStart(url);
  23453. setTimeout(function () {
  23454. if (onLoad) onLoad(cached);
  23455. scope.manager.itemEnd(url);
  23456. }, 0);
  23457. return cached;
  23458. }
  23459. const image = createElementNS('img');
  23460. function onImageLoad() {
  23461. removeEventListeners();
  23462. Cache.add(url, this);
  23463. if (onLoad) onLoad(this);
  23464. scope.manager.itemEnd(url);
  23465. }
  23466. function onImageError(event) {
  23467. removeEventListeners();
  23468. if (onError) onError(event);
  23469. scope.manager.itemError(url);
  23470. scope.manager.itemEnd(url);
  23471. }
  23472. function removeEventListeners() {
  23473. image.removeEventListener('load', onImageLoad, false);
  23474. image.removeEventListener('error', onImageError, false);
  23475. }
  23476. image.addEventListener('load', onImageLoad, false);
  23477. image.addEventListener('error', onImageError, false);
  23478. if (url.slice(0, 5) !== 'data:') {
  23479. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23480. }
  23481. scope.manager.itemStart(url);
  23482. image.src = url;
  23483. return image;
  23484. }
  23485. }
  23486. class CubeTextureLoader extends Loader {
  23487. constructor(manager) {
  23488. super(manager);
  23489. }
  23490. load(urls, onLoad, onProgress, onError) {
  23491. const texture = new CubeTexture();
  23492. const loader = new ImageLoader(this.manager);
  23493. loader.setCrossOrigin(this.crossOrigin);
  23494. loader.setPath(this.path);
  23495. let loaded = 0;
  23496. function loadTexture(i) {
  23497. loader.load(urls[i], function (image) {
  23498. texture.images[i] = image;
  23499. loaded++;
  23500. if (loaded === 6) {
  23501. texture.needsUpdate = true;
  23502. if (onLoad) onLoad(texture);
  23503. }
  23504. }, undefined, onError);
  23505. }
  23506. for (let i = 0; i < urls.length; ++i) {
  23507. loadTexture(i);
  23508. }
  23509. return texture;
  23510. }
  23511. }
  23512. /**
  23513. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23514. *
  23515. * Sub classes have to implement the parse() method which will be used in load().
  23516. */
  23517. class DataTextureLoader extends Loader {
  23518. constructor(manager) {
  23519. super(manager);
  23520. }
  23521. load(url, onLoad, onProgress, onError) {
  23522. const scope = this;
  23523. const texture = new DataTexture();
  23524. const loader = new FileLoader(this.manager);
  23525. loader.setResponseType('arraybuffer');
  23526. loader.setRequestHeader(this.requestHeader);
  23527. loader.setPath(this.path);
  23528. loader.setWithCredentials(scope.withCredentials);
  23529. loader.load(url, function (buffer) {
  23530. const texData = scope.parse(buffer);
  23531. if (!texData) return;
  23532. if (texData.image !== undefined) {
  23533. texture.image = texData.image;
  23534. } else if (texData.data !== undefined) {
  23535. texture.image.width = texData.width;
  23536. texture.image.height = texData.height;
  23537. texture.image.data = texData.data;
  23538. }
  23539. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23540. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23541. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23542. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23543. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23544. if (texData.encoding !== undefined) {
  23545. texture.encoding = texData.encoding;
  23546. }
  23547. if (texData.flipY !== undefined) {
  23548. texture.flipY = texData.flipY;
  23549. }
  23550. if (texData.format !== undefined) {
  23551. texture.format = texData.format;
  23552. }
  23553. if (texData.type !== undefined) {
  23554. texture.type = texData.type;
  23555. }
  23556. if (texData.mipmaps !== undefined) {
  23557. texture.mipmaps = texData.mipmaps;
  23558. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23559. }
  23560. if (texData.mipmapCount === 1) {
  23561. texture.minFilter = LinearFilter;
  23562. }
  23563. if (texData.generateMipmaps !== undefined) {
  23564. texture.generateMipmaps = texData.generateMipmaps;
  23565. }
  23566. texture.needsUpdate = true;
  23567. if (onLoad) onLoad(texture, texData);
  23568. }, onProgress, onError);
  23569. return texture;
  23570. }
  23571. }
  23572. class TextureLoader extends Loader {
  23573. constructor(manager) {
  23574. super(manager);
  23575. }
  23576. load(url, onLoad, onProgress, onError) {
  23577. const texture = new Texture();
  23578. const loader = new ImageLoader(this.manager);
  23579. loader.setCrossOrigin(this.crossOrigin);
  23580. loader.setPath(this.path);
  23581. loader.load(url, function (image) {
  23582. texture.image = image;
  23583. texture.needsUpdate = true;
  23584. if (onLoad !== undefined) {
  23585. onLoad(texture);
  23586. }
  23587. }, onProgress, onError);
  23588. return texture;
  23589. }
  23590. }
  23591. class Light extends Object3D {
  23592. constructor(color, intensity = 1) {
  23593. super();
  23594. this.isLight = true;
  23595. this.type = 'Light';
  23596. this.color = new Color(color);
  23597. this.intensity = intensity;
  23598. }
  23599. dispose() {// Empty here in base class; some subclasses override.
  23600. }
  23601. copy(source, recursive) {
  23602. super.copy(source, recursive);
  23603. this.color.copy(source.color);
  23604. this.intensity = source.intensity;
  23605. return this;
  23606. }
  23607. toJSON(meta) {
  23608. const data = super.toJSON(meta);
  23609. data.object.color = this.color.getHex();
  23610. data.object.intensity = this.intensity;
  23611. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23612. if (this.distance !== undefined) data.object.distance = this.distance;
  23613. if (this.angle !== undefined) data.object.angle = this.angle;
  23614. if (this.decay !== undefined) data.object.decay = this.decay;
  23615. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23616. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23617. return data;
  23618. }
  23619. }
  23620. class HemisphereLight extends Light {
  23621. constructor(skyColor, groundColor, intensity) {
  23622. super(skyColor, intensity);
  23623. this.isHemisphereLight = true;
  23624. this.type = 'HemisphereLight';
  23625. this.position.copy(Object3D.DefaultUp);
  23626. this.updateMatrix();
  23627. this.groundColor = new Color(groundColor);
  23628. }
  23629. copy(source, recursive) {
  23630. super.copy(source, recursive);
  23631. this.groundColor.copy(source.groundColor);
  23632. return this;
  23633. }
  23634. }
  23635. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23636. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23637. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23638. class LightShadow {
  23639. constructor(camera) {
  23640. this.camera = camera;
  23641. this.bias = 0;
  23642. this.normalBias = 0;
  23643. this.radius = 1;
  23644. this.blurSamples = 8;
  23645. this.mapSize = new Vector2(512, 512);
  23646. this.map = null;
  23647. this.mapPass = null;
  23648. this.matrix = new Matrix4();
  23649. this.autoUpdate = true;
  23650. this.needsUpdate = false;
  23651. this._frustum = new Frustum();
  23652. this._frameExtents = new Vector2(1, 1);
  23653. this._viewportCount = 1;
  23654. this._viewports = [new Vector4(0, 0, 1, 1)];
  23655. }
  23656. getViewportCount() {
  23657. return this._viewportCount;
  23658. }
  23659. getFrustum() {
  23660. return this._frustum;
  23661. }
  23662. updateMatrices(light) {
  23663. const shadowCamera = this.camera;
  23664. const shadowMatrix = this.matrix;
  23665. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23666. shadowCamera.position.copy(_lightPositionWorld$1);
  23667. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23668. shadowCamera.lookAt(_lookTarget$1);
  23669. shadowCamera.updateMatrixWorld();
  23670. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23671. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23672. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  23673. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23674. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23675. }
  23676. getViewport(viewportIndex) {
  23677. return this._viewports[viewportIndex];
  23678. }
  23679. getFrameExtents() {
  23680. return this._frameExtents;
  23681. }
  23682. dispose() {
  23683. if (this.map) {
  23684. this.map.dispose();
  23685. }
  23686. if (this.mapPass) {
  23687. this.mapPass.dispose();
  23688. }
  23689. }
  23690. copy(source) {
  23691. this.camera = source.camera.clone();
  23692. this.bias = source.bias;
  23693. this.radius = source.radius;
  23694. this.mapSize.copy(source.mapSize);
  23695. return this;
  23696. }
  23697. clone() {
  23698. return new this.constructor().copy(this);
  23699. }
  23700. toJSON() {
  23701. const object = {};
  23702. if (this.bias !== 0) object.bias = this.bias;
  23703. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23704. if (this.radius !== 1) object.radius = this.radius;
  23705. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23706. object.camera = this.camera.toJSON(false).object;
  23707. delete object.camera.matrix;
  23708. return object;
  23709. }
  23710. }
  23711. class SpotLightShadow extends LightShadow {
  23712. constructor() {
  23713. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23714. this.isSpotLightShadow = true;
  23715. this.focus = 1;
  23716. }
  23717. updateMatrices(light) {
  23718. const camera = this.camera;
  23719. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23720. const aspect = this.mapSize.width / this.mapSize.height;
  23721. const far = light.distance || camera.far;
  23722. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23723. camera.fov = fov;
  23724. camera.aspect = aspect;
  23725. camera.far = far;
  23726. camera.updateProjectionMatrix();
  23727. }
  23728. super.updateMatrices(light);
  23729. }
  23730. copy(source) {
  23731. super.copy(source);
  23732. this.focus = source.focus;
  23733. return this;
  23734. }
  23735. }
  23736. class SpotLight extends Light {
  23737. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23738. super(color, intensity);
  23739. this.isSpotLight = true;
  23740. this.type = 'SpotLight';
  23741. this.position.copy(Object3D.DefaultUp);
  23742. this.updateMatrix();
  23743. this.target = new Object3D();
  23744. this.distance = distance;
  23745. this.angle = angle;
  23746. this.penumbra = penumbra;
  23747. this.decay = decay; // for physically correct lights, should be 2.
  23748. this.map = null;
  23749. this.shadow = new SpotLightShadow();
  23750. }
  23751. get power() {
  23752. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23753. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23754. return this.intensity * Math.PI;
  23755. }
  23756. set power(power) {
  23757. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23758. this.intensity = power / Math.PI;
  23759. }
  23760. dispose() {
  23761. this.shadow.dispose();
  23762. }
  23763. copy(source, recursive) {
  23764. super.copy(source, recursive);
  23765. this.distance = source.distance;
  23766. this.angle = source.angle;
  23767. this.penumbra = source.penumbra;
  23768. this.decay = source.decay;
  23769. this.target = source.target.clone();
  23770. this.shadow = source.shadow.clone();
  23771. return this;
  23772. }
  23773. }
  23774. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23775. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23776. const _lookTarget = /*@__PURE__*/new Vector3();
  23777. class PointLightShadow extends LightShadow {
  23778. constructor() {
  23779. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23780. this.isPointLightShadow = true;
  23781. this._frameExtents = new Vector2(4, 2);
  23782. this._viewportCount = 6;
  23783. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23784. // following orientation:
  23785. //
  23786. // xzXZ
  23787. // y Y
  23788. //
  23789. // X - Positive x direction
  23790. // x - Negative x direction
  23791. // Y - Positive y direction
  23792. // y - Negative y direction
  23793. // Z - Positive z direction
  23794. // z - Negative z direction
  23795. // positive X
  23796. new Vector4(2, 1, 1, 1), // negative X
  23797. new Vector4(0, 1, 1, 1), // positive Z
  23798. new Vector4(3, 1, 1, 1), // negative Z
  23799. new Vector4(1, 1, 1, 1), // positive Y
  23800. new Vector4(3, 0, 1, 1), // negative Y
  23801. new Vector4(1, 0, 1, 1)];
  23802. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  23803. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  23804. }
  23805. updateMatrices(light, viewportIndex = 0) {
  23806. const camera = this.camera;
  23807. const shadowMatrix = this.matrix;
  23808. const far = light.distance || camera.far;
  23809. if (far !== camera.far) {
  23810. camera.far = far;
  23811. camera.updateProjectionMatrix();
  23812. }
  23813. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23814. camera.position.copy(_lightPositionWorld);
  23815. _lookTarget.copy(camera.position);
  23816. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23817. camera.up.copy(this._cubeUps[viewportIndex]);
  23818. camera.lookAt(_lookTarget);
  23819. camera.updateMatrixWorld();
  23820. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23821. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23822. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23823. }
  23824. }
  23825. class PointLight extends Light {
  23826. constructor(color, intensity, distance = 0, decay = 1) {
  23827. super(color, intensity);
  23828. this.isPointLight = true;
  23829. this.type = 'PointLight';
  23830. this.distance = distance;
  23831. this.decay = decay; // for physically correct lights, should be 2.
  23832. this.shadow = new PointLightShadow();
  23833. }
  23834. get power() {
  23835. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23836. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23837. return this.intensity * 4 * Math.PI;
  23838. }
  23839. set power(power) {
  23840. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23841. this.intensity = power / (4 * Math.PI);
  23842. }
  23843. dispose() {
  23844. this.shadow.dispose();
  23845. }
  23846. copy(source, recursive) {
  23847. super.copy(source, recursive);
  23848. this.distance = source.distance;
  23849. this.decay = source.decay;
  23850. this.shadow = source.shadow.clone();
  23851. return this;
  23852. }
  23853. }
  23854. class DirectionalLightShadow extends LightShadow {
  23855. constructor() {
  23856. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23857. this.isDirectionalLightShadow = true;
  23858. }
  23859. }
  23860. class DirectionalLight extends Light {
  23861. constructor(color, intensity) {
  23862. super(color, intensity);
  23863. this.isDirectionalLight = true;
  23864. this.type = 'DirectionalLight';
  23865. this.position.copy(Object3D.DefaultUp);
  23866. this.updateMatrix();
  23867. this.target = new Object3D();
  23868. this.shadow = new DirectionalLightShadow();
  23869. }
  23870. dispose() {
  23871. this.shadow.dispose();
  23872. }
  23873. copy(source) {
  23874. super.copy(source);
  23875. this.target = source.target.clone();
  23876. this.shadow = source.shadow.clone();
  23877. return this;
  23878. }
  23879. }
  23880. class AmbientLight extends Light {
  23881. constructor(color, intensity) {
  23882. super(color, intensity);
  23883. this.isAmbientLight = true;
  23884. this.type = 'AmbientLight';
  23885. }
  23886. }
  23887. class RectAreaLight extends Light {
  23888. constructor(color, intensity, width = 10, height = 10) {
  23889. super(color, intensity);
  23890. this.isRectAreaLight = true;
  23891. this.type = 'RectAreaLight';
  23892. this.width = width;
  23893. this.height = height;
  23894. }
  23895. get power() {
  23896. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23897. return this.intensity * this.width * this.height * Math.PI;
  23898. }
  23899. set power(power) {
  23900. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23901. this.intensity = power / (this.width * this.height * Math.PI);
  23902. }
  23903. copy(source) {
  23904. super.copy(source);
  23905. this.width = source.width;
  23906. this.height = source.height;
  23907. return this;
  23908. }
  23909. toJSON(meta) {
  23910. const data = super.toJSON(meta);
  23911. data.object.width = this.width;
  23912. data.object.height = this.height;
  23913. return data;
  23914. }
  23915. }
  23916. /**
  23917. * Primary reference:
  23918. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23919. *
  23920. * Secondary reference:
  23921. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23922. */
  23923. // 3-band SH defined by 9 coefficients
  23924. class SphericalHarmonics3 {
  23925. constructor() {
  23926. this.isSphericalHarmonics3 = true;
  23927. this.coefficients = [];
  23928. for (let i = 0; i < 9; i++) {
  23929. this.coefficients.push(new Vector3());
  23930. }
  23931. }
  23932. set(coefficients) {
  23933. for (let i = 0; i < 9; i++) {
  23934. this.coefficients[i].copy(coefficients[i]);
  23935. }
  23936. return this;
  23937. }
  23938. zero() {
  23939. for (let i = 0; i < 9; i++) {
  23940. this.coefficients[i].set(0, 0, 0);
  23941. }
  23942. return this;
  23943. } // get the radiance in the direction of the normal
  23944. // target is a Vector3
  23945. getAt(normal, target) {
  23946. // normal is assumed to be unit length
  23947. const x = normal.x,
  23948. y = normal.y,
  23949. z = normal.z;
  23950. const coeff = this.coefficients; // band 0
  23951. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23952. target.addScaledVector(coeff[1], 0.488603 * y);
  23953. target.addScaledVector(coeff[2], 0.488603 * z);
  23954. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23955. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23956. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23957. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23958. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23959. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23960. return target;
  23961. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23962. // target is a Vector3
  23963. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23964. getIrradianceAt(normal, target) {
  23965. // normal is assumed to be unit length
  23966. const x = normal.x,
  23967. y = normal.y,
  23968. z = normal.z;
  23969. const coeff = this.coefficients; // band 0
  23970. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23971. // band 1
  23972. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23973. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23974. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23975. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23976. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23977. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23978. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23979. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23980. return target;
  23981. }
  23982. add(sh) {
  23983. for (let i = 0; i < 9; i++) {
  23984. this.coefficients[i].add(sh.coefficients[i]);
  23985. }
  23986. return this;
  23987. }
  23988. addScaledSH(sh, s) {
  23989. for (let i = 0; i < 9; i++) {
  23990. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23991. }
  23992. return this;
  23993. }
  23994. scale(s) {
  23995. for (let i = 0; i < 9; i++) {
  23996. this.coefficients[i].multiplyScalar(s);
  23997. }
  23998. return this;
  23999. }
  24000. lerp(sh, alpha) {
  24001. for (let i = 0; i < 9; i++) {
  24002. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24003. }
  24004. return this;
  24005. }
  24006. equals(sh) {
  24007. for (let i = 0; i < 9; i++) {
  24008. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24009. return false;
  24010. }
  24011. }
  24012. return true;
  24013. }
  24014. copy(sh) {
  24015. return this.set(sh.coefficients);
  24016. }
  24017. clone() {
  24018. return new this.constructor().copy(this);
  24019. }
  24020. fromArray(array, offset = 0) {
  24021. const coefficients = this.coefficients;
  24022. for (let i = 0; i < 9; i++) {
  24023. coefficients[i].fromArray(array, offset + i * 3);
  24024. }
  24025. return this;
  24026. }
  24027. toArray(array = [], offset = 0) {
  24028. const coefficients = this.coefficients;
  24029. for (let i = 0; i < 9; i++) {
  24030. coefficients[i].toArray(array, offset + i * 3);
  24031. }
  24032. return array;
  24033. } // evaluate the basis functions
  24034. // shBasis is an Array[ 9 ]
  24035. static getBasisAt(normal, shBasis) {
  24036. // normal is assumed to be unit length
  24037. const x = normal.x,
  24038. y = normal.y,
  24039. z = normal.z; // band 0
  24040. shBasis[0] = 0.282095; // band 1
  24041. shBasis[1] = 0.488603 * y;
  24042. shBasis[2] = 0.488603 * z;
  24043. shBasis[3] = 0.488603 * x; // band 2
  24044. shBasis[4] = 1.092548 * x * y;
  24045. shBasis[5] = 1.092548 * y * z;
  24046. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24047. shBasis[7] = 1.092548 * x * z;
  24048. shBasis[8] = 0.546274 * (x * x - y * y);
  24049. }
  24050. }
  24051. class LightProbe extends Light {
  24052. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  24053. super(undefined, intensity);
  24054. this.isLightProbe = true;
  24055. this.sh = sh;
  24056. }
  24057. copy(source) {
  24058. super.copy(source);
  24059. this.sh.copy(source.sh);
  24060. return this;
  24061. }
  24062. fromJSON(json) {
  24063. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24064. this.sh.fromArray(json.sh);
  24065. return this;
  24066. }
  24067. toJSON(meta) {
  24068. const data = super.toJSON(meta);
  24069. data.object.sh = this.sh.toArray();
  24070. return data;
  24071. }
  24072. }
  24073. class MaterialLoader extends Loader {
  24074. constructor(manager) {
  24075. super(manager);
  24076. this.textures = {};
  24077. }
  24078. load(url, onLoad, onProgress, onError) {
  24079. const scope = this;
  24080. const loader = new FileLoader(scope.manager);
  24081. loader.setPath(scope.path);
  24082. loader.setRequestHeader(scope.requestHeader);
  24083. loader.setWithCredentials(scope.withCredentials);
  24084. loader.load(url, function (text) {
  24085. try {
  24086. onLoad(scope.parse(JSON.parse(text)));
  24087. } catch (e) {
  24088. if (onError) {
  24089. onError(e);
  24090. } else {
  24091. console.error(e);
  24092. }
  24093. scope.manager.itemError(url);
  24094. }
  24095. }, onProgress, onError);
  24096. }
  24097. parse(json) {
  24098. const textures = this.textures;
  24099. function getTexture(name) {
  24100. if (textures[name] === undefined) {
  24101. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24102. }
  24103. return textures[name];
  24104. }
  24105. const material = MaterialLoader.createMaterialFromType(json.type);
  24106. if (json.uuid !== undefined) material.uuid = json.uuid;
  24107. if (json.name !== undefined) material.name = json.name;
  24108. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24109. if (json.roughness !== undefined) material.roughness = json.roughness;
  24110. if (json.metalness !== undefined) material.metalness = json.metalness;
  24111. if (json.sheen !== undefined) material.sheen = json.sheen;
  24112. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  24113. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  24114. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24115. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24116. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  24117. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  24118. if (json.shininess !== undefined) material.shininess = json.shininess;
  24119. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24120. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24121. if (json.iridescence !== undefined) material.iridescence = json.iridescence;
  24122. if (json.iridescenceIOR !== undefined) material.iridescenceIOR = json.iridescenceIOR;
  24123. if (json.iridescenceThicknessRange !== undefined) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24124. if (json.transmission !== undefined) material.transmission = json.transmission;
  24125. if (json.thickness !== undefined) material.thickness = json.thickness;
  24126. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  24127. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  24128. if (json.fog !== undefined) material.fog = json.fog;
  24129. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24130. if (json.blending !== undefined) material.blending = json.blending;
  24131. if (json.combine !== undefined) material.combine = json.combine;
  24132. if (json.side !== undefined) material.side = json.side;
  24133. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  24134. if (json.opacity !== undefined) material.opacity = json.opacity;
  24135. if (json.transparent !== undefined) material.transparent = json.transparent;
  24136. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24137. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24138. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24139. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24140. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24141. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24142. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24143. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24144. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24145. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24146. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24147. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24148. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24149. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24150. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24151. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24152. if (json.rotation !== undefined) material.rotation = json.rotation;
  24153. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24154. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24155. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24156. if (json.scale !== undefined) material.scale = json.scale;
  24157. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24158. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24159. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24160. if (json.dithering !== undefined) material.dithering = json.dithering;
  24161. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  24162. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  24163. if (json.visible !== undefined) material.visible = json.visible;
  24164. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24165. if (json.userData !== undefined) material.userData = json.userData;
  24166. if (json.vertexColors !== undefined) {
  24167. if (typeof json.vertexColors === 'number') {
  24168. material.vertexColors = json.vertexColors > 0 ? true : false;
  24169. } else {
  24170. material.vertexColors = json.vertexColors;
  24171. }
  24172. } // Shader Material
  24173. if (json.uniforms !== undefined) {
  24174. for (const name in json.uniforms) {
  24175. const uniform = json.uniforms[name];
  24176. material.uniforms[name] = {};
  24177. switch (uniform.type) {
  24178. case 't':
  24179. material.uniforms[name].value = getTexture(uniform.value);
  24180. break;
  24181. case 'c':
  24182. material.uniforms[name].value = new Color().setHex(uniform.value);
  24183. break;
  24184. case 'v2':
  24185. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24186. break;
  24187. case 'v3':
  24188. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24189. break;
  24190. case 'v4':
  24191. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24192. break;
  24193. case 'm3':
  24194. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24195. break;
  24196. case 'm4':
  24197. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24198. break;
  24199. default:
  24200. material.uniforms[name].value = uniform.value;
  24201. }
  24202. }
  24203. }
  24204. if (json.defines !== undefined) material.defines = json.defines;
  24205. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24206. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24207. if (json.glslVersion !== undefined) material.glslVersion = json.glslVersion;
  24208. if (json.extensions !== undefined) {
  24209. for (const key in json.extensions) {
  24210. material.extensions[key] = json.extensions[key];
  24211. }
  24212. } // for PointsMaterial
  24213. if (json.size !== undefined) material.size = json.size;
  24214. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24215. if (json.map !== undefined) material.map = getTexture(json.map);
  24216. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24217. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24218. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24219. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24220. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24221. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24222. if (json.normalScale !== undefined) {
  24223. let normalScale = json.normalScale;
  24224. if (Array.isArray(normalScale) === false) {
  24225. // Blender exporter used to export a scalar. See #7459
  24226. normalScale = [normalScale, normalScale];
  24227. }
  24228. material.normalScale = new Vector2().fromArray(normalScale);
  24229. }
  24230. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24231. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24232. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24233. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24234. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24235. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24236. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24237. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24238. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  24239. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  24240. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24241. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24242. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24243. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24244. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24245. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24246. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24247. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24248. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24249. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24250. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24251. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24252. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24253. if (json.iridescenceMap !== undefined) material.iridescenceMap = getTexture(json.iridescenceMap);
  24254. if (json.iridescenceThicknessMap !== undefined) material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap);
  24255. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24256. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  24257. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24258. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24259. return material;
  24260. }
  24261. setTextures(value) {
  24262. this.textures = value;
  24263. return this;
  24264. }
  24265. static createMaterialFromType(type) {
  24266. const materialLib = {
  24267. ShadowMaterial,
  24268. SpriteMaterial,
  24269. RawShaderMaterial,
  24270. ShaderMaterial,
  24271. PointsMaterial,
  24272. MeshPhysicalMaterial,
  24273. MeshStandardMaterial,
  24274. MeshPhongMaterial,
  24275. MeshToonMaterial,
  24276. MeshNormalMaterial,
  24277. MeshLambertMaterial,
  24278. MeshDepthMaterial,
  24279. MeshDistanceMaterial,
  24280. MeshBasicMaterial,
  24281. MeshMatcapMaterial,
  24282. LineDashedMaterial,
  24283. LineBasicMaterial,
  24284. Material
  24285. };
  24286. return new materialLib[type]();
  24287. }
  24288. }
  24289. class LoaderUtils {
  24290. static decodeText(array) {
  24291. if (typeof TextDecoder !== 'undefined') {
  24292. return new TextDecoder().decode(array);
  24293. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24294. // throws a "maximum call stack size exceeded" error for large arrays.
  24295. let s = '';
  24296. for (let i = 0, il = array.length; i < il; i++) {
  24297. // Implicitly assumes little-endian.
  24298. s += String.fromCharCode(array[i]);
  24299. }
  24300. try {
  24301. // merges multi-byte utf-8 characters.
  24302. return decodeURIComponent(escape(s));
  24303. } catch (e) {
  24304. // see #16358
  24305. return s;
  24306. }
  24307. }
  24308. static extractUrlBase(url) {
  24309. const index = url.lastIndexOf('/');
  24310. if (index === -1) return './';
  24311. return url.slice(0, index + 1);
  24312. }
  24313. static resolveURL(url, path) {
  24314. // Invalid URL
  24315. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24316. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24317. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24318. } // Absolute URL http://,https://,//
  24319. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24320. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24321. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24322. return path + url;
  24323. }
  24324. }
  24325. class InstancedBufferGeometry extends BufferGeometry {
  24326. constructor() {
  24327. super();
  24328. this.isInstancedBufferGeometry = true;
  24329. this.type = 'InstancedBufferGeometry';
  24330. this.instanceCount = Infinity;
  24331. }
  24332. copy(source) {
  24333. super.copy(source);
  24334. this.instanceCount = source.instanceCount;
  24335. return this;
  24336. }
  24337. clone() {
  24338. return new this.constructor().copy(this);
  24339. }
  24340. toJSON() {
  24341. const data = super.toJSON(this);
  24342. data.instanceCount = this.instanceCount;
  24343. data.isInstancedBufferGeometry = true;
  24344. return data;
  24345. }
  24346. }
  24347. class BufferGeometryLoader extends Loader {
  24348. constructor(manager) {
  24349. super(manager);
  24350. }
  24351. load(url, onLoad, onProgress, onError) {
  24352. const scope = this;
  24353. const loader = new FileLoader(scope.manager);
  24354. loader.setPath(scope.path);
  24355. loader.setRequestHeader(scope.requestHeader);
  24356. loader.setWithCredentials(scope.withCredentials);
  24357. loader.load(url, function (text) {
  24358. try {
  24359. onLoad(scope.parse(JSON.parse(text)));
  24360. } catch (e) {
  24361. if (onError) {
  24362. onError(e);
  24363. } else {
  24364. console.error(e);
  24365. }
  24366. scope.manager.itemError(url);
  24367. }
  24368. }, onProgress, onError);
  24369. }
  24370. parse(json) {
  24371. const interleavedBufferMap = {};
  24372. const arrayBufferMap = {};
  24373. function getInterleavedBuffer(json, uuid) {
  24374. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24375. const interleavedBuffers = json.interleavedBuffers;
  24376. const interleavedBuffer = interleavedBuffers[uuid];
  24377. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24378. const array = getTypedArray(interleavedBuffer.type, buffer);
  24379. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24380. ib.uuid = interleavedBuffer.uuid;
  24381. interleavedBufferMap[uuid] = ib;
  24382. return ib;
  24383. }
  24384. function getArrayBuffer(json, uuid) {
  24385. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24386. const arrayBuffers = json.arrayBuffers;
  24387. const arrayBuffer = arrayBuffers[uuid];
  24388. const ab = new Uint32Array(arrayBuffer).buffer;
  24389. arrayBufferMap[uuid] = ab;
  24390. return ab;
  24391. }
  24392. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24393. const index = json.data.index;
  24394. if (index !== undefined) {
  24395. const typedArray = getTypedArray(index.type, index.array);
  24396. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24397. }
  24398. const attributes = json.data.attributes;
  24399. for (const key in attributes) {
  24400. const attribute = attributes[key];
  24401. let bufferAttribute;
  24402. if (attribute.isInterleavedBufferAttribute) {
  24403. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24404. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24405. } else {
  24406. const typedArray = getTypedArray(attribute.type, attribute.array);
  24407. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24408. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24409. }
  24410. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24411. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24412. if (attribute.updateRange !== undefined) {
  24413. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24414. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24415. }
  24416. geometry.setAttribute(key, bufferAttribute);
  24417. }
  24418. const morphAttributes = json.data.morphAttributes;
  24419. if (morphAttributes) {
  24420. for (const key in morphAttributes) {
  24421. const attributeArray = morphAttributes[key];
  24422. const array = [];
  24423. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24424. const attribute = attributeArray[i];
  24425. let bufferAttribute;
  24426. if (attribute.isInterleavedBufferAttribute) {
  24427. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24428. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24429. } else {
  24430. const typedArray = getTypedArray(attribute.type, attribute.array);
  24431. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24432. }
  24433. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24434. array.push(bufferAttribute);
  24435. }
  24436. geometry.morphAttributes[key] = array;
  24437. }
  24438. }
  24439. const morphTargetsRelative = json.data.morphTargetsRelative;
  24440. if (morphTargetsRelative) {
  24441. geometry.morphTargetsRelative = true;
  24442. }
  24443. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24444. if (groups !== undefined) {
  24445. for (let i = 0, n = groups.length; i !== n; ++i) {
  24446. const group = groups[i];
  24447. geometry.addGroup(group.start, group.count, group.materialIndex);
  24448. }
  24449. }
  24450. const boundingSphere = json.data.boundingSphere;
  24451. if (boundingSphere !== undefined) {
  24452. const center = new Vector3();
  24453. if (boundingSphere.center !== undefined) {
  24454. center.fromArray(boundingSphere.center);
  24455. }
  24456. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24457. }
  24458. if (json.name) geometry.name = json.name;
  24459. if (json.userData) geometry.userData = json.userData;
  24460. return geometry;
  24461. }
  24462. }
  24463. class ObjectLoader extends Loader {
  24464. constructor(manager) {
  24465. super(manager);
  24466. }
  24467. load(url, onLoad, onProgress, onError) {
  24468. const scope = this;
  24469. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24470. this.resourcePath = this.resourcePath || path;
  24471. const loader = new FileLoader(this.manager);
  24472. loader.setPath(this.path);
  24473. loader.setRequestHeader(this.requestHeader);
  24474. loader.setWithCredentials(this.withCredentials);
  24475. loader.load(url, function (text) {
  24476. let json = null;
  24477. try {
  24478. json = JSON.parse(text);
  24479. } catch (error) {
  24480. if (onError !== undefined) onError(error);
  24481. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24482. return;
  24483. }
  24484. const metadata = json.metadata;
  24485. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24486. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24487. return;
  24488. }
  24489. scope.parse(json, onLoad);
  24490. }, onProgress, onError);
  24491. }
  24492. async loadAsync(url, onProgress) {
  24493. const scope = this;
  24494. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24495. this.resourcePath = this.resourcePath || path;
  24496. const loader = new FileLoader(this.manager);
  24497. loader.setPath(this.path);
  24498. loader.setRequestHeader(this.requestHeader);
  24499. loader.setWithCredentials(this.withCredentials);
  24500. const text = await loader.loadAsync(url, onProgress);
  24501. const json = JSON.parse(text);
  24502. const metadata = json.metadata;
  24503. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24504. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24505. }
  24506. return await scope.parseAsync(json);
  24507. }
  24508. parse(json, onLoad) {
  24509. const animations = this.parseAnimations(json.animations);
  24510. const shapes = this.parseShapes(json.shapes);
  24511. const geometries = this.parseGeometries(json.geometries, shapes);
  24512. const images = this.parseImages(json.images, function () {
  24513. if (onLoad !== undefined) onLoad(object);
  24514. });
  24515. const textures = this.parseTextures(json.textures, images);
  24516. const materials = this.parseMaterials(json.materials, textures);
  24517. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24518. const skeletons = this.parseSkeletons(json.skeletons, object);
  24519. this.bindSkeletons(object, skeletons); //
  24520. if (onLoad !== undefined) {
  24521. let hasImages = false;
  24522. for (const uuid in images) {
  24523. if (images[uuid].data instanceof HTMLImageElement) {
  24524. hasImages = true;
  24525. break;
  24526. }
  24527. }
  24528. if (hasImages === false) onLoad(object);
  24529. }
  24530. return object;
  24531. }
  24532. async parseAsync(json) {
  24533. const animations = this.parseAnimations(json.animations);
  24534. const shapes = this.parseShapes(json.shapes);
  24535. const geometries = this.parseGeometries(json.geometries, shapes);
  24536. const images = await this.parseImagesAsync(json.images);
  24537. const textures = this.parseTextures(json.textures, images);
  24538. const materials = this.parseMaterials(json.materials, textures);
  24539. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24540. const skeletons = this.parseSkeletons(json.skeletons, object);
  24541. this.bindSkeletons(object, skeletons);
  24542. return object;
  24543. }
  24544. parseShapes(json) {
  24545. const shapes = {};
  24546. if (json !== undefined) {
  24547. for (let i = 0, l = json.length; i < l; i++) {
  24548. const shape = new Shape().fromJSON(json[i]);
  24549. shapes[shape.uuid] = shape;
  24550. }
  24551. }
  24552. return shapes;
  24553. }
  24554. parseSkeletons(json, object) {
  24555. const skeletons = {};
  24556. const bones = {}; // generate bone lookup table
  24557. object.traverse(function (child) {
  24558. if (child.isBone) bones[child.uuid] = child;
  24559. }); // create skeletons
  24560. if (json !== undefined) {
  24561. for (let i = 0, l = json.length; i < l; i++) {
  24562. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24563. skeletons[skeleton.uuid] = skeleton;
  24564. }
  24565. }
  24566. return skeletons;
  24567. }
  24568. parseGeometries(json, shapes) {
  24569. const geometries = {};
  24570. if (json !== undefined) {
  24571. const bufferGeometryLoader = new BufferGeometryLoader();
  24572. for (let i = 0, l = json.length; i < l; i++) {
  24573. let geometry;
  24574. const data = json[i];
  24575. switch (data.type) {
  24576. case 'BufferGeometry':
  24577. case 'InstancedBufferGeometry':
  24578. geometry = bufferGeometryLoader.parse(data);
  24579. break;
  24580. default:
  24581. if (data.type in Geometries) {
  24582. geometry = Geometries[data.type].fromJSON(data, shapes);
  24583. } else {
  24584. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24585. }
  24586. }
  24587. geometry.uuid = data.uuid;
  24588. if (data.name !== undefined) geometry.name = data.name;
  24589. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24590. geometries[data.uuid] = geometry;
  24591. }
  24592. }
  24593. return geometries;
  24594. }
  24595. parseMaterials(json, textures) {
  24596. const cache = {}; // MultiMaterial
  24597. const materials = {};
  24598. if (json !== undefined) {
  24599. const loader = new MaterialLoader();
  24600. loader.setTextures(textures);
  24601. for (let i = 0, l = json.length; i < l; i++) {
  24602. const data = json[i];
  24603. if (cache[data.uuid] === undefined) {
  24604. cache[data.uuid] = loader.parse(data);
  24605. }
  24606. materials[data.uuid] = cache[data.uuid];
  24607. }
  24608. }
  24609. return materials;
  24610. }
  24611. parseAnimations(json) {
  24612. const animations = {};
  24613. if (json !== undefined) {
  24614. for (let i = 0; i < json.length; i++) {
  24615. const data = json[i];
  24616. const clip = AnimationClip.parse(data);
  24617. animations[clip.uuid] = clip;
  24618. }
  24619. }
  24620. return animations;
  24621. }
  24622. parseImages(json, onLoad) {
  24623. const scope = this;
  24624. const images = {};
  24625. let loader;
  24626. function loadImage(url) {
  24627. scope.manager.itemStart(url);
  24628. return loader.load(url, function () {
  24629. scope.manager.itemEnd(url);
  24630. }, undefined, function () {
  24631. scope.manager.itemError(url);
  24632. scope.manager.itemEnd(url);
  24633. });
  24634. }
  24635. function deserializeImage(image) {
  24636. if (typeof image === 'string') {
  24637. const url = image;
  24638. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24639. return loadImage(path);
  24640. } else {
  24641. if (image.data) {
  24642. return {
  24643. data: getTypedArray(image.type, image.data),
  24644. width: image.width,
  24645. height: image.height
  24646. };
  24647. } else {
  24648. return null;
  24649. }
  24650. }
  24651. }
  24652. if (json !== undefined && json.length > 0) {
  24653. const manager = new LoadingManager(onLoad);
  24654. loader = new ImageLoader(manager);
  24655. loader.setCrossOrigin(this.crossOrigin);
  24656. for (let i = 0, il = json.length; i < il; i++) {
  24657. const image = json[i];
  24658. const url = image.url;
  24659. if (Array.isArray(url)) {
  24660. // load array of images e.g CubeTexture
  24661. const imageArray = [];
  24662. for (let j = 0, jl = url.length; j < jl; j++) {
  24663. const currentUrl = url[j];
  24664. const deserializedImage = deserializeImage(currentUrl);
  24665. if (deserializedImage !== null) {
  24666. if (deserializedImage instanceof HTMLImageElement) {
  24667. imageArray.push(deserializedImage);
  24668. } else {
  24669. // special case: handle array of data textures for cube textures
  24670. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24671. }
  24672. }
  24673. }
  24674. images[image.uuid] = new Source(imageArray);
  24675. } else {
  24676. // load single image
  24677. const deserializedImage = deserializeImage(image.url);
  24678. images[image.uuid] = new Source(deserializedImage);
  24679. }
  24680. }
  24681. }
  24682. return images;
  24683. }
  24684. async parseImagesAsync(json) {
  24685. const scope = this;
  24686. const images = {};
  24687. let loader;
  24688. async function deserializeImage(image) {
  24689. if (typeof image === 'string') {
  24690. const url = image;
  24691. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24692. return await loader.loadAsync(path);
  24693. } else {
  24694. if (image.data) {
  24695. return {
  24696. data: getTypedArray(image.type, image.data),
  24697. width: image.width,
  24698. height: image.height
  24699. };
  24700. } else {
  24701. return null;
  24702. }
  24703. }
  24704. }
  24705. if (json !== undefined && json.length > 0) {
  24706. loader = new ImageLoader(this.manager);
  24707. loader.setCrossOrigin(this.crossOrigin);
  24708. for (let i = 0, il = json.length; i < il; i++) {
  24709. const image = json[i];
  24710. const url = image.url;
  24711. if (Array.isArray(url)) {
  24712. // load array of images e.g CubeTexture
  24713. const imageArray = [];
  24714. for (let j = 0, jl = url.length; j < jl; j++) {
  24715. const currentUrl = url[j];
  24716. const deserializedImage = await deserializeImage(currentUrl);
  24717. if (deserializedImage !== null) {
  24718. if (deserializedImage instanceof HTMLImageElement) {
  24719. imageArray.push(deserializedImage);
  24720. } else {
  24721. // special case: handle array of data textures for cube textures
  24722. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24723. }
  24724. }
  24725. }
  24726. images[image.uuid] = new Source(imageArray);
  24727. } else {
  24728. // load single image
  24729. const deserializedImage = await deserializeImage(image.url);
  24730. images[image.uuid] = new Source(deserializedImage);
  24731. }
  24732. }
  24733. }
  24734. return images;
  24735. }
  24736. parseTextures(json, images) {
  24737. function parseConstant(value, type) {
  24738. if (typeof value === 'number') return value;
  24739. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24740. return type[value];
  24741. }
  24742. const textures = {};
  24743. if (json !== undefined) {
  24744. for (let i = 0, l = json.length; i < l; i++) {
  24745. const data = json[i];
  24746. if (data.image === undefined) {
  24747. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24748. }
  24749. if (images[data.image] === undefined) {
  24750. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24751. }
  24752. const source = images[data.image];
  24753. const image = source.data;
  24754. let texture;
  24755. if (Array.isArray(image)) {
  24756. texture = new CubeTexture();
  24757. if (image.length === 6) texture.needsUpdate = true;
  24758. } else {
  24759. if (image && image.data) {
  24760. texture = new DataTexture();
  24761. } else {
  24762. texture = new Texture();
  24763. }
  24764. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24765. }
  24766. texture.source = source;
  24767. texture.uuid = data.uuid;
  24768. if (data.name !== undefined) texture.name = data.name;
  24769. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24770. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24771. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24772. if (data.center !== undefined) texture.center.fromArray(data.center);
  24773. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24774. if (data.wrap !== undefined) {
  24775. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24776. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24777. }
  24778. if (data.format !== undefined) texture.format = data.format;
  24779. if (data.type !== undefined) texture.type = data.type;
  24780. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24781. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24782. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24783. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24784. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24785. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24786. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24787. if (data.userData !== undefined) texture.userData = data.userData;
  24788. textures[data.uuid] = texture;
  24789. }
  24790. }
  24791. return textures;
  24792. }
  24793. parseObject(data, geometries, materials, textures, animations) {
  24794. let object;
  24795. function getGeometry(name) {
  24796. if (geometries[name] === undefined) {
  24797. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24798. }
  24799. return geometries[name];
  24800. }
  24801. function getMaterial(name) {
  24802. if (name === undefined) return undefined;
  24803. if (Array.isArray(name)) {
  24804. const array = [];
  24805. for (let i = 0, l = name.length; i < l; i++) {
  24806. const uuid = name[i];
  24807. if (materials[uuid] === undefined) {
  24808. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24809. }
  24810. array.push(materials[uuid]);
  24811. }
  24812. return array;
  24813. }
  24814. if (materials[name] === undefined) {
  24815. console.warn('THREE.ObjectLoader: Undefined material', name);
  24816. }
  24817. return materials[name];
  24818. }
  24819. function getTexture(uuid) {
  24820. if (textures[uuid] === undefined) {
  24821. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24822. }
  24823. return textures[uuid];
  24824. }
  24825. let geometry, material;
  24826. switch (data.type) {
  24827. case 'Scene':
  24828. object = new Scene();
  24829. if (data.background !== undefined) {
  24830. if (Number.isInteger(data.background)) {
  24831. object.background = new Color(data.background);
  24832. } else {
  24833. object.background = getTexture(data.background);
  24834. }
  24835. }
  24836. if (data.environment !== undefined) {
  24837. object.environment = getTexture(data.environment);
  24838. }
  24839. if (data.fog !== undefined) {
  24840. if (data.fog.type === 'Fog') {
  24841. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24842. } else if (data.fog.type === 'FogExp2') {
  24843. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24844. }
  24845. }
  24846. break;
  24847. case 'PerspectiveCamera':
  24848. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24849. if (data.focus !== undefined) object.focus = data.focus;
  24850. if (data.zoom !== undefined) object.zoom = data.zoom;
  24851. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24852. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24853. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24854. break;
  24855. case 'OrthographicCamera':
  24856. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24857. if (data.zoom !== undefined) object.zoom = data.zoom;
  24858. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24859. break;
  24860. case 'AmbientLight':
  24861. object = new AmbientLight(data.color, data.intensity);
  24862. break;
  24863. case 'DirectionalLight':
  24864. object = new DirectionalLight(data.color, data.intensity);
  24865. break;
  24866. case 'PointLight':
  24867. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24868. break;
  24869. case 'RectAreaLight':
  24870. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24871. break;
  24872. case 'SpotLight':
  24873. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24874. break;
  24875. case 'HemisphereLight':
  24876. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24877. break;
  24878. case 'LightProbe':
  24879. object = new LightProbe().fromJSON(data);
  24880. break;
  24881. case 'SkinnedMesh':
  24882. geometry = getGeometry(data.geometry);
  24883. material = getMaterial(data.material);
  24884. object = new SkinnedMesh(geometry, material);
  24885. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24886. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24887. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24888. break;
  24889. case 'Mesh':
  24890. geometry = getGeometry(data.geometry);
  24891. material = getMaterial(data.material);
  24892. object = new Mesh(geometry, material);
  24893. break;
  24894. case 'InstancedMesh':
  24895. geometry = getGeometry(data.geometry);
  24896. material = getMaterial(data.material);
  24897. const count = data.count;
  24898. const instanceMatrix = data.instanceMatrix;
  24899. const instanceColor = data.instanceColor;
  24900. object = new InstancedMesh(geometry, material, count);
  24901. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24902. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24903. break;
  24904. case 'LOD':
  24905. object = new LOD();
  24906. break;
  24907. case 'Line':
  24908. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24909. break;
  24910. case 'LineLoop':
  24911. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24912. break;
  24913. case 'LineSegments':
  24914. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24915. break;
  24916. case 'PointCloud':
  24917. case 'Points':
  24918. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24919. break;
  24920. case 'Sprite':
  24921. object = new Sprite(getMaterial(data.material));
  24922. break;
  24923. case 'Group':
  24924. object = new Group();
  24925. break;
  24926. case 'Bone':
  24927. object = new Bone();
  24928. break;
  24929. default:
  24930. object = new Object3D();
  24931. }
  24932. object.uuid = data.uuid;
  24933. if (data.name !== undefined) object.name = data.name;
  24934. if (data.matrix !== undefined) {
  24935. object.matrix.fromArray(data.matrix);
  24936. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24937. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24938. } else {
  24939. if (data.position !== undefined) object.position.fromArray(data.position);
  24940. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24941. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24942. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24943. }
  24944. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24945. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24946. if (data.shadow) {
  24947. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24948. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24949. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24950. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24951. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24952. }
  24953. if (data.visible !== undefined) object.visible = data.visible;
  24954. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24955. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24956. if (data.userData !== undefined) object.userData = data.userData;
  24957. if (data.layers !== undefined) object.layers.mask = data.layers;
  24958. if (data.children !== undefined) {
  24959. const children = data.children;
  24960. for (let i = 0; i < children.length; i++) {
  24961. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24962. }
  24963. }
  24964. if (data.animations !== undefined) {
  24965. const objectAnimations = data.animations;
  24966. for (let i = 0; i < objectAnimations.length; i++) {
  24967. const uuid = objectAnimations[i];
  24968. object.animations.push(animations[uuid]);
  24969. }
  24970. }
  24971. if (data.type === 'LOD') {
  24972. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24973. const levels = data.levels;
  24974. for (let l = 0; l < levels.length; l++) {
  24975. const level = levels[l];
  24976. const child = object.getObjectByProperty('uuid', level.object);
  24977. if (child !== undefined) {
  24978. object.addLevel(child, level.distance);
  24979. }
  24980. }
  24981. }
  24982. return object;
  24983. }
  24984. bindSkeletons(object, skeletons) {
  24985. if (Object.keys(skeletons).length === 0) return;
  24986. object.traverse(function (child) {
  24987. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24988. const skeleton = skeletons[child.skeleton];
  24989. if (skeleton === undefined) {
  24990. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24991. } else {
  24992. child.bind(skeleton, child.bindMatrix);
  24993. }
  24994. }
  24995. });
  24996. }
  24997. }
  24998. const TEXTURE_MAPPING = {
  24999. UVMapping: UVMapping,
  25000. CubeReflectionMapping: CubeReflectionMapping,
  25001. CubeRefractionMapping: CubeRefractionMapping,
  25002. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25003. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25004. CubeUVReflectionMapping: CubeUVReflectionMapping
  25005. };
  25006. const TEXTURE_WRAPPING = {
  25007. RepeatWrapping: RepeatWrapping,
  25008. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25009. MirroredRepeatWrapping: MirroredRepeatWrapping
  25010. };
  25011. const TEXTURE_FILTER = {
  25012. NearestFilter: NearestFilter,
  25013. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25014. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25015. LinearFilter: LinearFilter,
  25016. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25017. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25018. };
  25019. class ImageBitmapLoader extends Loader {
  25020. constructor(manager) {
  25021. super(manager);
  25022. this.isImageBitmapLoader = true;
  25023. if (typeof createImageBitmap === 'undefined') {
  25024. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25025. }
  25026. if (typeof fetch === 'undefined') {
  25027. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25028. }
  25029. this.options = {
  25030. premultiplyAlpha: 'none'
  25031. };
  25032. }
  25033. setOptions(options) {
  25034. this.options = options;
  25035. return this;
  25036. }
  25037. load(url, onLoad, onProgress, onError) {
  25038. if (url === undefined) url = '';
  25039. if (this.path !== undefined) url = this.path + url;
  25040. url = this.manager.resolveURL(url);
  25041. const scope = this;
  25042. const cached = Cache.get(url);
  25043. if (cached !== undefined) {
  25044. scope.manager.itemStart(url);
  25045. setTimeout(function () {
  25046. if (onLoad) onLoad(cached);
  25047. scope.manager.itemEnd(url);
  25048. }, 0);
  25049. return cached;
  25050. }
  25051. const fetchOptions = {};
  25052. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25053. fetchOptions.headers = this.requestHeader;
  25054. fetch(url, fetchOptions).then(function (res) {
  25055. return res.blob();
  25056. }).then(function (blob) {
  25057. return createImageBitmap(blob, Object.assign(scope.options, {
  25058. colorSpaceConversion: 'none'
  25059. }));
  25060. }).then(function (imageBitmap) {
  25061. Cache.add(url, imageBitmap);
  25062. if (onLoad) onLoad(imageBitmap);
  25063. scope.manager.itemEnd(url);
  25064. }).catch(function (e) {
  25065. if (onError) onError(e);
  25066. scope.manager.itemError(url);
  25067. scope.manager.itemEnd(url);
  25068. });
  25069. scope.manager.itemStart(url);
  25070. }
  25071. }
  25072. let _context;
  25073. const AudioContext = {
  25074. getContext: function () {
  25075. if (_context === undefined) {
  25076. _context = new (window.AudioContext || window.webkitAudioContext)();
  25077. }
  25078. return _context;
  25079. },
  25080. setContext: function (value) {
  25081. _context = value;
  25082. }
  25083. };
  25084. class AudioLoader extends Loader {
  25085. constructor(manager) {
  25086. super(manager);
  25087. }
  25088. load(url, onLoad, onProgress, onError) {
  25089. const scope = this;
  25090. const loader = new FileLoader(this.manager);
  25091. loader.setResponseType('arraybuffer');
  25092. loader.setPath(this.path);
  25093. loader.setRequestHeader(this.requestHeader);
  25094. loader.setWithCredentials(this.withCredentials);
  25095. loader.load(url, function (buffer) {
  25096. try {
  25097. // Create a copy of the buffer. The `decodeAudioData` method
  25098. // detaches the buffer when complete, preventing reuse.
  25099. const bufferCopy = buffer.slice(0);
  25100. const context = AudioContext.getContext();
  25101. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25102. onLoad(audioBuffer);
  25103. });
  25104. } catch (e) {
  25105. if (onError) {
  25106. onError(e);
  25107. } else {
  25108. console.error(e);
  25109. }
  25110. scope.manager.itemError(url);
  25111. }
  25112. }, onProgress, onError);
  25113. }
  25114. }
  25115. class HemisphereLightProbe extends LightProbe {
  25116. constructor(skyColor, groundColor, intensity = 1) {
  25117. super(undefined, intensity);
  25118. this.isHemisphereLightProbe = true;
  25119. const color1 = new Color().set(skyColor);
  25120. const color2 = new Color().set(groundColor);
  25121. const sky = new Vector3(color1.r, color1.g, color1.b);
  25122. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25123. const c0 = Math.sqrt(Math.PI);
  25124. const c1 = c0 * Math.sqrt(0.75);
  25125. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25126. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25127. }
  25128. }
  25129. class AmbientLightProbe extends LightProbe {
  25130. constructor(color, intensity = 1) {
  25131. super(undefined, intensity);
  25132. this.isAmbientLightProbe = true;
  25133. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25134. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25135. }
  25136. }
  25137. const _eyeRight = /*@__PURE__*/new Matrix4();
  25138. const _eyeLeft = /*@__PURE__*/new Matrix4();
  25139. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  25140. class StereoCamera {
  25141. constructor() {
  25142. this.type = 'StereoCamera';
  25143. this.aspect = 1;
  25144. this.eyeSep = 0.064;
  25145. this.cameraL = new PerspectiveCamera();
  25146. this.cameraL.layers.enable(1);
  25147. this.cameraL.matrixAutoUpdate = false;
  25148. this.cameraR = new PerspectiveCamera();
  25149. this.cameraR.layers.enable(2);
  25150. this.cameraR.matrixAutoUpdate = false;
  25151. this._cache = {
  25152. focus: null,
  25153. fov: null,
  25154. aspect: null,
  25155. near: null,
  25156. far: null,
  25157. zoom: null,
  25158. eyeSep: null
  25159. };
  25160. }
  25161. update(camera) {
  25162. const cache = this._cache;
  25163. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25164. if (needsUpdate) {
  25165. cache.focus = camera.focus;
  25166. cache.fov = camera.fov;
  25167. cache.aspect = camera.aspect * this.aspect;
  25168. cache.near = camera.near;
  25169. cache.far = camera.far;
  25170. cache.zoom = camera.zoom;
  25171. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25172. // http://paulbourke.net/stereographics/stereorender/
  25173. _projectionMatrix.copy(camera.projectionMatrix);
  25174. const eyeSepHalf = cache.eyeSep / 2;
  25175. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25176. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25177. let xmin, xmax; // translate xOffset
  25178. _eyeLeft.elements[12] = -eyeSepHalf;
  25179. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25180. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25181. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25182. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25183. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25184. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  25185. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25186. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25187. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25188. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25189. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  25190. }
  25191. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25192. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25193. }
  25194. }
  25195. class Clock {
  25196. constructor(autoStart = true) {
  25197. this.autoStart = autoStart;
  25198. this.startTime = 0;
  25199. this.oldTime = 0;
  25200. this.elapsedTime = 0;
  25201. this.running = false;
  25202. }
  25203. start() {
  25204. this.startTime = now();
  25205. this.oldTime = this.startTime;
  25206. this.elapsedTime = 0;
  25207. this.running = true;
  25208. }
  25209. stop() {
  25210. this.getElapsedTime();
  25211. this.running = false;
  25212. this.autoStart = false;
  25213. }
  25214. getElapsedTime() {
  25215. this.getDelta();
  25216. return this.elapsedTime;
  25217. }
  25218. getDelta() {
  25219. let diff = 0;
  25220. if (this.autoStart && !this.running) {
  25221. this.start();
  25222. return 0;
  25223. }
  25224. if (this.running) {
  25225. const newTime = now();
  25226. diff = (newTime - this.oldTime) / 1000;
  25227. this.oldTime = newTime;
  25228. this.elapsedTime += diff;
  25229. }
  25230. return diff;
  25231. }
  25232. }
  25233. function now() {
  25234. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25235. }
  25236. const _position$1 = /*@__PURE__*/new Vector3();
  25237. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  25238. const _scale$1 = /*@__PURE__*/new Vector3();
  25239. const _orientation$1 = /*@__PURE__*/new Vector3();
  25240. class AudioListener extends Object3D {
  25241. constructor() {
  25242. super();
  25243. this.type = 'AudioListener';
  25244. this.context = AudioContext.getContext();
  25245. this.gain = this.context.createGain();
  25246. this.gain.connect(this.context.destination);
  25247. this.filter = null;
  25248. this.timeDelta = 0; // private
  25249. this._clock = new Clock();
  25250. }
  25251. getInput() {
  25252. return this.gain;
  25253. }
  25254. removeFilter() {
  25255. if (this.filter !== null) {
  25256. this.gain.disconnect(this.filter);
  25257. this.filter.disconnect(this.context.destination);
  25258. this.gain.connect(this.context.destination);
  25259. this.filter = null;
  25260. }
  25261. return this;
  25262. }
  25263. getFilter() {
  25264. return this.filter;
  25265. }
  25266. setFilter(value) {
  25267. if (this.filter !== null) {
  25268. this.gain.disconnect(this.filter);
  25269. this.filter.disconnect(this.context.destination);
  25270. } else {
  25271. this.gain.disconnect(this.context.destination);
  25272. }
  25273. this.filter = value;
  25274. this.gain.connect(this.filter);
  25275. this.filter.connect(this.context.destination);
  25276. return this;
  25277. }
  25278. getMasterVolume() {
  25279. return this.gain.gain.value;
  25280. }
  25281. setMasterVolume(value) {
  25282. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25283. return this;
  25284. }
  25285. updateMatrixWorld(force) {
  25286. super.updateMatrixWorld(force);
  25287. const listener = this.context.listener;
  25288. const up = this.up;
  25289. this.timeDelta = this._clock.getDelta();
  25290. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25291. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25292. if (listener.positionX) {
  25293. // code path for Chrome (see #14393)
  25294. const endTime = this.context.currentTime + this.timeDelta;
  25295. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25296. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25297. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25298. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25299. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25300. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25301. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25302. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25303. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25304. } else {
  25305. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25306. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25307. }
  25308. }
  25309. }
  25310. class Audio extends Object3D {
  25311. constructor(listener) {
  25312. super();
  25313. this.type = 'Audio';
  25314. this.listener = listener;
  25315. this.context = listener.context;
  25316. this.gain = this.context.createGain();
  25317. this.gain.connect(listener.getInput());
  25318. this.autoplay = false;
  25319. this.buffer = null;
  25320. this.detune = 0;
  25321. this.loop = false;
  25322. this.loopStart = 0;
  25323. this.loopEnd = 0;
  25324. this.offset = 0;
  25325. this.duration = undefined;
  25326. this.playbackRate = 1;
  25327. this.isPlaying = false;
  25328. this.hasPlaybackControl = true;
  25329. this.source = null;
  25330. this.sourceType = 'empty';
  25331. this._startedAt = 0;
  25332. this._progress = 0;
  25333. this._connected = false;
  25334. this.filters = [];
  25335. }
  25336. getOutput() {
  25337. return this.gain;
  25338. }
  25339. setNodeSource(audioNode) {
  25340. this.hasPlaybackControl = false;
  25341. this.sourceType = 'audioNode';
  25342. this.source = audioNode;
  25343. this.connect();
  25344. return this;
  25345. }
  25346. setMediaElementSource(mediaElement) {
  25347. this.hasPlaybackControl = false;
  25348. this.sourceType = 'mediaNode';
  25349. this.source = this.context.createMediaElementSource(mediaElement);
  25350. this.connect();
  25351. return this;
  25352. }
  25353. setMediaStreamSource(mediaStream) {
  25354. this.hasPlaybackControl = false;
  25355. this.sourceType = 'mediaStreamNode';
  25356. this.source = this.context.createMediaStreamSource(mediaStream);
  25357. this.connect();
  25358. return this;
  25359. }
  25360. setBuffer(audioBuffer) {
  25361. this.buffer = audioBuffer;
  25362. this.sourceType = 'buffer';
  25363. if (this.autoplay) this.play();
  25364. return this;
  25365. }
  25366. play(delay = 0) {
  25367. if (this.isPlaying === true) {
  25368. console.warn('THREE.Audio: Audio is already playing.');
  25369. return;
  25370. }
  25371. if (this.hasPlaybackControl === false) {
  25372. console.warn('THREE.Audio: this Audio has no playback control.');
  25373. return;
  25374. }
  25375. this._startedAt = this.context.currentTime + delay;
  25376. const source = this.context.createBufferSource();
  25377. source.buffer = this.buffer;
  25378. source.loop = this.loop;
  25379. source.loopStart = this.loopStart;
  25380. source.loopEnd = this.loopEnd;
  25381. source.onended = this.onEnded.bind(this);
  25382. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25383. this.isPlaying = true;
  25384. this.source = source;
  25385. this.setDetune(this.detune);
  25386. this.setPlaybackRate(this.playbackRate);
  25387. return this.connect();
  25388. }
  25389. pause() {
  25390. if (this.hasPlaybackControl === false) {
  25391. console.warn('THREE.Audio: this Audio has no playback control.');
  25392. return;
  25393. }
  25394. if (this.isPlaying === true) {
  25395. // update current progress
  25396. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25397. if (this.loop === true) {
  25398. // ensure _progress does not exceed duration with looped audios
  25399. this._progress = this._progress % (this.duration || this.buffer.duration);
  25400. }
  25401. this.source.stop();
  25402. this.source.onended = null;
  25403. this.isPlaying = false;
  25404. }
  25405. return this;
  25406. }
  25407. stop() {
  25408. if (this.hasPlaybackControl === false) {
  25409. console.warn('THREE.Audio: this Audio has no playback control.');
  25410. return;
  25411. }
  25412. this._progress = 0;
  25413. this.source.stop();
  25414. this.source.onended = null;
  25415. this.isPlaying = false;
  25416. return this;
  25417. }
  25418. connect() {
  25419. if (this.filters.length > 0) {
  25420. this.source.connect(this.filters[0]);
  25421. for (let i = 1, l = this.filters.length; i < l; i++) {
  25422. this.filters[i - 1].connect(this.filters[i]);
  25423. }
  25424. this.filters[this.filters.length - 1].connect(this.getOutput());
  25425. } else {
  25426. this.source.connect(this.getOutput());
  25427. }
  25428. this._connected = true;
  25429. return this;
  25430. }
  25431. disconnect() {
  25432. if (this.filters.length > 0) {
  25433. this.source.disconnect(this.filters[0]);
  25434. for (let i = 1, l = this.filters.length; i < l; i++) {
  25435. this.filters[i - 1].disconnect(this.filters[i]);
  25436. }
  25437. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25438. } else {
  25439. this.source.disconnect(this.getOutput());
  25440. }
  25441. this._connected = false;
  25442. return this;
  25443. }
  25444. getFilters() {
  25445. return this.filters;
  25446. }
  25447. setFilters(value) {
  25448. if (!value) value = [];
  25449. if (this._connected === true) {
  25450. this.disconnect();
  25451. this.filters = value.slice();
  25452. this.connect();
  25453. } else {
  25454. this.filters = value.slice();
  25455. }
  25456. return this;
  25457. }
  25458. setDetune(value) {
  25459. this.detune = value;
  25460. if (this.source.detune === undefined) return; // only set detune when available
  25461. if (this.isPlaying === true) {
  25462. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25463. }
  25464. return this;
  25465. }
  25466. getDetune() {
  25467. return this.detune;
  25468. }
  25469. getFilter() {
  25470. return this.getFilters()[0];
  25471. }
  25472. setFilter(filter) {
  25473. return this.setFilters(filter ? [filter] : []);
  25474. }
  25475. setPlaybackRate(value) {
  25476. if (this.hasPlaybackControl === false) {
  25477. console.warn('THREE.Audio: this Audio has no playback control.');
  25478. return;
  25479. }
  25480. this.playbackRate = value;
  25481. if (this.isPlaying === true) {
  25482. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25483. }
  25484. return this;
  25485. }
  25486. getPlaybackRate() {
  25487. return this.playbackRate;
  25488. }
  25489. onEnded() {
  25490. this.isPlaying = false;
  25491. }
  25492. getLoop() {
  25493. if (this.hasPlaybackControl === false) {
  25494. console.warn('THREE.Audio: this Audio has no playback control.');
  25495. return false;
  25496. }
  25497. return this.loop;
  25498. }
  25499. setLoop(value) {
  25500. if (this.hasPlaybackControl === false) {
  25501. console.warn('THREE.Audio: this Audio has no playback control.');
  25502. return;
  25503. }
  25504. this.loop = value;
  25505. if (this.isPlaying === true) {
  25506. this.source.loop = this.loop;
  25507. }
  25508. return this;
  25509. }
  25510. setLoopStart(value) {
  25511. this.loopStart = value;
  25512. return this;
  25513. }
  25514. setLoopEnd(value) {
  25515. this.loopEnd = value;
  25516. return this;
  25517. }
  25518. getVolume() {
  25519. return this.gain.gain.value;
  25520. }
  25521. setVolume(value) {
  25522. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25523. return this;
  25524. }
  25525. }
  25526. const _position = /*@__PURE__*/new Vector3();
  25527. const _quaternion = /*@__PURE__*/new Quaternion();
  25528. const _scale = /*@__PURE__*/new Vector3();
  25529. const _orientation = /*@__PURE__*/new Vector3();
  25530. class PositionalAudio extends Audio {
  25531. constructor(listener) {
  25532. super(listener);
  25533. this.panner = this.context.createPanner();
  25534. this.panner.panningModel = 'HRTF';
  25535. this.panner.connect(this.gain);
  25536. }
  25537. disconnect() {
  25538. super.disconnect();
  25539. this.panner.disconnect(this.gain);
  25540. }
  25541. getOutput() {
  25542. return this.panner;
  25543. }
  25544. getRefDistance() {
  25545. return this.panner.refDistance;
  25546. }
  25547. setRefDistance(value) {
  25548. this.panner.refDistance = value;
  25549. return this;
  25550. }
  25551. getRolloffFactor() {
  25552. return this.panner.rolloffFactor;
  25553. }
  25554. setRolloffFactor(value) {
  25555. this.panner.rolloffFactor = value;
  25556. return this;
  25557. }
  25558. getDistanceModel() {
  25559. return this.panner.distanceModel;
  25560. }
  25561. setDistanceModel(value) {
  25562. this.panner.distanceModel = value;
  25563. return this;
  25564. }
  25565. getMaxDistance() {
  25566. return this.panner.maxDistance;
  25567. }
  25568. setMaxDistance(value) {
  25569. this.panner.maxDistance = value;
  25570. return this;
  25571. }
  25572. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25573. this.panner.coneInnerAngle = coneInnerAngle;
  25574. this.panner.coneOuterAngle = coneOuterAngle;
  25575. this.panner.coneOuterGain = coneOuterGain;
  25576. return this;
  25577. }
  25578. updateMatrixWorld(force) {
  25579. super.updateMatrixWorld(force);
  25580. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25581. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25582. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25583. const panner = this.panner;
  25584. if (panner.positionX) {
  25585. // code path for Chrome and Firefox (see #14393)
  25586. const endTime = this.context.currentTime + this.listener.timeDelta;
  25587. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25588. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25589. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25590. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25591. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25592. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25593. } else {
  25594. panner.setPosition(_position.x, _position.y, _position.z);
  25595. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25596. }
  25597. }
  25598. }
  25599. class AudioAnalyser {
  25600. constructor(audio, fftSize = 2048) {
  25601. this.analyser = audio.context.createAnalyser();
  25602. this.analyser.fftSize = fftSize;
  25603. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25604. audio.getOutput().connect(this.analyser);
  25605. }
  25606. getFrequencyData() {
  25607. this.analyser.getByteFrequencyData(this.data);
  25608. return this.data;
  25609. }
  25610. getAverageFrequency() {
  25611. let value = 0;
  25612. const data = this.getFrequencyData();
  25613. for (let i = 0; i < data.length; i++) {
  25614. value += data[i];
  25615. }
  25616. return value / data.length;
  25617. }
  25618. }
  25619. class PropertyMixer {
  25620. constructor(binding, typeName, valueSize) {
  25621. this.binding = binding;
  25622. this.valueSize = valueSize;
  25623. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25624. //
  25625. // interpolators can use .buffer as their .result
  25626. // the data then goes to 'incoming'
  25627. //
  25628. // 'accu0' and 'accu1' are used frame-interleaved for
  25629. // the cumulative result and are compared to detect
  25630. // changes
  25631. //
  25632. // 'orig' stores the original state of the property
  25633. //
  25634. // 'add' is used for additive cumulative results
  25635. //
  25636. // 'work' is optional and is only present for quaternion types. It is used
  25637. // to store intermediate quaternion multiplication results
  25638. switch (typeName) {
  25639. case 'quaternion':
  25640. mixFunction = this._slerp;
  25641. mixFunctionAdditive = this._slerpAdditive;
  25642. setIdentity = this._setAdditiveIdentityQuaternion;
  25643. this.buffer = new Float64Array(valueSize * 6);
  25644. this._workIndex = 5;
  25645. break;
  25646. case 'string':
  25647. case 'bool':
  25648. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25649. // additive is not relevant for non-numeric types
  25650. mixFunctionAdditive = this._select;
  25651. setIdentity = this._setAdditiveIdentityOther;
  25652. this.buffer = new Array(valueSize * 5);
  25653. break;
  25654. default:
  25655. mixFunction = this._lerp;
  25656. mixFunctionAdditive = this._lerpAdditive;
  25657. setIdentity = this._setAdditiveIdentityNumeric;
  25658. this.buffer = new Float64Array(valueSize * 5);
  25659. }
  25660. this._mixBufferRegion = mixFunction;
  25661. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25662. this._setIdentity = setIdentity;
  25663. this._origIndex = 3;
  25664. this._addIndex = 4;
  25665. this.cumulativeWeight = 0;
  25666. this.cumulativeWeightAdditive = 0;
  25667. this.useCount = 0;
  25668. this.referenceCount = 0;
  25669. } // accumulate data in the 'incoming' region into 'accu<i>'
  25670. accumulate(accuIndex, weight) {
  25671. // note: happily accumulating nothing when weight = 0, the caller knows
  25672. // the weight and shouldn't have made the call in the first place
  25673. const buffer = this.buffer,
  25674. stride = this.valueSize,
  25675. offset = accuIndex * stride + stride;
  25676. let currentWeight = this.cumulativeWeight;
  25677. if (currentWeight === 0) {
  25678. // accuN := incoming * weight
  25679. for (let i = 0; i !== stride; ++i) {
  25680. buffer[offset + i] = buffer[i];
  25681. }
  25682. currentWeight = weight;
  25683. } else {
  25684. // accuN := accuN + incoming * weight
  25685. currentWeight += weight;
  25686. const mix = weight / currentWeight;
  25687. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25688. }
  25689. this.cumulativeWeight = currentWeight;
  25690. } // accumulate data in the 'incoming' region into 'add'
  25691. accumulateAdditive(weight) {
  25692. const buffer = this.buffer,
  25693. stride = this.valueSize,
  25694. offset = stride * this._addIndex;
  25695. if (this.cumulativeWeightAdditive === 0) {
  25696. // add = identity
  25697. this._setIdentity();
  25698. } // add := add + incoming * weight
  25699. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25700. this.cumulativeWeightAdditive += weight;
  25701. } // apply the state of 'accu<i>' to the binding when accus differ
  25702. apply(accuIndex) {
  25703. const stride = this.valueSize,
  25704. buffer = this.buffer,
  25705. offset = accuIndex * stride + stride,
  25706. weight = this.cumulativeWeight,
  25707. weightAdditive = this.cumulativeWeightAdditive,
  25708. binding = this.binding;
  25709. this.cumulativeWeight = 0;
  25710. this.cumulativeWeightAdditive = 0;
  25711. if (weight < 1) {
  25712. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25713. const originalValueOffset = stride * this._origIndex;
  25714. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25715. }
  25716. if (weightAdditive > 0) {
  25717. // accuN := accuN + additive accuN
  25718. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25719. }
  25720. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25721. if (buffer[i] !== buffer[i + stride]) {
  25722. // value has changed -> update scene graph
  25723. binding.setValue(buffer, offset);
  25724. break;
  25725. }
  25726. }
  25727. } // remember the state of the bound property and copy it to both accus
  25728. saveOriginalState() {
  25729. const binding = this.binding;
  25730. const buffer = this.buffer,
  25731. stride = this.valueSize,
  25732. originalValueOffset = stride * this._origIndex;
  25733. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25734. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25735. buffer[i] = buffer[originalValueOffset + i % stride];
  25736. } // Add to identity for additive
  25737. this._setIdentity();
  25738. this.cumulativeWeight = 0;
  25739. this.cumulativeWeightAdditive = 0;
  25740. } // apply the state previously taken via 'saveOriginalState' to the binding
  25741. restoreOriginalState() {
  25742. const originalValueOffset = this.valueSize * 3;
  25743. this.binding.setValue(this.buffer, originalValueOffset);
  25744. }
  25745. _setAdditiveIdentityNumeric() {
  25746. const startIndex = this._addIndex * this.valueSize;
  25747. const endIndex = startIndex + this.valueSize;
  25748. for (let i = startIndex; i < endIndex; i++) {
  25749. this.buffer[i] = 0;
  25750. }
  25751. }
  25752. _setAdditiveIdentityQuaternion() {
  25753. this._setAdditiveIdentityNumeric();
  25754. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25755. }
  25756. _setAdditiveIdentityOther() {
  25757. const startIndex = this._origIndex * this.valueSize;
  25758. const targetIndex = this._addIndex * this.valueSize;
  25759. for (let i = 0; i < this.valueSize; i++) {
  25760. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25761. }
  25762. } // mix functions
  25763. _select(buffer, dstOffset, srcOffset, t, stride) {
  25764. if (t >= 0.5) {
  25765. for (let i = 0; i !== stride; ++i) {
  25766. buffer[dstOffset + i] = buffer[srcOffset + i];
  25767. }
  25768. }
  25769. }
  25770. _slerp(buffer, dstOffset, srcOffset, t) {
  25771. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25772. }
  25773. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25774. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25775. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25776. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25777. }
  25778. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25779. const s = 1 - t;
  25780. for (let i = 0; i !== stride; ++i) {
  25781. const j = dstOffset + i;
  25782. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25783. }
  25784. }
  25785. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25786. for (let i = 0; i !== stride; ++i) {
  25787. const j = dstOffset + i;
  25788. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25789. }
  25790. }
  25791. }
  25792. // Characters [].:/ are reserved for track binding syntax.
  25793. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25794. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25795. // only latin characters, and the unicode \p{L} is not yet supported. So
  25796. // instead, we exclude reserved characters and match everything else.
  25797. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25798. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25799. // be matched to parse the rest of the track name.
  25800. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25801. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25802. // characters. Accessor may contain any character except closing bracket.
  25803. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25804. // contain any non-bracket characters.
  25805. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25806. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25807. const _supportedObjectNames = ['material', 'materials', 'bones', 'map'];
  25808. class Composite {
  25809. constructor(targetGroup, path, optionalParsedPath) {
  25810. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25811. this._targetGroup = targetGroup;
  25812. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25813. }
  25814. getValue(array, offset) {
  25815. this.bind(); // bind all binding
  25816. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25817. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25818. if (binding !== undefined) binding.getValue(array, offset);
  25819. }
  25820. setValue(array, offset) {
  25821. const bindings = this._bindings;
  25822. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25823. bindings[i].setValue(array, offset);
  25824. }
  25825. }
  25826. bind() {
  25827. const bindings = this._bindings;
  25828. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25829. bindings[i].bind();
  25830. }
  25831. }
  25832. unbind() {
  25833. const bindings = this._bindings;
  25834. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25835. bindings[i].unbind();
  25836. }
  25837. }
  25838. } // Note: This class uses a State pattern on a per-method basis:
  25839. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25840. // prototype version of these methods with one that represents
  25841. // the bound state. When the property is not found, the methods
  25842. // become no-ops.
  25843. class PropertyBinding {
  25844. constructor(rootNode, path, parsedPath) {
  25845. this.path = path;
  25846. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25847. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25848. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25849. this.getValue = this._getValue_unbound;
  25850. this.setValue = this._setValue_unbound;
  25851. }
  25852. static create(root, path, parsedPath) {
  25853. if (!(root && root.isAnimationObjectGroup)) {
  25854. return new PropertyBinding(root, path, parsedPath);
  25855. } else {
  25856. return new PropertyBinding.Composite(root, path, parsedPath);
  25857. }
  25858. }
  25859. /**
  25860. * Replaces spaces with underscores and removes unsupported characters from
  25861. * node names, to ensure compatibility with parseTrackName().
  25862. *
  25863. * @param {string} name Node name to be sanitized.
  25864. * @return {string}
  25865. */
  25866. static sanitizeNodeName(name) {
  25867. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25868. }
  25869. static parseTrackName(trackName) {
  25870. const matches = _trackRe.exec(trackName);
  25871. if (matches === null) {
  25872. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25873. }
  25874. const results = {
  25875. // directoryName: matches[ 1 ], // (tschw) currently unused
  25876. nodeName: matches[2],
  25877. objectName: matches[3],
  25878. objectIndex: matches[4],
  25879. propertyName: matches[5],
  25880. // required
  25881. propertyIndex: matches[6]
  25882. };
  25883. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25884. if (lastDot !== undefined && lastDot !== -1) {
  25885. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25886. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25887. // 'bar' could be the objectName, or part of a nodeName (which can
  25888. // include '.' characters).
  25889. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25890. results.nodeName = results.nodeName.substring(0, lastDot);
  25891. results.objectName = objectName;
  25892. }
  25893. }
  25894. if (results.propertyName === null || results.propertyName.length === 0) {
  25895. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25896. }
  25897. return results;
  25898. }
  25899. static findNode(root, nodeName) {
  25900. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25901. return root;
  25902. } // search into skeleton bones.
  25903. if (root.skeleton) {
  25904. const bone = root.skeleton.getBoneByName(nodeName);
  25905. if (bone !== undefined) {
  25906. return bone;
  25907. }
  25908. } // search into node subtree.
  25909. if (root.children) {
  25910. const searchNodeSubtree = function (children) {
  25911. for (let i = 0; i < children.length; i++) {
  25912. const childNode = children[i];
  25913. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25914. return childNode;
  25915. }
  25916. const result = searchNodeSubtree(childNode.children);
  25917. if (result) return result;
  25918. }
  25919. return null;
  25920. };
  25921. const subTreeNode = searchNodeSubtree(root.children);
  25922. if (subTreeNode) {
  25923. return subTreeNode;
  25924. }
  25925. }
  25926. return null;
  25927. } // these are used to "bind" a nonexistent property
  25928. _getValue_unavailable() {}
  25929. _setValue_unavailable() {} // Getters
  25930. _getValue_direct(buffer, offset) {
  25931. buffer[offset] = this.targetObject[this.propertyName];
  25932. }
  25933. _getValue_array(buffer, offset) {
  25934. const source = this.resolvedProperty;
  25935. for (let i = 0, n = source.length; i !== n; ++i) {
  25936. buffer[offset++] = source[i];
  25937. }
  25938. }
  25939. _getValue_arrayElement(buffer, offset) {
  25940. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25941. }
  25942. _getValue_toArray(buffer, offset) {
  25943. this.resolvedProperty.toArray(buffer, offset);
  25944. } // Direct
  25945. _setValue_direct(buffer, offset) {
  25946. this.targetObject[this.propertyName] = buffer[offset];
  25947. }
  25948. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25949. this.targetObject[this.propertyName] = buffer[offset];
  25950. this.targetObject.needsUpdate = true;
  25951. }
  25952. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25953. this.targetObject[this.propertyName] = buffer[offset];
  25954. this.targetObject.matrixWorldNeedsUpdate = true;
  25955. } // EntireArray
  25956. _setValue_array(buffer, offset) {
  25957. const dest = this.resolvedProperty;
  25958. for (let i = 0, n = dest.length; i !== n; ++i) {
  25959. dest[i] = buffer[offset++];
  25960. }
  25961. }
  25962. _setValue_array_setNeedsUpdate(buffer, offset) {
  25963. const dest = this.resolvedProperty;
  25964. for (let i = 0, n = dest.length; i !== n; ++i) {
  25965. dest[i] = buffer[offset++];
  25966. }
  25967. this.targetObject.needsUpdate = true;
  25968. }
  25969. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25970. const dest = this.resolvedProperty;
  25971. for (let i = 0, n = dest.length; i !== n; ++i) {
  25972. dest[i] = buffer[offset++];
  25973. }
  25974. this.targetObject.matrixWorldNeedsUpdate = true;
  25975. } // ArrayElement
  25976. _setValue_arrayElement(buffer, offset) {
  25977. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25978. }
  25979. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25980. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25981. this.targetObject.needsUpdate = true;
  25982. }
  25983. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25984. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25985. this.targetObject.matrixWorldNeedsUpdate = true;
  25986. } // HasToFromArray
  25987. _setValue_fromArray(buffer, offset) {
  25988. this.resolvedProperty.fromArray(buffer, offset);
  25989. }
  25990. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25991. this.resolvedProperty.fromArray(buffer, offset);
  25992. this.targetObject.needsUpdate = true;
  25993. }
  25994. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25995. this.resolvedProperty.fromArray(buffer, offset);
  25996. this.targetObject.matrixWorldNeedsUpdate = true;
  25997. }
  25998. _getValue_unbound(targetArray, offset) {
  25999. this.bind();
  26000. this.getValue(targetArray, offset);
  26001. }
  26002. _setValue_unbound(sourceArray, offset) {
  26003. this.bind();
  26004. this.setValue(sourceArray, offset);
  26005. } // create getter / setter pair for a property in the scene graph
  26006. bind() {
  26007. let targetObject = this.node;
  26008. const parsedPath = this.parsedPath;
  26009. const objectName = parsedPath.objectName;
  26010. const propertyName = parsedPath.propertyName;
  26011. let propertyIndex = parsedPath.propertyIndex;
  26012. if (!targetObject) {
  26013. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26014. this.node = targetObject;
  26015. } // set fail state so we can just 'return' on error
  26016. this.getValue = this._getValue_unavailable;
  26017. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26018. if (!targetObject) {
  26019. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26020. return;
  26021. }
  26022. if (objectName) {
  26023. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26024. switch (objectName) {
  26025. case 'materials':
  26026. if (!targetObject.material) {
  26027. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26028. return;
  26029. }
  26030. if (!targetObject.material.materials) {
  26031. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26032. return;
  26033. }
  26034. targetObject = targetObject.material.materials;
  26035. break;
  26036. case 'bones':
  26037. if (!targetObject.skeleton) {
  26038. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26039. return;
  26040. } // potential future optimization: skip this if propertyIndex is already an integer
  26041. // and convert the integer string to a true integer.
  26042. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26043. for (let i = 0; i < targetObject.length; i++) {
  26044. if (targetObject[i].name === objectIndex) {
  26045. objectIndex = i;
  26046. break;
  26047. }
  26048. }
  26049. break;
  26050. case 'map':
  26051. if (!targetObject.material) {
  26052. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26053. return;
  26054. }
  26055. if (!targetObject.material.map) {
  26056. console.error('THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this);
  26057. return;
  26058. }
  26059. targetObject = targetObject.material.map;
  26060. break;
  26061. default:
  26062. if (targetObject[objectName] === undefined) {
  26063. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26064. return;
  26065. }
  26066. targetObject = targetObject[objectName];
  26067. }
  26068. if (objectIndex !== undefined) {
  26069. if (targetObject[objectIndex] === undefined) {
  26070. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26071. return;
  26072. }
  26073. targetObject = targetObject[objectIndex];
  26074. }
  26075. } // resolve property
  26076. const nodeProperty = targetObject[propertyName];
  26077. if (nodeProperty === undefined) {
  26078. const nodeName = parsedPath.nodeName;
  26079. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26080. return;
  26081. } // determine versioning scheme
  26082. let versioning = this.Versioning.None;
  26083. this.targetObject = targetObject;
  26084. if (targetObject.needsUpdate !== undefined) {
  26085. // material
  26086. versioning = this.Versioning.NeedsUpdate;
  26087. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26088. // node transform
  26089. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26090. } // determine how the property gets bound
  26091. let bindingType = this.BindingType.Direct;
  26092. if (propertyIndex !== undefined) {
  26093. // access a sub element of the property array (only primitives are supported right now)
  26094. if (propertyName === 'morphTargetInfluences') {
  26095. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26096. // support resolving morphTarget names into indices.
  26097. if (!targetObject.geometry) {
  26098. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26099. return;
  26100. }
  26101. if (!targetObject.geometry.morphAttributes) {
  26102. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26103. return;
  26104. }
  26105. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26106. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26107. }
  26108. }
  26109. bindingType = this.BindingType.ArrayElement;
  26110. this.resolvedProperty = nodeProperty;
  26111. this.propertyIndex = propertyIndex;
  26112. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26113. // must use copy for Object3D.Euler/Quaternion
  26114. bindingType = this.BindingType.HasFromToArray;
  26115. this.resolvedProperty = nodeProperty;
  26116. } else if (Array.isArray(nodeProperty)) {
  26117. bindingType = this.BindingType.EntireArray;
  26118. this.resolvedProperty = nodeProperty;
  26119. } else {
  26120. this.propertyName = propertyName;
  26121. } // select getter / setter
  26122. this.getValue = this.GetterByBindingType[bindingType];
  26123. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26124. }
  26125. unbind() {
  26126. this.node = null; // back to the prototype version of getValue / setValue
  26127. // note: avoiding to mutate the shape of 'this' via 'delete'
  26128. this.getValue = this._getValue_unbound;
  26129. this.setValue = this._setValue_unbound;
  26130. }
  26131. }
  26132. PropertyBinding.Composite = Composite;
  26133. PropertyBinding.prototype.BindingType = {
  26134. Direct: 0,
  26135. EntireArray: 1,
  26136. ArrayElement: 2,
  26137. HasFromToArray: 3
  26138. };
  26139. PropertyBinding.prototype.Versioning = {
  26140. None: 0,
  26141. NeedsUpdate: 1,
  26142. MatrixWorldNeedsUpdate: 2
  26143. };
  26144. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  26145. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  26146. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  26147. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  26148. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  26149. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  26150. /**
  26151. *
  26152. * A group of objects that receives a shared animation state.
  26153. *
  26154. * Usage:
  26155. *
  26156. * - Add objects you would otherwise pass as 'root' to the
  26157. * constructor or the .clipAction method of AnimationMixer.
  26158. *
  26159. * - Instead pass this object as 'root'.
  26160. *
  26161. * - You can also add and remove objects later when the mixer
  26162. * is running.
  26163. *
  26164. * Note:
  26165. *
  26166. * Objects of this class appear as one object to the mixer,
  26167. * so cache control of the individual objects must be done
  26168. * on the group.
  26169. *
  26170. * Limitation:
  26171. *
  26172. * - The animated properties must be compatible among the
  26173. * all objects in the group.
  26174. *
  26175. * - A single property can either be controlled through a
  26176. * target group or directly, but not both.
  26177. */
  26178. class AnimationObjectGroup {
  26179. constructor() {
  26180. this.isAnimationObjectGroup = true;
  26181. this.uuid = generateUUID(); // cached objects followed by the active ones
  26182. this._objects = Array.prototype.slice.call(arguments);
  26183. this.nCachedObjects_ = 0; // threshold
  26184. // note: read by PropertyBinding.Composite
  26185. const indices = {};
  26186. this._indicesByUUID = indices; // for bookkeeping
  26187. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26188. indices[arguments[i].uuid] = i;
  26189. }
  26190. this._paths = []; // inside: string
  26191. this._parsedPaths = []; // inside: { we don't care, here }
  26192. this._bindings = []; // inside: Array< PropertyBinding >
  26193. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26194. const scope = this;
  26195. this.stats = {
  26196. objects: {
  26197. get total() {
  26198. return scope._objects.length;
  26199. },
  26200. get inUse() {
  26201. return this.total - scope.nCachedObjects_;
  26202. }
  26203. },
  26204. get bindingsPerObject() {
  26205. return scope._bindings.length;
  26206. }
  26207. };
  26208. }
  26209. add() {
  26210. const objects = this._objects,
  26211. indicesByUUID = this._indicesByUUID,
  26212. paths = this._paths,
  26213. parsedPaths = this._parsedPaths,
  26214. bindings = this._bindings,
  26215. nBindings = bindings.length;
  26216. let knownObject = undefined,
  26217. nObjects = objects.length,
  26218. nCachedObjects = this.nCachedObjects_;
  26219. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26220. const object = arguments[i],
  26221. uuid = object.uuid;
  26222. let index = indicesByUUID[uuid];
  26223. if (index === undefined) {
  26224. // unknown object -> add it to the ACTIVE region
  26225. index = nObjects++;
  26226. indicesByUUID[uuid] = index;
  26227. objects.push(object); // accounting is done, now do the same for all bindings
  26228. for (let j = 0, m = nBindings; j !== m; ++j) {
  26229. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26230. }
  26231. } else if (index < nCachedObjects) {
  26232. knownObject = objects[index]; // move existing object to the ACTIVE region
  26233. const firstActiveIndex = --nCachedObjects,
  26234. lastCachedObject = objects[firstActiveIndex];
  26235. indicesByUUID[lastCachedObject.uuid] = index;
  26236. objects[index] = lastCachedObject;
  26237. indicesByUUID[uuid] = firstActiveIndex;
  26238. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26239. for (let j = 0, m = nBindings; j !== m; ++j) {
  26240. const bindingsForPath = bindings[j],
  26241. lastCached = bindingsForPath[firstActiveIndex];
  26242. let binding = bindingsForPath[index];
  26243. bindingsForPath[index] = lastCached;
  26244. if (binding === undefined) {
  26245. // since we do not bother to create new bindings
  26246. // for objects that are cached, the binding may
  26247. // or may not exist
  26248. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26249. }
  26250. bindingsForPath[firstActiveIndex] = binding;
  26251. }
  26252. } else if (objects[index] !== knownObject) {
  26253. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26254. } // else the object is already where we want it to be
  26255. } // for arguments
  26256. this.nCachedObjects_ = nCachedObjects;
  26257. }
  26258. remove() {
  26259. const objects = this._objects,
  26260. indicesByUUID = this._indicesByUUID,
  26261. bindings = this._bindings,
  26262. nBindings = bindings.length;
  26263. let nCachedObjects = this.nCachedObjects_;
  26264. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26265. const object = arguments[i],
  26266. uuid = object.uuid,
  26267. index = indicesByUUID[uuid];
  26268. if (index !== undefined && index >= nCachedObjects) {
  26269. // move existing object into the CACHED region
  26270. const lastCachedIndex = nCachedObjects++,
  26271. firstActiveObject = objects[lastCachedIndex];
  26272. indicesByUUID[firstActiveObject.uuid] = index;
  26273. objects[index] = firstActiveObject;
  26274. indicesByUUID[uuid] = lastCachedIndex;
  26275. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26276. for (let j = 0, m = nBindings; j !== m; ++j) {
  26277. const bindingsForPath = bindings[j],
  26278. firstActive = bindingsForPath[lastCachedIndex],
  26279. binding = bindingsForPath[index];
  26280. bindingsForPath[index] = firstActive;
  26281. bindingsForPath[lastCachedIndex] = binding;
  26282. }
  26283. }
  26284. } // for arguments
  26285. this.nCachedObjects_ = nCachedObjects;
  26286. } // remove & forget
  26287. uncache() {
  26288. const objects = this._objects,
  26289. indicesByUUID = this._indicesByUUID,
  26290. bindings = this._bindings,
  26291. nBindings = bindings.length;
  26292. let nCachedObjects = this.nCachedObjects_,
  26293. nObjects = objects.length;
  26294. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26295. const object = arguments[i],
  26296. uuid = object.uuid,
  26297. index = indicesByUUID[uuid];
  26298. if (index !== undefined) {
  26299. delete indicesByUUID[uuid];
  26300. if (index < nCachedObjects) {
  26301. // object is cached, shrink the CACHED region
  26302. const firstActiveIndex = --nCachedObjects,
  26303. lastCachedObject = objects[firstActiveIndex],
  26304. lastIndex = --nObjects,
  26305. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26306. indicesByUUID[lastCachedObject.uuid] = index;
  26307. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26308. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26309. objects[firstActiveIndex] = lastObject;
  26310. objects.pop(); // accounting is done, now do the same for all bindings
  26311. for (let j = 0, m = nBindings; j !== m; ++j) {
  26312. const bindingsForPath = bindings[j],
  26313. lastCached = bindingsForPath[firstActiveIndex],
  26314. last = bindingsForPath[lastIndex];
  26315. bindingsForPath[index] = lastCached;
  26316. bindingsForPath[firstActiveIndex] = last;
  26317. bindingsForPath.pop();
  26318. }
  26319. } else {
  26320. // object is active, just swap with the last and pop
  26321. const lastIndex = --nObjects,
  26322. lastObject = objects[lastIndex];
  26323. if (lastIndex > 0) {
  26324. indicesByUUID[lastObject.uuid] = index;
  26325. }
  26326. objects[index] = lastObject;
  26327. objects.pop(); // accounting is done, now do the same for all bindings
  26328. for (let j = 0, m = nBindings; j !== m; ++j) {
  26329. const bindingsForPath = bindings[j];
  26330. bindingsForPath[index] = bindingsForPath[lastIndex];
  26331. bindingsForPath.pop();
  26332. }
  26333. } // cached or active
  26334. } // if object is known
  26335. } // for arguments
  26336. this.nCachedObjects_ = nCachedObjects;
  26337. } // Internal interface used by befriended PropertyBinding.Composite:
  26338. subscribe_(path, parsedPath) {
  26339. // returns an array of bindings for the given path that is changed
  26340. // according to the contained objects in the group
  26341. const indicesByPath = this._bindingsIndicesByPath;
  26342. let index = indicesByPath[path];
  26343. const bindings = this._bindings;
  26344. if (index !== undefined) return bindings[index];
  26345. const paths = this._paths,
  26346. parsedPaths = this._parsedPaths,
  26347. objects = this._objects,
  26348. nObjects = objects.length,
  26349. nCachedObjects = this.nCachedObjects_,
  26350. bindingsForPath = new Array(nObjects);
  26351. index = bindings.length;
  26352. indicesByPath[path] = index;
  26353. paths.push(path);
  26354. parsedPaths.push(parsedPath);
  26355. bindings.push(bindingsForPath);
  26356. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26357. const object = objects[i];
  26358. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26359. }
  26360. return bindingsForPath;
  26361. }
  26362. unsubscribe_(path) {
  26363. // tells the group to forget about a property path and no longer
  26364. // update the array previously obtained with 'subscribe_'
  26365. const indicesByPath = this._bindingsIndicesByPath,
  26366. index = indicesByPath[path];
  26367. if (index !== undefined) {
  26368. const paths = this._paths,
  26369. parsedPaths = this._parsedPaths,
  26370. bindings = this._bindings,
  26371. lastBindingsIndex = bindings.length - 1,
  26372. lastBindings = bindings[lastBindingsIndex],
  26373. lastBindingsPath = path[lastBindingsIndex];
  26374. indicesByPath[lastBindingsPath] = index;
  26375. bindings[index] = lastBindings;
  26376. bindings.pop();
  26377. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26378. parsedPaths.pop();
  26379. paths[index] = paths[lastBindingsIndex];
  26380. paths.pop();
  26381. }
  26382. }
  26383. }
  26384. class AnimationAction {
  26385. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26386. this._mixer = mixer;
  26387. this._clip = clip;
  26388. this._localRoot = localRoot;
  26389. this.blendMode = blendMode;
  26390. const tracks = clip.tracks,
  26391. nTracks = tracks.length,
  26392. interpolants = new Array(nTracks);
  26393. const interpolantSettings = {
  26394. endingStart: ZeroCurvatureEnding,
  26395. endingEnd: ZeroCurvatureEnding
  26396. };
  26397. for (let i = 0; i !== nTracks; ++i) {
  26398. const interpolant = tracks[i].createInterpolant(null);
  26399. interpolants[i] = interpolant;
  26400. interpolant.settings = interpolantSettings;
  26401. }
  26402. this._interpolantSettings = interpolantSettings;
  26403. this._interpolants = interpolants; // bound by the mixer
  26404. // inside: PropertyMixer (managed by the mixer)
  26405. this._propertyBindings = new Array(nTracks);
  26406. this._cacheIndex = null; // for the memory manager
  26407. this._byClipCacheIndex = null; // for the memory manager
  26408. this._timeScaleInterpolant = null;
  26409. this._weightInterpolant = null;
  26410. this.loop = LoopRepeat;
  26411. this._loopCount = -1; // global mixer time when the action is to be started
  26412. // it's set back to 'null' upon start of the action
  26413. this._startTime = null; // scaled local time of the action
  26414. // gets clamped or wrapped to 0..clip.duration according to loop
  26415. this.time = 0;
  26416. this.timeScale = 1;
  26417. this._effectiveTimeScale = 1;
  26418. this.weight = 1;
  26419. this._effectiveWeight = 1;
  26420. this.repetitions = Infinity; // no. of repetitions when looping
  26421. this.paused = false; // true -> zero effective time scale
  26422. this.enabled = true; // false -> zero effective weight
  26423. this.clampWhenFinished = false; // keep feeding the last frame?
  26424. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26425. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26426. } // State & Scheduling
  26427. play() {
  26428. this._mixer._activateAction(this);
  26429. return this;
  26430. }
  26431. stop() {
  26432. this._mixer._deactivateAction(this);
  26433. return this.reset();
  26434. }
  26435. reset() {
  26436. this.paused = false;
  26437. this.enabled = true;
  26438. this.time = 0; // restart clip
  26439. this._loopCount = -1; // forget previous loops
  26440. this._startTime = null; // forget scheduling
  26441. return this.stopFading().stopWarping();
  26442. }
  26443. isRunning() {
  26444. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26445. } // return true when play has been called
  26446. isScheduled() {
  26447. return this._mixer._isActiveAction(this);
  26448. }
  26449. startAt(time) {
  26450. this._startTime = time;
  26451. return this;
  26452. }
  26453. setLoop(mode, repetitions) {
  26454. this.loop = mode;
  26455. this.repetitions = repetitions;
  26456. return this;
  26457. } // Weight
  26458. // set the weight stopping any scheduled fading
  26459. // although .enabled = false yields an effective weight of zero, this
  26460. // method does *not* change .enabled, because it would be confusing
  26461. setEffectiveWeight(weight) {
  26462. this.weight = weight; // note: same logic as when updated at runtime
  26463. this._effectiveWeight = this.enabled ? weight : 0;
  26464. return this.stopFading();
  26465. } // return the weight considering fading and .enabled
  26466. getEffectiveWeight() {
  26467. return this._effectiveWeight;
  26468. }
  26469. fadeIn(duration) {
  26470. return this._scheduleFading(duration, 0, 1);
  26471. }
  26472. fadeOut(duration) {
  26473. return this._scheduleFading(duration, 1, 0);
  26474. }
  26475. crossFadeFrom(fadeOutAction, duration, warp) {
  26476. fadeOutAction.fadeOut(duration);
  26477. this.fadeIn(duration);
  26478. if (warp) {
  26479. const fadeInDuration = this._clip.duration,
  26480. fadeOutDuration = fadeOutAction._clip.duration,
  26481. startEndRatio = fadeOutDuration / fadeInDuration,
  26482. endStartRatio = fadeInDuration / fadeOutDuration;
  26483. fadeOutAction.warp(1.0, startEndRatio, duration);
  26484. this.warp(endStartRatio, 1.0, duration);
  26485. }
  26486. return this;
  26487. }
  26488. crossFadeTo(fadeInAction, duration, warp) {
  26489. return fadeInAction.crossFadeFrom(this, duration, warp);
  26490. }
  26491. stopFading() {
  26492. const weightInterpolant = this._weightInterpolant;
  26493. if (weightInterpolant !== null) {
  26494. this._weightInterpolant = null;
  26495. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26496. }
  26497. return this;
  26498. } // Time Scale Control
  26499. // set the time scale stopping any scheduled warping
  26500. // although .paused = true yields an effective time scale of zero, this
  26501. // method does *not* change .paused, because it would be confusing
  26502. setEffectiveTimeScale(timeScale) {
  26503. this.timeScale = timeScale;
  26504. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26505. return this.stopWarping();
  26506. } // return the time scale considering warping and .paused
  26507. getEffectiveTimeScale() {
  26508. return this._effectiveTimeScale;
  26509. }
  26510. setDuration(duration) {
  26511. this.timeScale = this._clip.duration / duration;
  26512. return this.stopWarping();
  26513. }
  26514. syncWith(action) {
  26515. this.time = action.time;
  26516. this.timeScale = action.timeScale;
  26517. return this.stopWarping();
  26518. }
  26519. halt(duration) {
  26520. return this.warp(this._effectiveTimeScale, 0, duration);
  26521. }
  26522. warp(startTimeScale, endTimeScale, duration) {
  26523. const mixer = this._mixer,
  26524. now = mixer.time,
  26525. timeScale = this.timeScale;
  26526. let interpolant = this._timeScaleInterpolant;
  26527. if (interpolant === null) {
  26528. interpolant = mixer._lendControlInterpolant();
  26529. this._timeScaleInterpolant = interpolant;
  26530. }
  26531. const times = interpolant.parameterPositions,
  26532. values = interpolant.sampleValues;
  26533. times[0] = now;
  26534. times[1] = now + duration;
  26535. values[0] = startTimeScale / timeScale;
  26536. values[1] = endTimeScale / timeScale;
  26537. return this;
  26538. }
  26539. stopWarping() {
  26540. const timeScaleInterpolant = this._timeScaleInterpolant;
  26541. if (timeScaleInterpolant !== null) {
  26542. this._timeScaleInterpolant = null;
  26543. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26544. }
  26545. return this;
  26546. } // Object Accessors
  26547. getMixer() {
  26548. return this._mixer;
  26549. }
  26550. getClip() {
  26551. return this._clip;
  26552. }
  26553. getRoot() {
  26554. return this._localRoot || this._mixer._root;
  26555. } // Interna
  26556. _update(time, deltaTime, timeDirection, accuIndex) {
  26557. // called by the mixer
  26558. if (!this.enabled) {
  26559. // call ._updateWeight() to update ._effectiveWeight
  26560. this._updateWeight(time);
  26561. return;
  26562. }
  26563. const startTime = this._startTime;
  26564. if (startTime !== null) {
  26565. // check for scheduled start of action
  26566. const timeRunning = (time - startTime) * timeDirection;
  26567. if (timeRunning < 0 || timeDirection === 0) {
  26568. deltaTime = 0;
  26569. } else {
  26570. this._startTime = null; // unschedule
  26571. deltaTime = timeDirection * timeRunning;
  26572. }
  26573. } // apply time scale and advance time
  26574. deltaTime *= this._updateTimeScale(time);
  26575. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26576. // an effective weight of 0
  26577. const weight = this._updateWeight(time);
  26578. if (weight > 0) {
  26579. const interpolants = this._interpolants;
  26580. const propertyMixers = this._propertyBindings;
  26581. switch (this.blendMode) {
  26582. case AdditiveAnimationBlendMode:
  26583. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26584. interpolants[j].evaluate(clipTime);
  26585. propertyMixers[j].accumulateAdditive(weight);
  26586. }
  26587. break;
  26588. case NormalAnimationBlendMode:
  26589. default:
  26590. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26591. interpolants[j].evaluate(clipTime);
  26592. propertyMixers[j].accumulate(accuIndex, weight);
  26593. }
  26594. }
  26595. }
  26596. }
  26597. _updateWeight(time) {
  26598. let weight = 0;
  26599. if (this.enabled) {
  26600. weight = this.weight;
  26601. const interpolant = this._weightInterpolant;
  26602. if (interpolant !== null) {
  26603. const interpolantValue = interpolant.evaluate(time)[0];
  26604. weight *= interpolantValue;
  26605. if (time > interpolant.parameterPositions[1]) {
  26606. this.stopFading();
  26607. if (interpolantValue === 0) {
  26608. // faded out, disable
  26609. this.enabled = false;
  26610. }
  26611. }
  26612. }
  26613. }
  26614. this._effectiveWeight = weight;
  26615. return weight;
  26616. }
  26617. _updateTimeScale(time) {
  26618. let timeScale = 0;
  26619. if (!this.paused) {
  26620. timeScale = this.timeScale;
  26621. const interpolant = this._timeScaleInterpolant;
  26622. if (interpolant !== null) {
  26623. const interpolantValue = interpolant.evaluate(time)[0];
  26624. timeScale *= interpolantValue;
  26625. if (time > interpolant.parameterPositions[1]) {
  26626. this.stopWarping();
  26627. if (timeScale === 0) {
  26628. // motion has halted, pause
  26629. this.paused = true;
  26630. } else {
  26631. // warp done - apply final time scale
  26632. this.timeScale = timeScale;
  26633. }
  26634. }
  26635. }
  26636. }
  26637. this._effectiveTimeScale = timeScale;
  26638. return timeScale;
  26639. }
  26640. _updateTime(deltaTime) {
  26641. const duration = this._clip.duration;
  26642. const loop = this.loop;
  26643. let time = this.time + deltaTime;
  26644. let loopCount = this._loopCount;
  26645. const pingPong = loop === LoopPingPong;
  26646. if (deltaTime === 0) {
  26647. if (loopCount === -1) return time;
  26648. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26649. }
  26650. if (loop === LoopOnce) {
  26651. if (loopCount === -1) {
  26652. // just started
  26653. this._loopCount = 0;
  26654. this._setEndings(true, true, false);
  26655. }
  26656. handle_stop: {
  26657. if (time >= duration) {
  26658. time = duration;
  26659. } else if (time < 0) {
  26660. time = 0;
  26661. } else {
  26662. this.time = time;
  26663. break handle_stop;
  26664. }
  26665. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26666. this.time = time;
  26667. this._mixer.dispatchEvent({
  26668. type: 'finished',
  26669. action: this,
  26670. direction: deltaTime < 0 ? -1 : 1
  26671. });
  26672. }
  26673. } else {
  26674. // repetitive Repeat or PingPong
  26675. if (loopCount === -1) {
  26676. // just started
  26677. if (deltaTime >= 0) {
  26678. loopCount = 0;
  26679. this._setEndings(true, this.repetitions === 0, pingPong);
  26680. } else {
  26681. // when looping in reverse direction, the initial
  26682. // transition through zero counts as a repetition,
  26683. // so leave loopCount at -1
  26684. this._setEndings(this.repetitions === 0, true, pingPong);
  26685. }
  26686. }
  26687. if (time >= duration || time < 0) {
  26688. // wrap around
  26689. const loopDelta = Math.floor(time / duration); // signed
  26690. time -= duration * loopDelta;
  26691. loopCount += Math.abs(loopDelta);
  26692. const pending = this.repetitions - loopCount;
  26693. if (pending <= 0) {
  26694. // have to stop (switch state, clamp time, fire event)
  26695. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26696. time = deltaTime > 0 ? duration : 0;
  26697. this.time = time;
  26698. this._mixer.dispatchEvent({
  26699. type: 'finished',
  26700. action: this,
  26701. direction: deltaTime > 0 ? 1 : -1
  26702. });
  26703. } else {
  26704. // keep running
  26705. if (pending === 1) {
  26706. // entering the last round
  26707. const atStart = deltaTime < 0;
  26708. this._setEndings(atStart, !atStart, pingPong);
  26709. } else {
  26710. this._setEndings(false, false, pingPong);
  26711. }
  26712. this._loopCount = loopCount;
  26713. this.time = time;
  26714. this._mixer.dispatchEvent({
  26715. type: 'loop',
  26716. action: this,
  26717. loopDelta: loopDelta
  26718. });
  26719. }
  26720. } else {
  26721. this.time = time;
  26722. }
  26723. if (pingPong && (loopCount & 1) === 1) {
  26724. // invert time for the "pong round"
  26725. return duration - time;
  26726. }
  26727. }
  26728. return time;
  26729. }
  26730. _setEndings(atStart, atEnd, pingPong) {
  26731. const settings = this._interpolantSettings;
  26732. if (pingPong) {
  26733. settings.endingStart = ZeroSlopeEnding;
  26734. settings.endingEnd = ZeroSlopeEnding;
  26735. } else {
  26736. // assuming for LoopOnce atStart == atEnd == true
  26737. if (atStart) {
  26738. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26739. } else {
  26740. settings.endingStart = WrapAroundEnding;
  26741. }
  26742. if (atEnd) {
  26743. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26744. } else {
  26745. settings.endingEnd = WrapAroundEnding;
  26746. }
  26747. }
  26748. }
  26749. _scheduleFading(duration, weightNow, weightThen) {
  26750. const mixer = this._mixer,
  26751. now = mixer.time;
  26752. let interpolant = this._weightInterpolant;
  26753. if (interpolant === null) {
  26754. interpolant = mixer._lendControlInterpolant();
  26755. this._weightInterpolant = interpolant;
  26756. }
  26757. const times = interpolant.parameterPositions,
  26758. values = interpolant.sampleValues;
  26759. times[0] = now;
  26760. values[0] = weightNow;
  26761. times[1] = now + duration;
  26762. values[1] = weightThen;
  26763. return this;
  26764. }
  26765. }
  26766. const _controlInterpolantsResultBuffer = new Float32Array(1);
  26767. class AnimationMixer extends EventDispatcher {
  26768. constructor(root) {
  26769. super();
  26770. this._root = root;
  26771. this._initMemoryManager();
  26772. this._accuIndex = 0;
  26773. this.time = 0;
  26774. this.timeScale = 1.0;
  26775. }
  26776. _bindAction(action, prototypeAction) {
  26777. const root = action._localRoot || this._root,
  26778. tracks = action._clip.tracks,
  26779. nTracks = tracks.length,
  26780. bindings = action._propertyBindings,
  26781. interpolants = action._interpolants,
  26782. rootUuid = root.uuid,
  26783. bindingsByRoot = this._bindingsByRootAndName;
  26784. let bindingsByName = bindingsByRoot[rootUuid];
  26785. if (bindingsByName === undefined) {
  26786. bindingsByName = {};
  26787. bindingsByRoot[rootUuid] = bindingsByName;
  26788. }
  26789. for (let i = 0; i !== nTracks; ++i) {
  26790. const track = tracks[i],
  26791. trackName = track.name;
  26792. let binding = bindingsByName[trackName];
  26793. if (binding !== undefined) {
  26794. ++binding.referenceCount;
  26795. bindings[i] = binding;
  26796. } else {
  26797. binding = bindings[i];
  26798. if (binding !== undefined) {
  26799. // existing binding, make sure the cache knows
  26800. if (binding._cacheIndex === null) {
  26801. ++binding.referenceCount;
  26802. this._addInactiveBinding(binding, rootUuid, trackName);
  26803. }
  26804. continue;
  26805. }
  26806. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26807. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26808. ++binding.referenceCount;
  26809. this._addInactiveBinding(binding, rootUuid, trackName);
  26810. bindings[i] = binding;
  26811. }
  26812. interpolants[i].resultBuffer = binding.buffer;
  26813. }
  26814. }
  26815. _activateAction(action) {
  26816. if (!this._isActiveAction(action)) {
  26817. if (action._cacheIndex === null) {
  26818. // this action has been forgotten by the cache, but the user
  26819. // appears to be still using it -> rebind
  26820. const rootUuid = (action._localRoot || this._root).uuid,
  26821. clipUuid = action._clip.uuid,
  26822. actionsForClip = this._actionsByClip[clipUuid];
  26823. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26824. this._addInactiveAction(action, clipUuid, rootUuid);
  26825. }
  26826. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26827. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26828. const binding = bindings[i];
  26829. if (binding.useCount++ === 0) {
  26830. this._lendBinding(binding);
  26831. binding.saveOriginalState();
  26832. }
  26833. }
  26834. this._lendAction(action);
  26835. }
  26836. }
  26837. _deactivateAction(action) {
  26838. if (this._isActiveAction(action)) {
  26839. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26840. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26841. const binding = bindings[i];
  26842. if (--binding.useCount === 0) {
  26843. binding.restoreOriginalState();
  26844. this._takeBackBinding(binding);
  26845. }
  26846. }
  26847. this._takeBackAction(action);
  26848. }
  26849. } // Memory manager
  26850. _initMemoryManager() {
  26851. this._actions = []; // 'nActiveActions' followed by inactive ones
  26852. this._nActiveActions = 0;
  26853. this._actionsByClip = {}; // inside:
  26854. // {
  26855. // knownActions: Array< AnimationAction > - used as prototypes
  26856. // actionByRoot: AnimationAction - lookup
  26857. // }
  26858. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26859. this._nActiveBindings = 0;
  26860. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26861. this._controlInterpolants = []; // same game as above
  26862. this._nActiveControlInterpolants = 0;
  26863. const scope = this;
  26864. this.stats = {
  26865. actions: {
  26866. get total() {
  26867. return scope._actions.length;
  26868. },
  26869. get inUse() {
  26870. return scope._nActiveActions;
  26871. }
  26872. },
  26873. bindings: {
  26874. get total() {
  26875. return scope._bindings.length;
  26876. },
  26877. get inUse() {
  26878. return scope._nActiveBindings;
  26879. }
  26880. },
  26881. controlInterpolants: {
  26882. get total() {
  26883. return scope._controlInterpolants.length;
  26884. },
  26885. get inUse() {
  26886. return scope._nActiveControlInterpolants;
  26887. }
  26888. }
  26889. };
  26890. } // Memory management for AnimationAction objects
  26891. _isActiveAction(action) {
  26892. const index = action._cacheIndex;
  26893. return index !== null && index < this._nActiveActions;
  26894. }
  26895. _addInactiveAction(action, clipUuid, rootUuid) {
  26896. const actions = this._actions,
  26897. actionsByClip = this._actionsByClip;
  26898. let actionsForClip = actionsByClip[clipUuid];
  26899. if (actionsForClip === undefined) {
  26900. actionsForClip = {
  26901. knownActions: [action],
  26902. actionByRoot: {}
  26903. };
  26904. action._byClipCacheIndex = 0;
  26905. actionsByClip[clipUuid] = actionsForClip;
  26906. } else {
  26907. const knownActions = actionsForClip.knownActions;
  26908. action._byClipCacheIndex = knownActions.length;
  26909. knownActions.push(action);
  26910. }
  26911. action._cacheIndex = actions.length;
  26912. actions.push(action);
  26913. actionsForClip.actionByRoot[rootUuid] = action;
  26914. }
  26915. _removeInactiveAction(action) {
  26916. const actions = this._actions,
  26917. lastInactiveAction = actions[actions.length - 1],
  26918. cacheIndex = action._cacheIndex;
  26919. lastInactiveAction._cacheIndex = cacheIndex;
  26920. actions[cacheIndex] = lastInactiveAction;
  26921. actions.pop();
  26922. action._cacheIndex = null;
  26923. const clipUuid = action._clip.uuid,
  26924. actionsByClip = this._actionsByClip,
  26925. actionsForClip = actionsByClip[clipUuid],
  26926. knownActionsForClip = actionsForClip.knownActions,
  26927. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26928. byClipCacheIndex = action._byClipCacheIndex;
  26929. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26930. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26931. knownActionsForClip.pop();
  26932. action._byClipCacheIndex = null;
  26933. const actionByRoot = actionsForClip.actionByRoot,
  26934. rootUuid = (action._localRoot || this._root).uuid;
  26935. delete actionByRoot[rootUuid];
  26936. if (knownActionsForClip.length === 0) {
  26937. delete actionsByClip[clipUuid];
  26938. }
  26939. this._removeInactiveBindingsForAction(action);
  26940. }
  26941. _removeInactiveBindingsForAction(action) {
  26942. const bindings = action._propertyBindings;
  26943. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26944. const binding = bindings[i];
  26945. if (--binding.referenceCount === 0) {
  26946. this._removeInactiveBinding(binding);
  26947. }
  26948. }
  26949. }
  26950. _lendAction(action) {
  26951. // [ active actions | inactive actions ]
  26952. // [ active actions >| inactive actions ]
  26953. // s a
  26954. // <-swap->
  26955. // a s
  26956. const actions = this._actions,
  26957. prevIndex = action._cacheIndex,
  26958. lastActiveIndex = this._nActiveActions++,
  26959. firstInactiveAction = actions[lastActiveIndex];
  26960. action._cacheIndex = lastActiveIndex;
  26961. actions[lastActiveIndex] = action;
  26962. firstInactiveAction._cacheIndex = prevIndex;
  26963. actions[prevIndex] = firstInactiveAction;
  26964. }
  26965. _takeBackAction(action) {
  26966. // [ active actions | inactive actions ]
  26967. // [ active actions |< inactive actions ]
  26968. // a s
  26969. // <-swap->
  26970. // s a
  26971. const actions = this._actions,
  26972. prevIndex = action._cacheIndex,
  26973. firstInactiveIndex = --this._nActiveActions,
  26974. lastActiveAction = actions[firstInactiveIndex];
  26975. action._cacheIndex = firstInactiveIndex;
  26976. actions[firstInactiveIndex] = action;
  26977. lastActiveAction._cacheIndex = prevIndex;
  26978. actions[prevIndex] = lastActiveAction;
  26979. } // Memory management for PropertyMixer objects
  26980. _addInactiveBinding(binding, rootUuid, trackName) {
  26981. const bindingsByRoot = this._bindingsByRootAndName,
  26982. bindings = this._bindings;
  26983. let bindingByName = bindingsByRoot[rootUuid];
  26984. if (bindingByName === undefined) {
  26985. bindingByName = {};
  26986. bindingsByRoot[rootUuid] = bindingByName;
  26987. }
  26988. bindingByName[trackName] = binding;
  26989. binding._cacheIndex = bindings.length;
  26990. bindings.push(binding);
  26991. }
  26992. _removeInactiveBinding(binding) {
  26993. const bindings = this._bindings,
  26994. propBinding = binding.binding,
  26995. rootUuid = propBinding.rootNode.uuid,
  26996. trackName = propBinding.path,
  26997. bindingsByRoot = this._bindingsByRootAndName,
  26998. bindingByName = bindingsByRoot[rootUuid],
  26999. lastInactiveBinding = bindings[bindings.length - 1],
  27000. cacheIndex = binding._cacheIndex;
  27001. lastInactiveBinding._cacheIndex = cacheIndex;
  27002. bindings[cacheIndex] = lastInactiveBinding;
  27003. bindings.pop();
  27004. delete bindingByName[trackName];
  27005. if (Object.keys(bindingByName).length === 0) {
  27006. delete bindingsByRoot[rootUuid];
  27007. }
  27008. }
  27009. _lendBinding(binding) {
  27010. const bindings = this._bindings,
  27011. prevIndex = binding._cacheIndex,
  27012. lastActiveIndex = this._nActiveBindings++,
  27013. firstInactiveBinding = bindings[lastActiveIndex];
  27014. binding._cacheIndex = lastActiveIndex;
  27015. bindings[lastActiveIndex] = binding;
  27016. firstInactiveBinding._cacheIndex = prevIndex;
  27017. bindings[prevIndex] = firstInactiveBinding;
  27018. }
  27019. _takeBackBinding(binding) {
  27020. const bindings = this._bindings,
  27021. prevIndex = binding._cacheIndex,
  27022. firstInactiveIndex = --this._nActiveBindings,
  27023. lastActiveBinding = bindings[firstInactiveIndex];
  27024. binding._cacheIndex = firstInactiveIndex;
  27025. bindings[firstInactiveIndex] = binding;
  27026. lastActiveBinding._cacheIndex = prevIndex;
  27027. bindings[prevIndex] = lastActiveBinding;
  27028. } // Memory management of Interpolants for weight and time scale
  27029. _lendControlInterpolant() {
  27030. const interpolants = this._controlInterpolants,
  27031. lastActiveIndex = this._nActiveControlInterpolants++;
  27032. let interpolant = interpolants[lastActiveIndex];
  27033. if (interpolant === undefined) {
  27034. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  27035. interpolant.__cacheIndex = lastActiveIndex;
  27036. interpolants[lastActiveIndex] = interpolant;
  27037. }
  27038. return interpolant;
  27039. }
  27040. _takeBackControlInterpolant(interpolant) {
  27041. const interpolants = this._controlInterpolants,
  27042. prevIndex = interpolant.__cacheIndex,
  27043. firstInactiveIndex = --this._nActiveControlInterpolants,
  27044. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27045. interpolant.__cacheIndex = firstInactiveIndex;
  27046. interpolants[firstInactiveIndex] = interpolant;
  27047. lastActiveInterpolant.__cacheIndex = prevIndex;
  27048. interpolants[prevIndex] = lastActiveInterpolant;
  27049. } // return an action for a clip optionally using a custom root target
  27050. // object (this method allocates a lot of dynamic memory in case a
  27051. // previously unknown clip/root combination is specified)
  27052. clipAction(clip, optionalRoot, blendMode) {
  27053. const root = optionalRoot || this._root,
  27054. rootUuid = root.uuid;
  27055. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  27056. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27057. const actionsForClip = this._actionsByClip[clipUuid];
  27058. let prototypeAction = null;
  27059. if (blendMode === undefined) {
  27060. if (clipObject !== null) {
  27061. blendMode = clipObject.blendMode;
  27062. } else {
  27063. blendMode = NormalAnimationBlendMode;
  27064. }
  27065. }
  27066. if (actionsForClip !== undefined) {
  27067. const existingAction = actionsForClip.actionByRoot[rootUuid];
  27068. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  27069. return existingAction;
  27070. } // we know the clip, so we don't have to parse all
  27071. // the bindings again but can just copy
  27072. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27073. if (clipObject === null) clipObject = prototypeAction._clip;
  27074. } // clip must be known when specified via string
  27075. if (clipObject === null) return null; // allocate all resources required to run it
  27076. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27077. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27078. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27079. return newAction;
  27080. } // get an existing action
  27081. existingAction(clip, optionalRoot) {
  27082. const root = optionalRoot || this._root,
  27083. rootUuid = root.uuid,
  27084. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27085. clipUuid = clipObject ? clipObject.uuid : clip,
  27086. actionsForClip = this._actionsByClip[clipUuid];
  27087. if (actionsForClip !== undefined) {
  27088. return actionsForClip.actionByRoot[rootUuid] || null;
  27089. }
  27090. return null;
  27091. } // deactivates all previously scheduled actions
  27092. stopAllAction() {
  27093. const actions = this._actions,
  27094. nActions = this._nActiveActions;
  27095. for (let i = nActions - 1; i >= 0; --i) {
  27096. actions[i].stop();
  27097. }
  27098. return this;
  27099. } // advance the time and update apply the animation
  27100. update(deltaTime) {
  27101. deltaTime *= this.timeScale;
  27102. const actions = this._actions,
  27103. nActions = this._nActiveActions,
  27104. time = this.time += deltaTime,
  27105. timeDirection = Math.sign(deltaTime),
  27106. accuIndex = this._accuIndex ^= 1; // run active actions
  27107. for (let i = 0; i !== nActions; ++i) {
  27108. const action = actions[i];
  27109. action._update(time, deltaTime, timeDirection, accuIndex);
  27110. } // update scene graph
  27111. const bindings = this._bindings,
  27112. nBindings = this._nActiveBindings;
  27113. for (let i = 0; i !== nBindings; ++i) {
  27114. bindings[i].apply(accuIndex);
  27115. }
  27116. return this;
  27117. } // Allows you to seek to a specific time in an animation.
  27118. setTime(timeInSeconds) {
  27119. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27120. for (let i = 0; i < this._actions.length; i++) {
  27121. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27122. }
  27123. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27124. } // return this mixer's root target object
  27125. getRoot() {
  27126. return this._root;
  27127. } // free all resources specific to a particular clip
  27128. uncacheClip(clip) {
  27129. const actions = this._actions,
  27130. clipUuid = clip.uuid,
  27131. actionsByClip = this._actionsByClip,
  27132. actionsForClip = actionsByClip[clipUuid];
  27133. if (actionsForClip !== undefined) {
  27134. // note: just calling _removeInactiveAction would mess up the
  27135. // iteration state and also require updating the state we can
  27136. // just throw away
  27137. const actionsToRemove = actionsForClip.knownActions;
  27138. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27139. const action = actionsToRemove[i];
  27140. this._deactivateAction(action);
  27141. const cacheIndex = action._cacheIndex,
  27142. lastInactiveAction = actions[actions.length - 1];
  27143. action._cacheIndex = null;
  27144. action._byClipCacheIndex = null;
  27145. lastInactiveAction._cacheIndex = cacheIndex;
  27146. actions[cacheIndex] = lastInactiveAction;
  27147. actions.pop();
  27148. this._removeInactiveBindingsForAction(action);
  27149. }
  27150. delete actionsByClip[clipUuid];
  27151. }
  27152. } // free all resources specific to a particular root target object
  27153. uncacheRoot(root) {
  27154. const rootUuid = root.uuid,
  27155. actionsByClip = this._actionsByClip;
  27156. for (const clipUuid in actionsByClip) {
  27157. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27158. action = actionByRoot[rootUuid];
  27159. if (action !== undefined) {
  27160. this._deactivateAction(action);
  27161. this._removeInactiveAction(action);
  27162. }
  27163. }
  27164. const bindingsByRoot = this._bindingsByRootAndName,
  27165. bindingByName = bindingsByRoot[rootUuid];
  27166. if (bindingByName !== undefined) {
  27167. for (const trackName in bindingByName) {
  27168. const binding = bindingByName[trackName];
  27169. binding.restoreOriginalState();
  27170. this._removeInactiveBinding(binding);
  27171. }
  27172. }
  27173. } // remove a targeted clip from the cache
  27174. uncacheAction(clip, optionalRoot) {
  27175. const action = this.existingAction(clip, optionalRoot);
  27176. if (action !== null) {
  27177. this._deactivateAction(action);
  27178. this._removeInactiveAction(action);
  27179. }
  27180. }
  27181. }
  27182. class Uniform {
  27183. constructor(value) {
  27184. this.value = value;
  27185. }
  27186. clone() {
  27187. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27188. }
  27189. }
  27190. let id = 0;
  27191. class UniformsGroup extends EventDispatcher {
  27192. constructor() {
  27193. super();
  27194. this.isUniformsGroup = true;
  27195. Object.defineProperty(this, 'id', {
  27196. value: id++
  27197. });
  27198. this.name = '';
  27199. this.usage = StaticDrawUsage;
  27200. this.uniforms = [];
  27201. }
  27202. add(uniform) {
  27203. this.uniforms.push(uniform);
  27204. return this;
  27205. }
  27206. remove(uniform) {
  27207. const index = this.uniforms.indexOf(uniform);
  27208. if (index !== -1) this.uniforms.splice(index, 1);
  27209. return this;
  27210. }
  27211. setName(name) {
  27212. this.name = name;
  27213. return this;
  27214. }
  27215. setUsage(value) {
  27216. this.usage = value;
  27217. return this;
  27218. }
  27219. dispose() {
  27220. this.dispatchEvent({
  27221. type: 'dispose'
  27222. });
  27223. return this;
  27224. }
  27225. copy(source) {
  27226. this.name = source.name;
  27227. this.usage = source.usage;
  27228. const uniformsSource = source.uniforms;
  27229. this.uniforms.length = 0;
  27230. for (let i = 0, l = uniformsSource.length; i < l; i++) {
  27231. this.uniforms.push(uniformsSource[i].clone());
  27232. }
  27233. return this;
  27234. }
  27235. clone() {
  27236. return new this.constructor().copy(this);
  27237. }
  27238. }
  27239. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27240. constructor(array, stride, meshPerAttribute = 1) {
  27241. super(array, stride);
  27242. this.isInstancedInterleavedBuffer = true;
  27243. this.meshPerAttribute = meshPerAttribute;
  27244. }
  27245. copy(source) {
  27246. super.copy(source);
  27247. this.meshPerAttribute = source.meshPerAttribute;
  27248. return this;
  27249. }
  27250. clone(data) {
  27251. const ib = super.clone(data);
  27252. ib.meshPerAttribute = this.meshPerAttribute;
  27253. return ib;
  27254. }
  27255. toJSON(data) {
  27256. const json = super.toJSON(data);
  27257. json.isInstancedInterleavedBuffer = true;
  27258. json.meshPerAttribute = this.meshPerAttribute;
  27259. return json;
  27260. }
  27261. }
  27262. class GLBufferAttribute {
  27263. constructor(buffer, type, itemSize, elementSize, count) {
  27264. this.isGLBufferAttribute = true;
  27265. this.buffer = buffer;
  27266. this.type = type;
  27267. this.itemSize = itemSize;
  27268. this.elementSize = elementSize;
  27269. this.count = count;
  27270. this.version = 0;
  27271. }
  27272. set needsUpdate(value) {
  27273. if (value === true) this.version++;
  27274. }
  27275. setBuffer(buffer) {
  27276. this.buffer = buffer;
  27277. return this;
  27278. }
  27279. setType(type, elementSize) {
  27280. this.type = type;
  27281. this.elementSize = elementSize;
  27282. return this;
  27283. }
  27284. setItemSize(itemSize) {
  27285. this.itemSize = itemSize;
  27286. return this;
  27287. }
  27288. setCount(count) {
  27289. this.count = count;
  27290. return this;
  27291. }
  27292. }
  27293. class Raycaster {
  27294. constructor(origin, direction, near = 0, far = Infinity) {
  27295. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27296. this.near = near;
  27297. this.far = far;
  27298. this.camera = null;
  27299. this.layers = new Layers();
  27300. this.params = {
  27301. Mesh: {},
  27302. Line: {
  27303. threshold: 1
  27304. },
  27305. LOD: {},
  27306. Points: {
  27307. threshold: 1
  27308. },
  27309. Sprite: {}
  27310. };
  27311. }
  27312. set(origin, direction) {
  27313. // direction is assumed to be normalized (for accurate distance calculations)
  27314. this.ray.set(origin, direction);
  27315. }
  27316. setFromCamera(coords, camera) {
  27317. if (camera.isPerspectiveCamera) {
  27318. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27319. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27320. this.camera = camera;
  27321. } else if (camera.isOrthographicCamera) {
  27322. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27323. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27324. this.camera = camera;
  27325. } else {
  27326. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27327. }
  27328. }
  27329. intersectObject(object, recursive = true, intersects = []) {
  27330. intersectObject(object, this, intersects, recursive);
  27331. intersects.sort(ascSort);
  27332. return intersects;
  27333. }
  27334. intersectObjects(objects, recursive = true, intersects = []) {
  27335. for (let i = 0, l = objects.length; i < l; i++) {
  27336. intersectObject(objects[i], this, intersects, recursive);
  27337. }
  27338. intersects.sort(ascSort);
  27339. return intersects;
  27340. }
  27341. }
  27342. function ascSort(a, b) {
  27343. return a.distance - b.distance;
  27344. }
  27345. function intersectObject(object, raycaster, intersects, recursive) {
  27346. if (object.layers.test(raycaster.layers)) {
  27347. object.raycast(raycaster, intersects);
  27348. }
  27349. if (recursive === true) {
  27350. const children = object.children;
  27351. for (let i = 0, l = children.length; i < l; i++) {
  27352. intersectObject(children[i], raycaster, intersects, true);
  27353. }
  27354. }
  27355. }
  27356. /**
  27357. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27358. *
  27359. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27360. * The azimuthal angle (theta) is measured from the positive z-axis.
  27361. */
  27362. class Spherical {
  27363. constructor(radius = 1, phi = 0, theta = 0) {
  27364. this.radius = radius;
  27365. this.phi = phi; // polar angle
  27366. this.theta = theta; // azimuthal angle
  27367. return this;
  27368. }
  27369. set(radius, phi, theta) {
  27370. this.radius = radius;
  27371. this.phi = phi;
  27372. this.theta = theta;
  27373. return this;
  27374. }
  27375. copy(other) {
  27376. this.radius = other.radius;
  27377. this.phi = other.phi;
  27378. this.theta = other.theta;
  27379. return this;
  27380. } // restrict phi to be between EPS and PI-EPS
  27381. makeSafe() {
  27382. const EPS = 0.000001;
  27383. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27384. return this;
  27385. }
  27386. setFromVector3(v) {
  27387. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27388. }
  27389. setFromCartesianCoords(x, y, z) {
  27390. this.radius = Math.sqrt(x * x + y * y + z * z);
  27391. if (this.radius === 0) {
  27392. this.theta = 0;
  27393. this.phi = 0;
  27394. } else {
  27395. this.theta = Math.atan2(x, z);
  27396. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27397. }
  27398. return this;
  27399. }
  27400. clone() {
  27401. return new this.constructor().copy(this);
  27402. }
  27403. }
  27404. /**
  27405. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27406. */
  27407. class Cylindrical {
  27408. constructor(radius = 1, theta = 0, y = 0) {
  27409. this.radius = radius; // distance from the origin to a point in the x-z plane
  27410. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27411. this.y = y; // height above the x-z plane
  27412. return this;
  27413. }
  27414. set(radius, theta, y) {
  27415. this.radius = radius;
  27416. this.theta = theta;
  27417. this.y = y;
  27418. return this;
  27419. }
  27420. copy(other) {
  27421. this.radius = other.radius;
  27422. this.theta = other.theta;
  27423. this.y = other.y;
  27424. return this;
  27425. }
  27426. setFromVector3(v) {
  27427. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27428. }
  27429. setFromCartesianCoords(x, y, z) {
  27430. this.radius = Math.sqrt(x * x + z * z);
  27431. this.theta = Math.atan2(x, z);
  27432. this.y = y;
  27433. return this;
  27434. }
  27435. clone() {
  27436. return new this.constructor().copy(this);
  27437. }
  27438. }
  27439. const _vector$4 = /*@__PURE__*/new Vector2();
  27440. class Box2 {
  27441. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27442. this.isBox2 = true;
  27443. this.min = min;
  27444. this.max = max;
  27445. }
  27446. set(min, max) {
  27447. this.min.copy(min);
  27448. this.max.copy(max);
  27449. return this;
  27450. }
  27451. setFromPoints(points) {
  27452. this.makeEmpty();
  27453. for (let i = 0, il = points.length; i < il; i++) {
  27454. this.expandByPoint(points[i]);
  27455. }
  27456. return this;
  27457. }
  27458. setFromCenterAndSize(center, size) {
  27459. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27460. this.min.copy(center).sub(halfSize);
  27461. this.max.copy(center).add(halfSize);
  27462. return this;
  27463. }
  27464. clone() {
  27465. return new this.constructor().copy(this);
  27466. }
  27467. copy(box) {
  27468. this.min.copy(box.min);
  27469. this.max.copy(box.max);
  27470. return this;
  27471. }
  27472. makeEmpty() {
  27473. this.min.x = this.min.y = +Infinity;
  27474. this.max.x = this.max.y = -Infinity;
  27475. return this;
  27476. }
  27477. isEmpty() {
  27478. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27479. return this.max.x < this.min.x || this.max.y < this.min.y;
  27480. }
  27481. getCenter(target) {
  27482. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27483. }
  27484. getSize(target) {
  27485. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27486. }
  27487. expandByPoint(point) {
  27488. this.min.min(point);
  27489. this.max.max(point);
  27490. return this;
  27491. }
  27492. expandByVector(vector) {
  27493. this.min.sub(vector);
  27494. this.max.add(vector);
  27495. return this;
  27496. }
  27497. expandByScalar(scalar) {
  27498. this.min.addScalar(-scalar);
  27499. this.max.addScalar(scalar);
  27500. return this;
  27501. }
  27502. containsPoint(point) {
  27503. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27504. }
  27505. containsBox(box) {
  27506. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  27507. }
  27508. getParameter(point, target) {
  27509. // This can potentially have a divide by zero if the box
  27510. // has a size dimension of 0.
  27511. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  27512. }
  27513. intersectsBox(box) {
  27514. // using 4 splitting planes to rule out intersections
  27515. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27516. }
  27517. clampPoint(point, target) {
  27518. return target.copy(point).clamp(this.min, this.max);
  27519. }
  27520. distanceToPoint(point) {
  27521. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27522. return clampedPoint.sub(point).length();
  27523. }
  27524. intersect(box) {
  27525. this.min.max(box.min);
  27526. this.max.min(box.max);
  27527. return this;
  27528. }
  27529. union(box) {
  27530. this.min.min(box.min);
  27531. this.max.max(box.max);
  27532. return this;
  27533. }
  27534. translate(offset) {
  27535. this.min.add(offset);
  27536. this.max.add(offset);
  27537. return this;
  27538. }
  27539. equals(box) {
  27540. return box.min.equals(this.min) && box.max.equals(this.max);
  27541. }
  27542. }
  27543. const _startP = /*@__PURE__*/new Vector3();
  27544. const _startEnd = /*@__PURE__*/new Vector3();
  27545. class Line3 {
  27546. constructor(start = new Vector3(), end = new Vector3()) {
  27547. this.start = start;
  27548. this.end = end;
  27549. }
  27550. set(start, end) {
  27551. this.start.copy(start);
  27552. this.end.copy(end);
  27553. return this;
  27554. }
  27555. copy(line) {
  27556. this.start.copy(line.start);
  27557. this.end.copy(line.end);
  27558. return this;
  27559. }
  27560. getCenter(target) {
  27561. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27562. }
  27563. delta(target) {
  27564. return target.subVectors(this.end, this.start);
  27565. }
  27566. distanceSq() {
  27567. return this.start.distanceToSquared(this.end);
  27568. }
  27569. distance() {
  27570. return this.start.distanceTo(this.end);
  27571. }
  27572. at(t, target) {
  27573. return this.delta(target).multiplyScalar(t).add(this.start);
  27574. }
  27575. closestPointToPointParameter(point, clampToLine) {
  27576. _startP.subVectors(point, this.start);
  27577. _startEnd.subVectors(this.end, this.start);
  27578. const startEnd2 = _startEnd.dot(_startEnd);
  27579. const startEnd_startP = _startEnd.dot(_startP);
  27580. let t = startEnd_startP / startEnd2;
  27581. if (clampToLine) {
  27582. t = clamp(t, 0, 1);
  27583. }
  27584. return t;
  27585. }
  27586. closestPointToPoint(point, clampToLine, target) {
  27587. const t = this.closestPointToPointParameter(point, clampToLine);
  27588. return this.delta(target).multiplyScalar(t).add(this.start);
  27589. }
  27590. applyMatrix4(matrix) {
  27591. this.start.applyMatrix4(matrix);
  27592. this.end.applyMatrix4(matrix);
  27593. return this;
  27594. }
  27595. equals(line) {
  27596. return line.start.equals(this.start) && line.end.equals(this.end);
  27597. }
  27598. clone() {
  27599. return new this.constructor().copy(this);
  27600. }
  27601. }
  27602. const _vector$3 = /*@__PURE__*/new Vector3();
  27603. class SpotLightHelper extends Object3D {
  27604. constructor(light, color) {
  27605. super();
  27606. this.light = light;
  27607. this.light.updateMatrixWorld();
  27608. this.matrix = light.matrixWorld;
  27609. this.matrixAutoUpdate = false;
  27610. this.color = color;
  27611. const geometry = new BufferGeometry();
  27612. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  27613. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27614. const p1 = i / l * Math.PI * 2;
  27615. const p2 = j / l * Math.PI * 2;
  27616. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27617. }
  27618. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27619. const material = new LineBasicMaterial({
  27620. fog: false,
  27621. toneMapped: false
  27622. });
  27623. this.cone = new LineSegments(geometry, material);
  27624. this.add(this.cone);
  27625. this.update();
  27626. }
  27627. dispose() {
  27628. this.cone.geometry.dispose();
  27629. this.cone.material.dispose();
  27630. }
  27631. update() {
  27632. this.light.updateMatrixWorld();
  27633. const coneLength = this.light.distance ? this.light.distance : 1000;
  27634. const coneWidth = coneLength * Math.tan(this.light.angle);
  27635. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27636. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27637. this.cone.lookAt(_vector$3);
  27638. if (this.color !== undefined) {
  27639. this.cone.material.color.set(this.color);
  27640. } else {
  27641. this.cone.material.color.copy(this.light.color);
  27642. }
  27643. }
  27644. }
  27645. const _vector$2 = /*@__PURE__*/new Vector3();
  27646. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27647. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27648. class SkeletonHelper extends LineSegments {
  27649. constructor(object) {
  27650. const bones = getBoneList(object);
  27651. const geometry = new BufferGeometry();
  27652. const vertices = [];
  27653. const colors = [];
  27654. const color1 = new Color(0, 0, 1);
  27655. const color2 = new Color(0, 1, 0);
  27656. for (let i = 0; i < bones.length; i++) {
  27657. const bone = bones[i];
  27658. if (bone.parent && bone.parent.isBone) {
  27659. vertices.push(0, 0, 0);
  27660. vertices.push(0, 0, 0);
  27661. colors.push(color1.r, color1.g, color1.b);
  27662. colors.push(color2.r, color2.g, color2.b);
  27663. }
  27664. }
  27665. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27666. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27667. const material = new LineBasicMaterial({
  27668. vertexColors: true,
  27669. depthTest: false,
  27670. depthWrite: false,
  27671. toneMapped: false,
  27672. transparent: true
  27673. });
  27674. super(geometry, material);
  27675. this.isSkeletonHelper = true;
  27676. this.type = 'SkeletonHelper';
  27677. this.root = object;
  27678. this.bones = bones;
  27679. this.matrix = object.matrixWorld;
  27680. this.matrixAutoUpdate = false;
  27681. }
  27682. updateMatrixWorld(force) {
  27683. const bones = this.bones;
  27684. const geometry = this.geometry;
  27685. const position = geometry.getAttribute('position');
  27686. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27687. for (let i = 0, j = 0; i < bones.length; i++) {
  27688. const bone = bones[i];
  27689. if (bone.parent && bone.parent.isBone) {
  27690. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27691. _vector$2.setFromMatrixPosition(_boneMatrix);
  27692. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27693. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27694. _vector$2.setFromMatrixPosition(_boneMatrix);
  27695. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27696. j += 2;
  27697. }
  27698. }
  27699. geometry.getAttribute('position').needsUpdate = true;
  27700. super.updateMatrixWorld(force);
  27701. }
  27702. }
  27703. function getBoneList(object) {
  27704. const boneList = [];
  27705. if (object.isBone === true) {
  27706. boneList.push(object);
  27707. }
  27708. for (let i = 0; i < object.children.length; i++) {
  27709. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27710. }
  27711. return boneList;
  27712. }
  27713. class PointLightHelper extends Mesh {
  27714. constructor(light, sphereSize, color) {
  27715. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27716. const material = new MeshBasicMaterial({
  27717. wireframe: true,
  27718. fog: false,
  27719. toneMapped: false
  27720. });
  27721. super(geometry, material);
  27722. this.light = light;
  27723. this.light.updateMatrixWorld();
  27724. this.color = color;
  27725. this.type = 'PointLightHelper';
  27726. this.matrix = this.light.matrixWorld;
  27727. this.matrixAutoUpdate = false;
  27728. this.update();
  27729. /*
  27730. // TODO: delete this comment?
  27731. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  27732. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27733. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27734. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27735. const d = light.distance;
  27736. if ( d === 0.0 ) {
  27737. this.lightDistance.visible = false;
  27738. } else {
  27739. this.lightDistance.scale.set( d, d, d );
  27740. }
  27741. this.add( this.lightDistance );
  27742. */
  27743. }
  27744. dispose() {
  27745. this.geometry.dispose();
  27746. this.material.dispose();
  27747. }
  27748. update() {
  27749. if (this.color !== undefined) {
  27750. this.material.color.set(this.color);
  27751. } else {
  27752. this.material.color.copy(this.light.color);
  27753. }
  27754. /*
  27755. const d = this.light.distance;
  27756. if ( d === 0.0 ) {
  27757. this.lightDistance.visible = false;
  27758. } else {
  27759. this.lightDistance.visible = true;
  27760. this.lightDistance.scale.set( d, d, d );
  27761. }
  27762. */
  27763. }
  27764. }
  27765. const _vector$1 = /*@__PURE__*/new Vector3();
  27766. const _color1 = /*@__PURE__*/new Color();
  27767. const _color2 = /*@__PURE__*/new Color();
  27768. class HemisphereLightHelper extends Object3D {
  27769. constructor(light, size, color) {
  27770. super();
  27771. this.light = light;
  27772. this.light.updateMatrixWorld();
  27773. this.matrix = light.matrixWorld;
  27774. this.matrixAutoUpdate = false;
  27775. this.color = color;
  27776. const geometry = new OctahedronGeometry(size);
  27777. geometry.rotateY(Math.PI * 0.5);
  27778. this.material = new MeshBasicMaterial({
  27779. wireframe: true,
  27780. fog: false,
  27781. toneMapped: false
  27782. });
  27783. if (this.color === undefined) this.material.vertexColors = true;
  27784. const position = geometry.getAttribute('position');
  27785. const colors = new Float32Array(position.count * 3);
  27786. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27787. this.add(new Mesh(geometry, this.material));
  27788. this.update();
  27789. }
  27790. dispose() {
  27791. this.children[0].geometry.dispose();
  27792. this.children[0].material.dispose();
  27793. }
  27794. update() {
  27795. const mesh = this.children[0];
  27796. if (this.color !== undefined) {
  27797. this.material.color.set(this.color);
  27798. } else {
  27799. const colors = mesh.geometry.getAttribute('color');
  27800. _color1.copy(this.light.color);
  27801. _color2.copy(this.light.groundColor);
  27802. for (let i = 0, l = colors.count; i < l; i++) {
  27803. const color = i < l / 2 ? _color1 : _color2;
  27804. colors.setXYZ(i, color.r, color.g, color.b);
  27805. }
  27806. colors.needsUpdate = true;
  27807. }
  27808. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27809. }
  27810. }
  27811. class GridHelper extends LineSegments {
  27812. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27813. color1 = new Color(color1);
  27814. color2 = new Color(color2);
  27815. const center = divisions / 2;
  27816. const step = size / divisions;
  27817. const halfSize = size / 2;
  27818. const vertices = [],
  27819. colors = [];
  27820. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27821. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27822. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27823. const color = i === center ? color1 : color2;
  27824. color.toArray(colors, j);
  27825. j += 3;
  27826. color.toArray(colors, j);
  27827. j += 3;
  27828. color.toArray(colors, j);
  27829. j += 3;
  27830. color.toArray(colors, j);
  27831. j += 3;
  27832. }
  27833. const geometry = new BufferGeometry();
  27834. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27835. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27836. const material = new LineBasicMaterial({
  27837. vertexColors: true,
  27838. toneMapped: false
  27839. });
  27840. super(geometry, material);
  27841. this.type = 'GridHelper';
  27842. }
  27843. }
  27844. class PolarGridHelper extends LineSegments {
  27845. constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27846. color1 = new Color(color1);
  27847. color2 = new Color(color2);
  27848. const vertices = [];
  27849. const colors = []; // create the sectors
  27850. if (sectors > 1) {
  27851. for (let i = 0; i < sectors; i++) {
  27852. const v = i / sectors * (Math.PI * 2);
  27853. const x = Math.sin(v) * radius;
  27854. const z = Math.cos(v) * radius;
  27855. vertices.push(0, 0, 0);
  27856. vertices.push(x, 0, z);
  27857. const color = i & 1 ? color1 : color2;
  27858. colors.push(color.r, color.g, color.b);
  27859. colors.push(color.r, color.g, color.b);
  27860. }
  27861. } // create the rings
  27862. for (let i = 0; i < rings; i++) {
  27863. const color = i & 1 ? color1 : color2;
  27864. const r = radius - radius / rings * i;
  27865. for (let j = 0; j < divisions; j++) {
  27866. // first vertex
  27867. let v = j / divisions * (Math.PI * 2);
  27868. let x = Math.sin(v) * r;
  27869. let z = Math.cos(v) * r;
  27870. vertices.push(x, 0, z);
  27871. colors.push(color.r, color.g, color.b); // second vertex
  27872. v = (j + 1) / divisions * (Math.PI * 2);
  27873. x = Math.sin(v) * r;
  27874. z = Math.cos(v) * r;
  27875. vertices.push(x, 0, z);
  27876. colors.push(color.r, color.g, color.b);
  27877. }
  27878. }
  27879. const geometry = new BufferGeometry();
  27880. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27881. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27882. const material = new LineBasicMaterial({
  27883. vertexColors: true,
  27884. toneMapped: false
  27885. });
  27886. super(geometry, material);
  27887. this.type = 'PolarGridHelper';
  27888. }
  27889. }
  27890. const _v1 = /*@__PURE__*/new Vector3();
  27891. const _v2 = /*@__PURE__*/new Vector3();
  27892. const _v3 = /*@__PURE__*/new Vector3();
  27893. class DirectionalLightHelper extends Object3D {
  27894. constructor(light, size, color) {
  27895. super();
  27896. this.light = light;
  27897. this.light.updateMatrixWorld();
  27898. this.matrix = light.matrixWorld;
  27899. this.matrixAutoUpdate = false;
  27900. this.color = color;
  27901. if (size === undefined) size = 1;
  27902. let geometry = new BufferGeometry();
  27903. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27904. const material = new LineBasicMaterial({
  27905. fog: false,
  27906. toneMapped: false
  27907. });
  27908. this.lightPlane = new Line(geometry, material);
  27909. this.add(this.lightPlane);
  27910. geometry = new BufferGeometry();
  27911. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27912. this.targetLine = new Line(geometry, material);
  27913. this.add(this.targetLine);
  27914. this.update();
  27915. }
  27916. dispose() {
  27917. this.lightPlane.geometry.dispose();
  27918. this.lightPlane.material.dispose();
  27919. this.targetLine.geometry.dispose();
  27920. this.targetLine.material.dispose();
  27921. }
  27922. update() {
  27923. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27924. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27925. _v3.subVectors(_v2, _v1);
  27926. this.lightPlane.lookAt(_v2);
  27927. if (this.color !== undefined) {
  27928. this.lightPlane.material.color.set(this.color);
  27929. this.targetLine.material.color.set(this.color);
  27930. } else {
  27931. this.lightPlane.material.color.copy(this.light.color);
  27932. this.targetLine.material.color.copy(this.light.color);
  27933. }
  27934. this.targetLine.lookAt(_v2);
  27935. this.targetLine.scale.z = _v3.length();
  27936. }
  27937. }
  27938. const _vector = /*@__PURE__*/new Vector3();
  27939. const _camera = /*@__PURE__*/new Camera();
  27940. /**
  27941. * - shows frustum, line of sight and up of the camera
  27942. * - suitable for fast updates
  27943. * - based on frustum visualization in lightgl.js shadowmap example
  27944. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27945. */
  27946. class CameraHelper extends LineSegments {
  27947. constructor(camera) {
  27948. const geometry = new BufferGeometry();
  27949. const material = new LineBasicMaterial({
  27950. color: 0xffffff,
  27951. vertexColors: true,
  27952. toneMapped: false
  27953. });
  27954. const vertices = [];
  27955. const colors = [];
  27956. const pointMap = {}; // near
  27957. addLine('n1', 'n2');
  27958. addLine('n2', 'n4');
  27959. addLine('n4', 'n3');
  27960. addLine('n3', 'n1'); // far
  27961. addLine('f1', 'f2');
  27962. addLine('f2', 'f4');
  27963. addLine('f4', 'f3');
  27964. addLine('f3', 'f1'); // sides
  27965. addLine('n1', 'f1');
  27966. addLine('n2', 'f2');
  27967. addLine('n3', 'f3');
  27968. addLine('n4', 'f4'); // cone
  27969. addLine('p', 'n1');
  27970. addLine('p', 'n2');
  27971. addLine('p', 'n3');
  27972. addLine('p', 'n4'); // up
  27973. addLine('u1', 'u2');
  27974. addLine('u2', 'u3');
  27975. addLine('u3', 'u1'); // target
  27976. addLine('c', 't');
  27977. addLine('p', 'c'); // cross
  27978. addLine('cn1', 'cn2');
  27979. addLine('cn3', 'cn4');
  27980. addLine('cf1', 'cf2');
  27981. addLine('cf3', 'cf4');
  27982. function addLine(a, b) {
  27983. addPoint(a);
  27984. addPoint(b);
  27985. }
  27986. function addPoint(id) {
  27987. vertices.push(0, 0, 0);
  27988. colors.push(0, 0, 0);
  27989. if (pointMap[id] === undefined) {
  27990. pointMap[id] = [];
  27991. }
  27992. pointMap[id].push(vertices.length / 3 - 1);
  27993. }
  27994. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27995. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27996. super(geometry, material);
  27997. this.type = 'CameraHelper';
  27998. this.camera = camera;
  27999. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28000. this.matrix = camera.matrixWorld;
  28001. this.matrixAutoUpdate = false;
  28002. this.pointMap = pointMap;
  28003. this.update(); // colors
  28004. const colorFrustum = new Color(0xffaa00);
  28005. const colorCone = new Color(0xff0000);
  28006. const colorUp = new Color(0x00aaff);
  28007. const colorTarget = new Color(0xffffff);
  28008. const colorCross = new Color(0x333333);
  28009. this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross);
  28010. }
  28011. setColors(frustum, cone, up, target, cross) {
  28012. const geometry = this.geometry;
  28013. const colorAttribute = geometry.getAttribute('color'); // near
  28014. colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b);
  28015. colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); // n1, n2
  28016. colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b);
  28017. colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); // n2, n4
  28018. colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b);
  28019. colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); // n4, n3
  28020. colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b);
  28021. colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); // n3, n1
  28022. // far
  28023. colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b);
  28024. colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); // f1, f2
  28025. colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b);
  28026. colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); // f2, f4
  28027. colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b);
  28028. colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); // f4, f3
  28029. colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b);
  28030. colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); // f3, f1
  28031. // sides
  28032. colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b);
  28033. colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); // n1, f1
  28034. colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b);
  28035. colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); // n2, f2
  28036. colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b);
  28037. colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); // n3, f3
  28038. colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b);
  28039. colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); // n4, f4
  28040. // cone
  28041. colorAttribute.setXYZ(24, cone.r, cone.g, cone.b);
  28042. colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); // p, n1
  28043. colorAttribute.setXYZ(26, cone.r, cone.g, cone.b);
  28044. colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); // p, n2
  28045. colorAttribute.setXYZ(28, cone.r, cone.g, cone.b);
  28046. colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); // p, n3
  28047. colorAttribute.setXYZ(30, cone.r, cone.g, cone.b);
  28048. colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); // p, n4
  28049. // up
  28050. colorAttribute.setXYZ(32, up.r, up.g, up.b);
  28051. colorAttribute.setXYZ(33, up.r, up.g, up.b); // u1, u2
  28052. colorAttribute.setXYZ(34, up.r, up.g, up.b);
  28053. colorAttribute.setXYZ(35, up.r, up.g, up.b); // u2, u3
  28054. colorAttribute.setXYZ(36, up.r, up.g, up.b);
  28055. colorAttribute.setXYZ(37, up.r, up.g, up.b); // u3, u1
  28056. // target
  28057. colorAttribute.setXYZ(38, target.r, target.g, target.b);
  28058. colorAttribute.setXYZ(39, target.r, target.g, target.b); // c, t
  28059. colorAttribute.setXYZ(40, cross.r, cross.g, cross.b);
  28060. colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); // p, c
  28061. // cross
  28062. colorAttribute.setXYZ(42, cross.r, cross.g, cross.b);
  28063. colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); // cn1, cn2
  28064. colorAttribute.setXYZ(44, cross.r, cross.g, cross.b);
  28065. colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); // cn3, cn4
  28066. colorAttribute.setXYZ(46, cross.r, cross.g, cross.b);
  28067. colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); // cf1, cf2
  28068. colorAttribute.setXYZ(48, cross.r, cross.g, cross.b);
  28069. colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); // cf3, cf4
  28070. colorAttribute.needsUpdate = true;
  28071. }
  28072. update() {
  28073. const geometry = this.geometry;
  28074. const pointMap = this.pointMap;
  28075. const w = 1,
  28076. h = 1; // we need just camera projection matrix inverse
  28077. // world matrix must be identity
  28078. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28079. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28080. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28081. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28082. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28083. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28084. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28085. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28086. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28087. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28088. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28089. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28090. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28091. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28092. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28093. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28094. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28095. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28096. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28097. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28098. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28099. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28100. geometry.getAttribute('position').needsUpdate = true;
  28101. }
  28102. dispose() {
  28103. this.geometry.dispose();
  28104. this.material.dispose();
  28105. }
  28106. }
  28107. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28108. _vector.set(x, y, z).unproject(camera);
  28109. const points = pointMap[point];
  28110. if (points !== undefined) {
  28111. const position = geometry.getAttribute('position');
  28112. for (let i = 0, l = points.length; i < l; i++) {
  28113. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  28114. }
  28115. }
  28116. }
  28117. const _box = /*@__PURE__*/new Box3();
  28118. class BoxHelper extends LineSegments {
  28119. constructor(object, color = 0xffff00) {
  28120. const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  28121. const positions = new Float32Array(8 * 3);
  28122. const geometry = new BufferGeometry();
  28123. geometry.setIndex(new BufferAttribute(indices, 1));
  28124. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28125. super(geometry, new LineBasicMaterial({
  28126. color: color,
  28127. toneMapped: false
  28128. }));
  28129. this.object = object;
  28130. this.type = 'BoxHelper';
  28131. this.matrixAutoUpdate = false;
  28132. this.update();
  28133. }
  28134. update(object) {
  28135. if (object !== undefined) {
  28136. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28137. }
  28138. if (this.object !== undefined) {
  28139. _box.setFromObject(this.object);
  28140. }
  28141. if (_box.isEmpty()) return;
  28142. const min = _box.min;
  28143. const max = _box.max;
  28144. /*
  28145. 5____4
  28146. 1/___0/|
  28147. | 6__|_7
  28148. 2/___3/
  28149. 0: max.x, max.y, max.z
  28150. 1: min.x, max.y, max.z
  28151. 2: min.x, min.y, max.z
  28152. 3: max.x, min.y, max.z
  28153. 4: max.x, max.y, min.z
  28154. 5: min.x, max.y, min.z
  28155. 6: min.x, min.y, min.z
  28156. 7: max.x, min.y, min.z
  28157. */
  28158. const position = this.geometry.attributes.position;
  28159. const array = position.array;
  28160. array[0] = max.x;
  28161. array[1] = max.y;
  28162. array[2] = max.z;
  28163. array[3] = min.x;
  28164. array[4] = max.y;
  28165. array[5] = max.z;
  28166. array[6] = min.x;
  28167. array[7] = min.y;
  28168. array[8] = max.z;
  28169. array[9] = max.x;
  28170. array[10] = min.y;
  28171. array[11] = max.z;
  28172. array[12] = max.x;
  28173. array[13] = max.y;
  28174. array[14] = min.z;
  28175. array[15] = min.x;
  28176. array[16] = max.y;
  28177. array[17] = min.z;
  28178. array[18] = min.x;
  28179. array[19] = min.y;
  28180. array[20] = min.z;
  28181. array[21] = max.x;
  28182. array[22] = min.y;
  28183. array[23] = min.z;
  28184. position.needsUpdate = true;
  28185. this.geometry.computeBoundingSphere();
  28186. }
  28187. setFromObject(object) {
  28188. this.object = object;
  28189. this.update();
  28190. return this;
  28191. }
  28192. copy(source, recursive) {
  28193. super.copy(source, recursive);
  28194. this.object = source.object;
  28195. return this;
  28196. }
  28197. }
  28198. class Box3Helper extends LineSegments {
  28199. constructor(box, color = 0xffff00) {
  28200. const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  28201. const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
  28202. const geometry = new BufferGeometry();
  28203. geometry.setIndex(new BufferAttribute(indices, 1));
  28204. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28205. super(geometry, new LineBasicMaterial({
  28206. color: color,
  28207. toneMapped: false
  28208. }));
  28209. this.box = box;
  28210. this.type = 'Box3Helper';
  28211. this.geometry.computeBoundingSphere();
  28212. }
  28213. updateMatrixWorld(force) {
  28214. const box = this.box;
  28215. if (box.isEmpty()) return;
  28216. box.getCenter(this.position);
  28217. box.getSize(this.scale);
  28218. this.scale.multiplyScalar(0.5);
  28219. super.updateMatrixWorld(force);
  28220. }
  28221. }
  28222. class PlaneHelper extends Line {
  28223. constructor(plane, size = 1, hex = 0xffff00) {
  28224. const color = hex;
  28225. const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0];
  28226. const geometry = new BufferGeometry();
  28227. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28228. geometry.computeBoundingSphere();
  28229. super(geometry, new LineBasicMaterial({
  28230. color: color,
  28231. toneMapped: false
  28232. }));
  28233. this.type = 'PlaneHelper';
  28234. this.plane = plane;
  28235. this.size = size;
  28236. const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0];
  28237. const geometry2 = new BufferGeometry();
  28238. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28239. geometry2.computeBoundingSphere();
  28240. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28241. color: color,
  28242. opacity: 0.2,
  28243. transparent: true,
  28244. depthWrite: false,
  28245. toneMapped: false
  28246. })));
  28247. }
  28248. updateMatrixWorld(force) {
  28249. this.position.set(0, 0, 0);
  28250. this.scale.set(0.5 * this.size, 0.5 * this.size, 1);
  28251. this.lookAt(this.plane.normal);
  28252. this.translateZ(-this.plane.constant);
  28253. super.updateMatrixWorld(force);
  28254. }
  28255. }
  28256. const _axis = /*@__PURE__*/new Vector3();
  28257. let _lineGeometry, _coneGeometry;
  28258. class ArrowHelper extends Object3D {
  28259. // dir is assumed to be normalized
  28260. constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2) {
  28261. super();
  28262. this.type = 'ArrowHelper';
  28263. if (_lineGeometry === undefined) {
  28264. _lineGeometry = new BufferGeometry();
  28265. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28266. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  28267. _coneGeometry.translate(0, -0.5, 0);
  28268. }
  28269. this.position.copy(origin);
  28270. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28271. color: color,
  28272. toneMapped: false
  28273. }));
  28274. this.line.matrixAutoUpdate = false;
  28275. this.add(this.line);
  28276. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28277. color: color,
  28278. toneMapped: false
  28279. }));
  28280. this.cone.matrixAutoUpdate = false;
  28281. this.add(this.cone);
  28282. this.setDirection(dir);
  28283. this.setLength(length, headLength, headWidth);
  28284. }
  28285. setDirection(dir) {
  28286. // dir is assumed to be normalized
  28287. if (dir.y > 0.99999) {
  28288. this.quaternion.set(0, 0, 0, 1);
  28289. } else if (dir.y < -0.99999) {
  28290. this.quaternion.set(1, 0, 0, 0);
  28291. } else {
  28292. _axis.set(dir.z, 0, -dir.x).normalize();
  28293. const radians = Math.acos(dir.y);
  28294. this.quaternion.setFromAxisAngle(_axis, radians);
  28295. }
  28296. }
  28297. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  28298. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28299. this.line.updateMatrix();
  28300. this.cone.scale.set(headWidth, headLength, headWidth);
  28301. this.cone.position.y = length;
  28302. this.cone.updateMatrix();
  28303. }
  28304. setColor(color) {
  28305. this.line.material.color.set(color);
  28306. this.cone.material.color.set(color);
  28307. }
  28308. copy(source) {
  28309. super.copy(source, false);
  28310. this.line.copy(source.line);
  28311. this.cone.copy(source.cone);
  28312. return this;
  28313. }
  28314. }
  28315. class AxesHelper extends LineSegments {
  28316. constructor(size = 1) {
  28317. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28318. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28319. const geometry = new BufferGeometry();
  28320. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28321. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28322. const material = new LineBasicMaterial({
  28323. vertexColors: true,
  28324. toneMapped: false
  28325. });
  28326. super(geometry, material);
  28327. this.type = 'AxesHelper';
  28328. }
  28329. setColors(xAxisColor, yAxisColor, zAxisColor) {
  28330. const color = new Color();
  28331. const array = this.geometry.attributes.color.array;
  28332. color.set(xAxisColor);
  28333. color.toArray(array, 0);
  28334. color.toArray(array, 3);
  28335. color.set(yAxisColor);
  28336. color.toArray(array, 6);
  28337. color.toArray(array, 9);
  28338. color.set(zAxisColor);
  28339. color.toArray(array, 12);
  28340. color.toArray(array, 15);
  28341. this.geometry.attributes.color.needsUpdate = true;
  28342. return this;
  28343. }
  28344. dispose() {
  28345. this.geometry.dispose();
  28346. this.material.dispose();
  28347. }
  28348. }
  28349. class ShapePath {
  28350. constructor() {
  28351. this.type = 'ShapePath';
  28352. this.color = new Color();
  28353. this.subPaths = [];
  28354. this.currentPath = null;
  28355. }
  28356. moveTo(x, y) {
  28357. this.currentPath = new Path();
  28358. this.subPaths.push(this.currentPath);
  28359. this.currentPath.moveTo(x, y);
  28360. return this;
  28361. }
  28362. lineTo(x, y) {
  28363. this.currentPath.lineTo(x, y);
  28364. return this;
  28365. }
  28366. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28367. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  28368. return this;
  28369. }
  28370. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28371. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  28372. return this;
  28373. }
  28374. splineThru(pts) {
  28375. this.currentPath.splineThru(pts);
  28376. return this;
  28377. }
  28378. toShapes(isCCW, noHoles) {
  28379. function toShapesNoHoles(inSubpaths) {
  28380. const shapes = [];
  28381. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28382. const tmpPath = inSubpaths[i];
  28383. const tmpShape = new Shape();
  28384. tmpShape.curves = tmpPath.curves;
  28385. shapes.push(tmpShape);
  28386. }
  28387. return shapes;
  28388. }
  28389. function isPointInsidePolygon(inPt, inPolygon) {
  28390. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28391. // toggling of inside/outside at every single! intersection point of an edge
  28392. // with the horizontal line through inPt, left of inPt
  28393. // not counting lowerY endpoints of edges and whole edges on that line
  28394. let inside = false;
  28395. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28396. let edgeLowPt = inPolygon[p];
  28397. let edgeHighPt = inPolygon[q];
  28398. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28399. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28400. if (Math.abs(edgeDy) > Number.EPSILON) {
  28401. // not parallel
  28402. if (edgeDy < 0) {
  28403. edgeLowPt = inPolygon[q];
  28404. edgeDx = -edgeDx;
  28405. edgeHighPt = inPolygon[p];
  28406. edgeDy = -edgeDy;
  28407. }
  28408. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28409. if (inPt.y === edgeLowPt.y) {
  28410. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28411. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28412. } else {
  28413. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28414. if (perpEdge === 0) return true; // inPt is on contour ?
  28415. if (perpEdge < 0) continue;
  28416. inside = !inside; // true intersection left of inPt
  28417. }
  28418. } else {
  28419. // parallel or collinear
  28420. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28421. // edge lies on the same horizontal line as inPt
  28422. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28423. // continue;
  28424. }
  28425. }
  28426. return inside;
  28427. }
  28428. const isClockWise = ShapeUtils.isClockWise;
  28429. const subPaths = this.subPaths;
  28430. if (subPaths.length === 0) return [];
  28431. if (noHoles === true) return toShapesNoHoles(subPaths);
  28432. let solid, tmpPath, tmpShape;
  28433. const shapes = [];
  28434. if (subPaths.length === 1) {
  28435. tmpPath = subPaths[0];
  28436. tmpShape = new Shape();
  28437. tmpShape.curves = tmpPath.curves;
  28438. shapes.push(tmpShape);
  28439. return shapes;
  28440. }
  28441. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28442. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28443. const betterShapeHoles = [];
  28444. const newShapes = [];
  28445. let newShapeHoles = [];
  28446. let mainIdx = 0;
  28447. let tmpPoints;
  28448. newShapes[mainIdx] = undefined;
  28449. newShapeHoles[mainIdx] = [];
  28450. for (let i = 0, l = subPaths.length; i < l; i++) {
  28451. tmpPath = subPaths[i];
  28452. tmpPoints = tmpPath.getPoints();
  28453. solid = isClockWise(tmpPoints);
  28454. solid = isCCW ? !solid : solid;
  28455. if (solid) {
  28456. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28457. newShapes[mainIdx] = {
  28458. s: new Shape(),
  28459. p: tmpPoints
  28460. };
  28461. newShapes[mainIdx].s.curves = tmpPath.curves;
  28462. if (holesFirst) mainIdx++;
  28463. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28464. } else {
  28465. newShapeHoles[mainIdx].push({
  28466. h: tmpPath,
  28467. p: tmpPoints[0]
  28468. }); //console.log('ccw', i);
  28469. }
  28470. } // only Holes? -> probably all Shapes with wrong orientation
  28471. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28472. if (newShapes.length > 1) {
  28473. let ambiguous = false;
  28474. let toChange = 0;
  28475. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28476. betterShapeHoles[sIdx] = [];
  28477. }
  28478. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28479. const sho = newShapeHoles[sIdx];
  28480. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28481. const ho = sho[hIdx];
  28482. let hole_unassigned = true;
  28483. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28484. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28485. if (sIdx !== s2Idx) toChange++;
  28486. if (hole_unassigned) {
  28487. hole_unassigned = false;
  28488. betterShapeHoles[s2Idx].push(ho);
  28489. } else {
  28490. ambiguous = true;
  28491. }
  28492. }
  28493. }
  28494. if (hole_unassigned) {
  28495. betterShapeHoles[sIdx].push(ho);
  28496. }
  28497. }
  28498. }
  28499. if (toChange > 0 && ambiguous === false) {
  28500. newShapeHoles = betterShapeHoles;
  28501. }
  28502. }
  28503. let tmpHoles;
  28504. for (let i = 0, il = newShapes.length; i < il; i++) {
  28505. tmpShape = newShapes[i].s;
  28506. shapes.push(tmpShape);
  28507. tmpHoles = newShapeHoles[i];
  28508. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28509. tmpShape.holes.push(tmpHoles[j].h);
  28510. }
  28511. } //console.log("shape", shapes);
  28512. return shapes;
  28513. }
  28514. }
  28515. const _tables = /*@__PURE__*/_generateTables();
  28516. function _generateTables() {
  28517. // float32 to float16 helpers
  28518. const buffer = new ArrayBuffer(4);
  28519. const floatView = new Float32Array(buffer);
  28520. const uint32View = new Uint32Array(buffer);
  28521. const baseTable = new Uint32Array(512);
  28522. const shiftTable = new Uint32Array(512);
  28523. for (let i = 0; i < 256; ++i) {
  28524. const e = i - 127; // very small number (0, -0)
  28525. if (e < -27) {
  28526. baseTable[i] = 0x0000;
  28527. baseTable[i | 0x100] = 0x8000;
  28528. shiftTable[i] = 24;
  28529. shiftTable[i | 0x100] = 24; // small number (denorm)
  28530. } else if (e < -14) {
  28531. baseTable[i] = 0x0400 >> -e - 14;
  28532. baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  28533. shiftTable[i] = -e - 1;
  28534. shiftTable[i | 0x100] = -e - 1; // normal number
  28535. } else if (e <= 15) {
  28536. baseTable[i] = e + 15 << 10;
  28537. baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  28538. shiftTable[i] = 13;
  28539. shiftTable[i | 0x100] = 13; // large number (Infinity, -Infinity)
  28540. } else if (e < 128) {
  28541. baseTable[i] = 0x7c00;
  28542. baseTable[i | 0x100] = 0xfc00;
  28543. shiftTable[i] = 24;
  28544. shiftTable[i | 0x100] = 24; // stay (NaN, Infinity, -Infinity)
  28545. } else {
  28546. baseTable[i] = 0x7c00;
  28547. baseTable[i | 0x100] = 0xfc00;
  28548. shiftTable[i] = 13;
  28549. shiftTable[i | 0x100] = 13;
  28550. }
  28551. } // float16 to float32 helpers
  28552. const mantissaTable = new Uint32Array(2048);
  28553. const exponentTable = new Uint32Array(64);
  28554. const offsetTable = new Uint32Array(64);
  28555. for (let i = 1; i < 1024; ++i) {
  28556. let m = i << 13; // zero pad mantissa bits
  28557. let e = 0; // zero exponent
  28558. // normalized
  28559. while ((m & 0x00800000) === 0) {
  28560. m <<= 1;
  28561. e -= 0x00800000; // decrement exponent
  28562. }
  28563. m &= ~0x00800000; // clear leading 1 bit
  28564. e += 0x38800000; // adjust bias
  28565. mantissaTable[i] = m | e;
  28566. }
  28567. for (let i = 1024; i < 2048; ++i) {
  28568. mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  28569. }
  28570. for (let i = 1; i < 31; ++i) {
  28571. exponentTable[i] = i << 23;
  28572. }
  28573. exponentTable[31] = 0x47800000;
  28574. exponentTable[32] = 0x80000000;
  28575. for (let i = 33; i < 63; ++i) {
  28576. exponentTable[i] = 0x80000000 + (i - 32 << 23);
  28577. }
  28578. exponentTable[63] = 0xc7800000;
  28579. for (let i = 1; i < 64; ++i) {
  28580. if (i !== 32) {
  28581. offsetTable[i] = 1024;
  28582. }
  28583. }
  28584. return {
  28585. floatView: floatView,
  28586. uint32View: uint32View,
  28587. baseTable: baseTable,
  28588. shiftTable: shiftTable,
  28589. mantissaTable: mantissaTable,
  28590. exponentTable: exponentTable,
  28591. offsetTable: offsetTable
  28592. };
  28593. } // float32 to float16
  28594. function toHalfFloat(val) {
  28595. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  28596. val = clamp(val, -65504, 65504);
  28597. _tables.floatView[0] = val;
  28598. const f = _tables.uint32View[0];
  28599. const e = f >> 23 & 0x1ff;
  28600. return _tables.baseTable[e] + ((f & 0x007fffff) >> _tables.shiftTable[e]);
  28601. } // float16 to float32
  28602. function fromHalfFloat(val) {
  28603. const m = val >> 10;
  28604. _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 0x3ff)] + _tables.exponentTable[m];
  28605. return _tables.floatView[0];
  28606. }
  28607. var DataUtils = /*#__PURE__*/Object.freeze({
  28608. __proto__: null,
  28609. toHalfFloat: toHalfFloat,
  28610. fromHalfFloat: fromHalfFloat
  28611. });
  28612. function ImmediateRenderObject() {
  28613. console.error('THREE.ImmediateRenderObject has been removed.');
  28614. } // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  28615. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  28616. constructor(width, height, options) {
  28617. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  28618. super(width, height, options);
  28619. this.samples = 4;
  28620. }
  28621. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28622. class DataTexture2DArray extends DataArrayTexture {
  28623. constructor(data, width, height, depth) {
  28624. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  28625. super(data, width, height, depth);
  28626. }
  28627. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28628. class DataTexture3D extends Data3DTexture {
  28629. constructor(data, width, height, depth) {
  28630. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  28631. super(data, width, height, depth);
  28632. }
  28633. } // r144
  28634. class BoxBufferGeometry extends BoxGeometry {
  28635. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  28636. console.warn('THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.');
  28637. super(width, height, depth, widthSegments, heightSegments, depthSegments);
  28638. }
  28639. } // r144
  28640. class CapsuleBufferGeometry extends CapsuleGeometry {
  28641. constructor(radius, length, capSegments, radialSegments) {
  28642. console.warn('THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.');
  28643. super(radius, length, capSegments, radialSegments);
  28644. }
  28645. } // r144
  28646. class CircleBufferGeometry extends CircleGeometry {
  28647. constructor(radius, segments, thetaStart, thetaLength) {
  28648. console.warn('THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.');
  28649. super(radius, segments, thetaStart, thetaLength);
  28650. }
  28651. } // r144
  28652. class ConeBufferGeometry extends ConeGeometry {
  28653. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  28654. console.warn('THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.');
  28655. super(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  28656. }
  28657. } // r144
  28658. class CylinderBufferGeometry extends CylinderGeometry {
  28659. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  28660. console.warn('THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.');
  28661. super(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  28662. }
  28663. } // r144
  28664. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  28665. constructor(radius, detail) {
  28666. console.warn('THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.');
  28667. super(radius, detail);
  28668. }
  28669. } // r144
  28670. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  28671. constructor(shapes, options) {
  28672. console.warn('THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.');
  28673. super(shapes, options);
  28674. }
  28675. } // r144
  28676. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  28677. constructor(radius, detail) {
  28678. console.warn('THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.');
  28679. super(radius, detail);
  28680. }
  28681. } // r144
  28682. class LatheBufferGeometry extends LatheGeometry {
  28683. constructor(points, segments, phiStart, phiLength) {
  28684. console.warn('THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.');
  28685. super(points, segments, phiStart, phiLength);
  28686. }
  28687. } // r144
  28688. class OctahedronBufferGeometry extends OctahedronGeometry {
  28689. constructor(radius, detail) {
  28690. console.warn('THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.');
  28691. super(radius, detail);
  28692. }
  28693. } // r144
  28694. class PlaneBufferGeometry extends PlaneGeometry {
  28695. constructor(width, height, widthSegments, heightSegments) {
  28696. console.warn('THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.');
  28697. super(width, height, widthSegments, heightSegments);
  28698. }
  28699. } // r144
  28700. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  28701. constructor(vertices, indices, radius, detail) {
  28702. console.warn('THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.');
  28703. super(vertices, indices, radius, detail);
  28704. }
  28705. } // r144
  28706. class RingBufferGeometry extends RingGeometry {
  28707. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  28708. console.warn('THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.');
  28709. super(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength);
  28710. }
  28711. } // r144
  28712. class ShapeBufferGeometry extends ShapeGeometry {
  28713. constructor(shapes, curveSegments) {
  28714. console.warn('THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.');
  28715. super(shapes, curveSegments);
  28716. }
  28717. } // r144
  28718. class SphereBufferGeometry extends SphereGeometry {
  28719. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  28720. console.warn('THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.');
  28721. super(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength);
  28722. }
  28723. } // r144
  28724. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  28725. constructor(radius, detail) {
  28726. console.warn('THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.');
  28727. super(radius, detail);
  28728. }
  28729. } // r144
  28730. class TorusBufferGeometry extends TorusGeometry {
  28731. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  28732. console.warn('THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.');
  28733. super(radius, tube, radialSegments, tubularSegments, arc);
  28734. }
  28735. } // r144
  28736. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  28737. constructor(radius, tube, tubularSegments, radialSegments, p, q) {
  28738. console.warn('THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.');
  28739. super(radius, tube, tubularSegments, radialSegments, p, q);
  28740. }
  28741. } // r144
  28742. class TubeBufferGeometry extends TubeGeometry {
  28743. constructor(path, tubularSegments, radius, radialSegments, closed) {
  28744. console.warn('THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.');
  28745. super(path, tubularSegments, radius, radialSegments, closed);
  28746. }
  28747. }
  28748. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28749. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28750. detail: {
  28751. revision: REVISION
  28752. }
  28753. }));
  28754. }
  28755. if (typeof window !== 'undefined') {
  28756. if (window.__THREE__) {
  28757. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28758. } else {
  28759. window.__THREE__ = REVISION;
  28760. }
  28761. }
  28762. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28763. exports.AddEquation = AddEquation;
  28764. exports.AddOperation = AddOperation;
  28765. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28766. exports.AdditiveBlending = AdditiveBlending;
  28767. exports.AlphaFormat = AlphaFormat;
  28768. exports.AlwaysDepth = AlwaysDepth;
  28769. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28770. exports.AmbientLight = AmbientLight;
  28771. exports.AmbientLightProbe = AmbientLightProbe;
  28772. exports.AnimationClip = AnimationClip;
  28773. exports.AnimationLoader = AnimationLoader;
  28774. exports.AnimationMixer = AnimationMixer;
  28775. exports.AnimationObjectGroup = AnimationObjectGroup;
  28776. exports.AnimationUtils = AnimationUtils;
  28777. exports.ArcCurve = ArcCurve;
  28778. exports.ArrayCamera = ArrayCamera;
  28779. exports.ArrowHelper = ArrowHelper;
  28780. exports.Audio = Audio;
  28781. exports.AudioAnalyser = AudioAnalyser;
  28782. exports.AudioContext = AudioContext;
  28783. exports.AudioListener = AudioListener;
  28784. exports.AudioLoader = AudioLoader;
  28785. exports.AxesHelper = AxesHelper;
  28786. exports.BackSide = BackSide;
  28787. exports.BasicDepthPacking = BasicDepthPacking;
  28788. exports.BasicShadowMap = BasicShadowMap;
  28789. exports.Bone = Bone;
  28790. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28791. exports.Box2 = Box2;
  28792. exports.Box3 = Box3;
  28793. exports.Box3Helper = Box3Helper;
  28794. exports.BoxBufferGeometry = BoxBufferGeometry;
  28795. exports.BoxGeometry = BoxGeometry;
  28796. exports.BoxHelper = BoxHelper;
  28797. exports.BufferAttribute = BufferAttribute;
  28798. exports.BufferGeometry = BufferGeometry;
  28799. exports.BufferGeometryLoader = BufferGeometryLoader;
  28800. exports.ByteType = ByteType;
  28801. exports.Cache = Cache;
  28802. exports.Camera = Camera;
  28803. exports.CameraHelper = CameraHelper;
  28804. exports.CanvasTexture = CanvasTexture;
  28805. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  28806. exports.CapsuleGeometry = CapsuleGeometry;
  28807. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28808. exports.CineonToneMapping = CineonToneMapping;
  28809. exports.CircleBufferGeometry = CircleBufferGeometry;
  28810. exports.CircleGeometry = CircleGeometry;
  28811. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28812. exports.Clock = Clock;
  28813. exports.Color = Color;
  28814. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28815. exports.ColorManagement = ColorManagement;
  28816. exports.CompressedTexture = CompressedTexture;
  28817. exports.CompressedTextureLoader = CompressedTextureLoader;
  28818. exports.ConeBufferGeometry = ConeBufferGeometry;
  28819. exports.ConeGeometry = ConeGeometry;
  28820. exports.CubeCamera = CubeCamera;
  28821. exports.CubeReflectionMapping = CubeReflectionMapping;
  28822. exports.CubeRefractionMapping = CubeRefractionMapping;
  28823. exports.CubeTexture = CubeTexture;
  28824. exports.CubeTextureLoader = CubeTextureLoader;
  28825. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28826. exports.CubicBezierCurve = CubicBezierCurve;
  28827. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28828. exports.CubicInterpolant = CubicInterpolant;
  28829. exports.CullFaceBack = CullFaceBack;
  28830. exports.CullFaceFront = CullFaceFront;
  28831. exports.CullFaceFrontBack = CullFaceFrontBack;
  28832. exports.CullFaceNone = CullFaceNone;
  28833. exports.Curve = Curve;
  28834. exports.CurvePath = CurvePath;
  28835. exports.CustomBlending = CustomBlending;
  28836. exports.CustomToneMapping = CustomToneMapping;
  28837. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  28838. exports.CylinderGeometry = CylinderGeometry;
  28839. exports.Cylindrical = Cylindrical;
  28840. exports.Data3DTexture = Data3DTexture;
  28841. exports.DataArrayTexture = DataArrayTexture;
  28842. exports.DataTexture = DataTexture;
  28843. exports.DataTexture2DArray = DataTexture2DArray;
  28844. exports.DataTexture3D = DataTexture3D;
  28845. exports.DataTextureLoader = DataTextureLoader;
  28846. exports.DataUtils = DataUtils;
  28847. exports.DecrementStencilOp = DecrementStencilOp;
  28848. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28849. exports.DefaultLoadingManager = DefaultLoadingManager;
  28850. exports.DepthFormat = DepthFormat;
  28851. exports.DepthStencilFormat = DepthStencilFormat;
  28852. exports.DepthTexture = DepthTexture;
  28853. exports.DirectionalLight = DirectionalLight;
  28854. exports.DirectionalLightHelper = DirectionalLightHelper;
  28855. exports.DiscreteInterpolant = DiscreteInterpolant;
  28856. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  28857. exports.DodecahedronGeometry = DodecahedronGeometry;
  28858. exports.DoubleSide = DoubleSide;
  28859. exports.DstAlphaFactor = DstAlphaFactor;
  28860. exports.DstColorFactor = DstColorFactor;
  28861. exports.DynamicCopyUsage = DynamicCopyUsage;
  28862. exports.DynamicDrawUsage = DynamicDrawUsage;
  28863. exports.DynamicReadUsage = DynamicReadUsage;
  28864. exports.EdgesGeometry = EdgesGeometry;
  28865. exports.EllipseCurve = EllipseCurve;
  28866. exports.EqualDepth = EqualDepth;
  28867. exports.EqualStencilFunc = EqualStencilFunc;
  28868. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28869. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28870. exports.Euler = Euler;
  28871. exports.EventDispatcher = EventDispatcher;
  28872. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  28873. exports.ExtrudeGeometry = ExtrudeGeometry;
  28874. exports.FileLoader = FileLoader;
  28875. exports.Float16BufferAttribute = Float16BufferAttribute;
  28876. exports.Float32BufferAttribute = Float32BufferAttribute;
  28877. exports.Float64BufferAttribute = Float64BufferAttribute;
  28878. exports.FloatType = FloatType;
  28879. exports.Fog = Fog;
  28880. exports.FogExp2 = FogExp2;
  28881. exports.FramebufferTexture = FramebufferTexture;
  28882. exports.FrontSide = FrontSide;
  28883. exports.Frustum = Frustum;
  28884. exports.GLBufferAttribute = GLBufferAttribute;
  28885. exports.GLSL1 = GLSL1;
  28886. exports.GLSL3 = GLSL3;
  28887. exports.GreaterDepth = GreaterDepth;
  28888. exports.GreaterEqualDepth = GreaterEqualDepth;
  28889. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28890. exports.GreaterStencilFunc = GreaterStencilFunc;
  28891. exports.GridHelper = GridHelper;
  28892. exports.Group = Group;
  28893. exports.HalfFloatType = HalfFloatType;
  28894. exports.HemisphereLight = HemisphereLight;
  28895. exports.HemisphereLightHelper = HemisphereLightHelper;
  28896. exports.HemisphereLightProbe = HemisphereLightProbe;
  28897. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  28898. exports.IcosahedronGeometry = IcosahedronGeometry;
  28899. exports.ImageBitmapLoader = ImageBitmapLoader;
  28900. exports.ImageLoader = ImageLoader;
  28901. exports.ImageUtils = ImageUtils;
  28902. exports.ImmediateRenderObject = ImmediateRenderObject;
  28903. exports.IncrementStencilOp = IncrementStencilOp;
  28904. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28905. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28906. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28907. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28908. exports.InstancedMesh = InstancedMesh;
  28909. exports.Int16BufferAttribute = Int16BufferAttribute;
  28910. exports.Int32BufferAttribute = Int32BufferAttribute;
  28911. exports.Int8BufferAttribute = Int8BufferAttribute;
  28912. exports.IntType = IntType;
  28913. exports.InterleavedBuffer = InterleavedBuffer;
  28914. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28915. exports.Interpolant = Interpolant;
  28916. exports.InterpolateDiscrete = InterpolateDiscrete;
  28917. exports.InterpolateLinear = InterpolateLinear;
  28918. exports.InterpolateSmooth = InterpolateSmooth;
  28919. exports.InvertStencilOp = InvertStencilOp;
  28920. exports.KeepStencilOp = KeepStencilOp;
  28921. exports.KeyframeTrack = KeyframeTrack;
  28922. exports.LOD = LOD;
  28923. exports.LatheBufferGeometry = LatheBufferGeometry;
  28924. exports.LatheGeometry = LatheGeometry;
  28925. exports.Layers = Layers;
  28926. exports.LessDepth = LessDepth;
  28927. exports.LessEqualDepth = LessEqualDepth;
  28928. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28929. exports.LessStencilFunc = LessStencilFunc;
  28930. exports.Light = Light;
  28931. exports.LightProbe = LightProbe;
  28932. exports.Line = Line;
  28933. exports.Line3 = Line3;
  28934. exports.LineBasicMaterial = LineBasicMaterial;
  28935. exports.LineCurve = LineCurve;
  28936. exports.LineCurve3 = LineCurve3;
  28937. exports.LineDashedMaterial = LineDashedMaterial;
  28938. exports.LineLoop = LineLoop;
  28939. exports.LineSegments = LineSegments;
  28940. exports.LinearEncoding = LinearEncoding;
  28941. exports.LinearFilter = LinearFilter;
  28942. exports.LinearInterpolant = LinearInterpolant;
  28943. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28944. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28945. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28946. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28947. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  28948. exports.LinearToneMapping = LinearToneMapping;
  28949. exports.Loader = Loader;
  28950. exports.LoaderUtils = LoaderUtils;
  28951. exports.LoadingManager = LoadingManager;
  28952. exports.LoopOnce = LoopOnce;
  28953. exports.LoopPingPong = LoopPingPong;
  28954. exports.LoopRepeat = LoopRepeat;
  28955. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28956. exports.LuminanceFormat = LuminanceFormat;
  28957. exports.MOUSE = MOUSE;
  28958. exports.Material = Material;
  28959. exports.MaterialLoader = MaterialLoader;
  28960. exports.MathUtils = MathUtils;
  28961. exports.Matrix3 = Matrix3;
  28962. exports.Matrix4 = Matrix4;
  28963. exports.MaxEquation = MaxEquation;
  28964. exports.Mesh = Mesh;
  28965. exports.MeshBasicMaterial = MeshBasicMaterial;
  28966. exports.MeshDepthMaterial = MeshDepthMaterial;
  28967. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28968. exports.MeshLambertMaterial = MeshLambertMaterial;
  28969. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28970. exports.MeshNormalMaterial = MeshNormalMaterial;
  28971. exports.MeshPhongMaterial = MeshPhongMaterial;
  28972. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28973. exports.MeshStandardMaterial = MeshStandardMaterial;
  28974. exports.MeshToonMaterial = MeshToonMaterial;
  28975. exports.MinEquation = MinEquation;
  28976. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28977. exports.MixOperation = MixOperation;
  28978. exports.MultiplyBlending = MultiplyBlending;
  28979. exports.MultiplyOperation = MultiplyOperation;
  28980. exports.NearestFilter = NearestFilter;
  28981. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28982. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28983. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28984. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28985. exports.NeverDepth = NeverDepth;
  28986. exports.NeverStencilFunc = NeverStencilFunc;
  28987. exports.NoBlending = NoBlending;
  28988. exports.NoColorSpace = NoColorSpace;
  28989. exports.NoToneMapping = NoToneMapping;
  28990. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28991. exports.NormalBlending = NormalBlending;
  28992. exports.NotEqualDepth = NotEqualDepth;
  28993. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28994. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28995. exports.Object3D = Object3D;
  28996. exports.ObjectLoader = ObjectLoader;
  28997. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28998. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  28999. exports.OctahedronGeometry = OctahedronGeometry;
  29000. exports.OneFactor = OneFactor;
  29001. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29002. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29003. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29004. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29005. exports.OrthographicCamera = OrthographicCamera;
  29006. exports.PCFShadowMap = PCFShadowMap;
  29007. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29008. exports.PMREMGenerator = PMREMGenerator;
  29009. exports.Path = Path;
  29010. exports.PerspectiveCamera = PerspectiveCamera;
  29011. exports.Plane = Plane;
  29012. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  29013. exports.PlaneGeometry = PlaneGeometry;
  29014. exports.PlaneHelper = PlaneHelper;
  29015. exports.PointLight = PointLight;
  29016. exports.PointLightHelper = PointLightHelper;
  29017. exports.Points = Points;
  29018. exports.PointsMaterial = PointsMaterial;
  29019. exports.PolarGridHelper = PolarGridHelper;
  29020. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  29021. exports.PolyhedronGeometry = PolyhedronGeometry;
  29022. exports.PositionalAudio = PositionalAudio;
  29023. exports.PropertyBinding = PropertyBinding;
  29024. exports.PropertyMixer = PropertyMixer;
  29025. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29026. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29027. exports.Quaternion = Quaternion;
  29028. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29029. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29030. exports.REVISION = REVISION;
  29031. exports.RGBADepthPacking = RGBADepthPacking;
  29032. exports.RGBAFormat = RGBAFormat;
  29033. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29034. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29035. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29036. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29037. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29038. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29039. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29040. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29041. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29042. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29043. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29044. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29045. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29046. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29047. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29048. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29049. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29050. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29051. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29052. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29053. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29054. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29055. exports.RGBFormat = RGBFormat;
  29056. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29057. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29058. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29059. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29060. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29061. exports.RGFormat = RGFormat;
  29062. exports.RGIntegerFormat = RGIntegerFormat;
  29063. exports.RawShaderMaterial = RawShaderMaterial;
  29064. exports.Ray = Ray;
  29065. exports.Raycaster = Raycaster;
  29066. exports.RectAreaLight = RectAreaLight;
  29067. exports.RedFormat = RedFormat;
  29068. exports.RedIntegerFormat = RedIntegerFormat;
  29069. exports.ReinhardToneMapping = ReinhardToneMapping;
  29070. exports.RepeatWrapping = RepeatWrapping;
  29071. exports.ReplaceStencilOp = ReplaceStencilOp;
  29072. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29073. exports.RingBufferGeometry = RingBufferGeometry;
  29074. exports.RingGeometry = RingGeometry;
  29075. exports.SRGBColorSpace = SRGBColorSpace;
  29076. exports.Scene = Scene;
  29077. exports.ShaderChunk = ShaderChunk;
  29078. exports.ShaderLib = ShaderLib;
  29079. exports.ShaderMaterial = ShaderMaterial;
  29080. exports.ShadowMaterial = ShadowMaterial;
  29081. exports.Shape = Shape;
  29082. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  29083. exports.ShapeGeometry = ShapeGeometry;
  29084. exports.ShapePath = ShapePath;
  29085. exports.ShapeUtils = ShapeUtils;
  29086. exports.ShortType = ShortType;
  29087. exports.Skeleton = Skeleton;
  29088. exports.SkeletonHelper = SkeletonHelper;
  29089. exports.SkinnedMesh = SkinnedMesh;
  29090. exports.Source = Source;
  29091. exports.Sphere = Sphere;
  29092. exports.SphereBufferGeometry = SphereBufferGeometry;
  29093. exports.SphereGeometry = SphereGeometry;
  29094. exports.Spherical = Spherical;
  29095. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29096. exports.SplineCurve = SplineCurve;
  29097. exports.SpotLight = SpotLight;
  29098. exports.SpotLightHelper = SpotLightHelper;
  29099. exports.Sprite = Sprite;
  29100. exports.SpriteMaterial = SpriteMaterial;
  29101. exports.SrcAlphaFactor = SrcAlphaFactor;
  29102. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29103. exports.SrcColorFactor = SrcColorFactor;
  29104. exports.StaticCopyUsage = StaticCopyUsage;
  29105. exports.StaticDrawUsage = StaticDrawUsage;
  29106. exports.StaticReadUsage = StaticReadUsage;
  29107. exports.StereoCamera = StereoCamera;
  29108. exports.StreamCopyUsage = StreamCopyUsage;
  29109. exports.StreamDrawUsage = StreamDrawUsage;
  29110. exports.StreamReadUsage = StreamReadUsage;
  29111. exports.StringKeyframeTrack = StringKeyframeTrack;
  29112. exports.SubtractEquation = SubtractEquation;
  29113. exports.SubtractiveBlending = SubtractiveBlending;
  29114. exports.TOUCH = TOUCH;
  29115. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29116. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  29117. exports.TetrahedronGeometry = TetrahedronGeometry;
  29118. exports.Texture = Texture;
  29119. exports.TextureLoader = TextureLoader;
  29120. exports.TorusBufferGeometry = TorusBufferGeometry;
  29121. exports.TorusGeometry = TorusGeometry;
  29122. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  29123. exports.TorusKnotGeometry = TorusKnotGeometry;
  29124. exports.Triangle = Triangle;
  29125. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29126. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29127. exports.TrianglesDrawMode = TrianglesDrawMode;
  29128. exports.TubeBufferGeometry = TubeBufferGeometry;
  29129. exports.TubeGeometry = TubeGeometry;
  29130. exports.UVMapping = UVMapping;
  29131. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29132. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29133. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29134. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29135. exports.Uniform = Uniform;
  29136. exports.UniformsGroup = UniformsGroup;
  29137. exports.UniformsLib = UniformsLib;
  29138. exports.UniformsUtils = UniformsUtils;
  29139. exports.UnsignedByteType = UnsignedByteType;
  29140. exports.UnsignedInt248Type = UnsignedInt248Type;
  29141. exports.UnsignedIntType = UnsignedIntType;
  29142. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29143. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29144. exports.UnsignedShortType = UnsignedShortType;
  29145. exports.VSMShadowMap = VSMShadowMap;
  29146. exports.Vector2 = Vector2;
  29147. exports.Vector3 = Vector3;
  29148. exports.Vector4 = Vector4;
  29149. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29150. exports.VideoTexture = VideoTexture;
  29151. exports.WebGL1Renderer = WebGL1Renderer;
  29152. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  29153. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  29154. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29155. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29156. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29157. exports.WebGLRenderTarget = WebGLRenderTarget;
  29158. exports.WebGLRenderer = WebGLRenderer;
  29159. exports.WebGLUtils = WebGLUtils;
  29160. exports.WireframeGeometry = WireframeGeometry;
  29161. exports.WrapAroundEnding = WrapAroundEnding;
  29162. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29163. exports.ZeroFactor = ZeroFactor;
  29164. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29165. exports.ZeroStencilOp = ZeroStencilOp;
  29166. exports._SRGBAFormat = _SRGBAFormat;
  29167. exports.sRGBEncoding = sRGBEncoding;